openCV video saving in python
Try this. It's working for me (Windows 10).
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
#fourcc = cv2.cv.CV_FOURCC(*'DIVX')
#out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
How to save a video after changing its speed with opencv in your folder?
You can use the fps parameter of the cv2.VideoWriter()
method. The fps can be calculated by simple diving your frameTime
variable by 1000
, as the cv2.waitKey()
method takes in a number and uses it as a thousandth of a second.
Note that if the cap
never closed during the while
loop, the while cap.isOpened()
won't be any better than while True
, meaning by the time the last frame is read, an error would occur, causing the writer.release()
method to never be called, thus making the resulting file unreadable.
Here is how I would do it:
import cv2
cap = cv2.VideoCapture('Pothole testing.mp4')
ret, frame = cap.read() # Get one ret and frame
h, w, _ = frame.shape # Use frame to get width and height
frameTime = 100
fourcc = cv2.VideoWriter_fourcc(*"XVID") # XVID is the ID, can be changed to anything
fps = 1000 / frameTime # Calculate fps
writer = cv2.VideoWriter("Pothole testing 2.mp4", fourcc, fps, (w, h)) # Video writing device
while ret: # Use the ret to determin end of video
writer.write(frame) # Write frame
cv2.imshow("frame", frame)
if cv2.waitKey(frameTime) & 0xFF == ord('q'):
break
ret, frame = cap.read()
writer.release()
cap.release()
cv2.destroyAllWindows()
If all you need is the resulting file and not the progress window, you can omit a few lines:
import cv2
cap = cv2.VideoCapture('Pothole testing.mp4')
ret, frame = cap.read()
h, w, _ = frame.shape
frameTime = 100
fourcc = cv2.VideoWriter_fourcc(*"XVID")
fps = 1000 / frameTime
writer = cv2.VideoWriter("Pothole testing 2.mp4", fourcc, fps, (w, h))
while ret:
writer.write(frame)
ret, frame = cap.read()
writer.release()
cap.release()
How can i save a frame in a live video using opencv in python?
You can use imwrite function from your opencv to extract the current frame.
You can also add time and convert it to string for naming purpose for the output file.
import time as t
LiveVideo = VideoStream(src=0).start()
while True:
frame = LiveVideo.read()
timestr = t.strftime("%Y%m%d-%H%M%S")
cv2.imwrite("frame%s.jpg" % timestr, frame )
How to save a video in Python OpenCV
You can save video frame by frame. Based on example on docs:
Open Cv video capture
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
How to save specific parts of video into separate videos using opencv in python?
Here is how I would do it:
import cv2
file = "video.avi"
parts = [(15, 30), (50, 79)]
cap = cv2.VideoCapture(file)
ret, frame = cap.read()
h, w, _ = frame.shape
fourcc = cv2.VideoWriter_fourcc(*"XVID")
writers = [cv2.VideoWriter(f"part{start}-{end}.avi", fourcc, 20.0, (w, h)) for start, end in parts]
f = 0
while ret:
f += 1
for i, part in enumerate(parts):
start, end = part
if start <= f <= end:
writers[i].write(frame)
ret, frame = cap.read()
for writer in writers:
writer.release()
cap.release()
Explanation:
- Import the
cv2
module, define the name of the video file and the parts of the file you want to save into different video files:
import cv2
file = "video.avi"
parts = [(15, 30), (50, 79)]
- Define a video capture device to read frames from the video file and read from it once to get the shape of the frames of the video:
cap = cv2.VideoCapture(file)
ret, frame = cap.read()
h, w, _ = frame.shape
- Define a fourcc (four-character code), and define a list of video writers; one for every video you want to generate:
fourcc = cv2.VideoWriter_fourcc(*"XVID")
writers = [cv2.VideoWriter(f"part{start}-{end}.avi", fourcc, 20.0, (w, h)) for start, end in parts]
- Define a
while
loop, but before that, define a variable to keep track of which frame the while loop is at in the capture device:
f = 0
while ret:
f += 1
- Using a
for
loop inside thewhile
loop, loop through the start and end frames of the parts, using theenumerate
method to allow the program to access the index of the parts each iteration is at when needed. If the variable defined before thewhile
loop is between (inclusive) the start and end of the part, write that frame to the corresponding video writer (using the index provided by theenumerate
method):
for i, (start, end) in enumerate(parts):
if start <= f <= end:
writers[i].write(frame)
ret, frame = cap.read()
- Finally, release all the video writers and the capture device:
for writer in writers:
writer.release()
cap.release()
Can't save a video in opencv
The problem is that the video codec and the video container format do not match.
When executing your code, I am getting an error message (in the console windows):
OpenCV: FFMPEG: tag 0x3234504d/'MP42' is not supported with codec id 15 and format 'mp4 / MP4 (MPEG-4 Part 14)'
[mp4 @ 00000155e95dcec0] Could not find tag for codec msmpeg4v2 in stream #0, codec not currently supported in container
- You are using
fourcc = cv2.VideoWriter_fourcc(*'MP42')
, andM420
applies video codec MPEG-4v2. - Video output file name is
'output.mp4'
.
The.mp4
extension applies MP4 container format.
Apparently .mp4
video file cannot contain video encoded with MPEG-4v2
codec.
You may either change codec, or change file format.
Example:
- Changing output file name to
'output.avi'
or'output.wmv'
works. - Changing the codec to
MPEG-4
:fourcc = cv2.VideoWriter_fourcc(*'mp4v')
(and keeping file name'output.mp4'
) also works.
One more issue:
Add the following code after ret, frame = cap.read()
:
if not ret:
break;
Related Topics
How to Set the Default Color Cycle for All Subplots with Matplotlib
Running Jupyter via Command Line on Windows
Python SQLite Parameter Substitution with Wildcards in Like
Class Inheritance in Python 3.7 Dataclasses
Installing Numpy with Pip on Windows 10 for Python 3.7
Differencebetween an Opencv Bgr Image and Its Reverse Version Rgb Image[:,:,::-1]
Generating File to Download with Django
Opencv - Apply Mask to a Color Image
How to Initialize Weights in Pytorch
How to Check If a String Only Contains Letters
How to Check That Multiple Keys Are in a Dict in a Single Pass
Cancel an Already Executing Task with Celery
Shipping Python Modules in Pyspark to Other Nodes
<Django Object > Is Not JSON Serializable
Understanding String Reversal via Slicing
Running an Interactive Command from Within Python
Unique Combinations of Values in Selected Columns in Pandas Data Frame and Count