I'm trying to read a video, put some shapes on it and write it out using opencv-python (using VideoWriter class):
def Mask_info(path):
"""This function will mask the information part of the video"""
video = cv.VideoCapture(path)
framenum = video.get(cv.CAP_PROP_FRAME_COUNT)
fps = video.get(cv.CAP_PROP_FPS)
fourcc = cv.VideoWriter_fourcc(*"vp09")
width = int(video.get(cv.CAP_PROP_FRAME_WIDTH))
height = int(video.get(cv.CAP_PROP_FRAME_HEIGHT))
size = (width,height)
if (video.isOpened ==False ):
print("Error while reading the file.")
result = cv.VideoWriter("masked_video.mp4",fourcc,fps,size)
while(True):
isTrue,frame = video.read()
cv.rectangle(frame,(65,0),(255,10),(0,0,0),-1)
cv.rectangle(frame,(394,0),(571,10),(0,0,0),-1)
if isTrue == True:
result.write(frame)
cv.imshow("Masked Video",frame)
if cv.waitKey(1) & 0xFF == ord("d"):
break
else:
break
video.release()
result.release()
cv.destroyAllWindows()
Mask_info("samplesound.webm")
The problem is that the output video length is zero, while the input video is 10 seconds.
To elaborate on my comment above:
You should verify that video.read() returns any valid frame.
It could be that due to path or other issue the VideoCapture failed to open the input file.
You attempt to draw the rectangles (using cv.rectangle) before the if that checks whether you have a valid frame.
But if video.read() failed (e.g. when reaching the end of the input) frame will be None. Then cv.rectangle will throw an exception causing the program to terminate without flushing and closing the output file.
Instead you should do the drawings inside the isTrue == True branch of the if:
if isTrue == True:
cv.rectangle(frame,(65,0),(255,10),(0,0,0),-1)
cv.rectangle(frame,(394,0),(571,10),(0,0,0),-1)
result.write(frame)
# ...
I have written a program that uses the web-cam to monitor a machine, and when a movement is detected, I want to save the ‘movement’-frames into a time stamped video.
However, while the program is running, the latest video is viewable, but the previous versions are corrupted.
Ex:
Files:
Movement_11_25_01.avi (corrupted)
Movement_11_28_22.avi (corrupted)
Movement_11_33_21.avi (this is the latest video created, and it is viewable.)
And then another movement is detected;
Files:
Movement_11_25_01.avi (corrupted)
Movement_11_28_22.avi (corrupted)
Movement_11_33_21.avi (corrupted)
Movement_11_35_41.avi (this is the latest video created, and it is viewable.)
This is the code that runs in the end of every motion detected:
out = cv2.VideoWriter('Results\\'+self.name, self.fourcc, self.fps, (self.frame_width, self.frame_height))
print('Len Frames before saving video: ', len(self.frames))
for frame in self.frames:
out.write(frame)
out.release()
self.cap.release()
print('Video saved.')
cv2.destroyAllWindows()
self.frames = list()
# Open up a new instance of VideoCapture
self.cap = cv2.VideoCapture(file_path, cv2.CAP_DSHOW)
I suspect that the corruption is related to how the video file is stored while the program is running, but I cannot figure out how to save a video, close the connection to that file, and then create a new file.
Any help is apprichiated!
I have tried to close the cap = cv2.VideoCapture() and the out = cv2.VideoWriter('Results\\'+self.name, self.fourcc, self.fps, (self.frame_width, self.frame_height)) by running cap.release() and
out.release() but with no success. Only when the program is terminated, a uncurrupted file is generated, and it is the most recent file.
Edit 2022-11-07:
Here is an MRE that i run on windows 10, with Python 3.10.6, together with the modules numpy (1.23.2) and opencv-python (4.6.0.66).
I have noticed that in this MRE, the first file is saved in a workable format. However, the second and third file is corrupted. The main issue is the same, but reversed.
import cv2
import numpy as np
import time
from datetime import datetime
file_path = 0
cap = cv2.VideoCapture(file_path, cv2.CAP_DSHOW) # create a capture instance
startTime = time.time() # Starttider
date_time = datetime.fromtimestamp(startTime)
frames = list()
image = list()
frame_width = int( cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height =int( cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = 30
for _ in range(3):
# Get some images
for _ in range(60):
_, frame = cap.read()
frames.append(frame)
# Initiate a video file
fourcc = cv2.VideoWriter_fourcc('X','V','I','D')
date_time = datetime.fromtimestamp(time.time())
name = "v2Motiondetect_output"+str(date_time.strftime("%d-%m-%Y__ %H_%M_%S") )+ ".avi"
out = cv2.VideoWriter(name, fourcc, fps, (frame_width, frame_height))
print('Len Frames before saving video: ', len(frames))
# Write out all frames
for frame in frames:
out.write(frame)
print('Video Capture before ending program: ', out)
print('Frames before ending program: ', id(frames))
out.release()
cap.release()
print('Video Capture after ending program: ', out)
print('Frames after ending program: ', id(frames))
frames = list()
print('frames after it is overwritten with an empty list object:', id(frames))
cv2.destroyAllWindows()
time.sleep(2) # Needed to ensure different timestamps
Aim : Detect the motion and save only the motion periods in files with names of the starting time.
Now I met the issue about how to save the video to the files with video starting time.
What I tested :
I tested my program part by part. It seems that each part works well except the saving part.
Running status: No error. But in the saving folder, there is no video. If I use a static saving path instead, the video will be saved successfully, but the video will be override by the next video. My codes are below:
import cv2
import numpy as np
import time
cap = cv2.VideoCapture( 0 )
bgst = cv2.createBackgroundSubtractorMOG2()
fourcc=cv2.VideoWriter_fourcc(*'DIVX')
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
n = "start_time"
while True:
ret, frame = cap.read()
dst = bgst.apply(frame)
dst = np.array(dst, np.int8)
if np.count_nonzero(dst)>3000: # use this value to adjust the "Sensitivity“
print('something is moving %s' %(time.ctime()))
path = r'E:\OpenCV\Motion_Detection\%s.avi' %n
out = cv2.VideoWriter( path, fourcc, 50, size )
out.write(frame)
key = cv2.waitKey(3)
if key == 32:
break
else:
out.release()
n = time.ctime()
print("No motion Detected %s" %n)
What I meant is:
import cv2
import numpy as np
import time
cap = cv2.VideoCapture( 0 )
bgst = cv2.createBackgroundSubtractorMOG2()
fourcc=cv2.VideoWriter_fourcc(*'DIVX')
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
path = r'E:\OpenCV\Motion_Detection\%s.avi' %(time.ctime())
out = cv2.VideoWriter( path, fourcc, 16, size )
while True:
ret, frame = cap.read()
dst = bgst.apply(frame)
dst = np.array(dst, np.int8)
for i in range(number of frames in the video):
if np.count_nonzero(dst)<3000: # use this value to adjust the "Sensitivity“
print("No Motion Detected")
out.release()
else:
print('something is moving %s' %(time.ctime()))
#label each frame you want to output here
out.write(frame(i))
key = cv2.waitKey(1)
if key == 32:
break
cap.release()
cv2.destroyAllWindows()
If you see the code there will be a for loop, within which the process of saving is done.
I do not know the exact syntax involving for loop with frames, but I hope you have the gist of it. You have to find the number of frames present in the video and set that as the range in the for loop.
Each frame gets saved uniquely (see the else condition.) As I said I do not know the syntax. Please refer and follow this procedure.
Cheers!
I want to capture video from a webcam and save it to an mp4 file using opencv. I found example code on stackoverflow (below) that works great. The only hitch is that I'm trying to save it as mp4, not avi. Part of what I don't get is that the 'XVID' argument passed to the FOURCC writer is supposed to be, I think, an mp4 codec (from this link). If I change the filename to 'output.mp4' it tells me that the tag is invalid, so I have to believe that the XVID codec is actually making an avi file. Is this a stupid question? How do I write to an mp4?
I have found links showing how to convert an avi to an mp4 after the fact but that seems inefficient. Seems like I should be able to do it during the initial write.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_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()
This worked for me.
self._name = name + '.mp4'
self._cap = VideoCapture(0)
self._fourcc = VideoWriter_fourcc(*'MP4V')
self._out = VideoWriter(self._name, self._fourcc, 20.0, (640,480))
What worked for me was to make sure the input 'frame' size is equal to output video's size (in this case, (680, 480) ).
http://answers.opencv.org/question/27902/how-to-record-video-using-opencv-and-python/
Here is my working code (Mac OSX Sierra 10.12.6):
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('output.mp4', fourcc, 20.0, (640,480))
while(True):
ret, frame = cap.read()
out.write(frame)
cv2.imshow('frame', frame)
c = cv2.waitKey(1)
if c & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
Note: I installed openh264 as suggested by #10SecTom but I'm not sure if that was relevant to the problem.
Just in case:
brew install openh264
There are some things to change in your code:
Change the name of your output to 'output.mp4' (change to .mp4)
I had the the same issues that people have in the comments, so I changed the fourcc to 0x7634706d: out = cv2.VideoWriter('output.mp4',0x7634706d , 20.0, (640,480))
This is the default code given to save a video captured by camera
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()
For about two minutes of a clip captured that FULL HD
Using
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
cap.set(3,1920)
cap.set(4,1080)
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (1920,1080))
The file saved was more than 150MB
Then had to use ffmpeg to reduce the size of the file saved, between 30MB to 60MB based on the quality of the video that is required changed using crf lower the crf better the quality of the video and larger the file size generated. You can also change the format avi,mp4,mkv,etc
Then i found ffmpeg-python
Here a code to save numpy array of each frame as video using ffmpeg-python
import numpy as np
import cv2
import ffmpeg
def save_video(cap,saving_file_name,fps=33.0):
while cap.isOpened():
ret, frame = cap.read()
if ret:
i_width,i_height = frame.shape[1],frame.shape[0]
break
process = (
ffmpeg
.input('pipe:',format='rawvideo', pix_fmt='rgb24',s='{}x{}'.format(i_width,i_height))
.output(saved_video_file_name,pix_fmt='yuv420p',vcodec='libx264',r=fps,crf=37)
.overwrite_output()
.run_async(pipe_stdin=True)
)
return process
if __name__=='__main__':
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
cap.set(3,1920)
cap.set(4,1080)
saved_video_file_name = 'output.avi'
process = save_video(cap,saved_video_file_name)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
process.stdin.write(
cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
.astype(np.uint8)
.tobytes()
)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
process.stdin.close()
process.wait()
cap.release()
cv2.destroyAllWindows()
break
else:
process.stdin.close()
process.wait()
cap.release()
cv2.destroyAllWindows()
break
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
'mp4v' returns no errors unlike 'MP4V' which is defined inside fourcc
for the error:
"OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id
13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to
use tag 0x00000020/' ???'"
This worked for me, I added images.sort() to keep the sequence order:
import cv2
import numpy as np
import os
image_folder = 'data-set-race-01'
video_file = 'race-01.mp4'
image_size = (160, 120)
fps = 24
images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
images.sort()
out = cv2.VideoWriter(video_file, cv2.VideoWriter_fourcc(*'MP4V'), fps, image_size)
img_array = []
for filename in images:
img = cv2.imread(os.path.join(image_folder, filename))
img_array.append(img)
out.write(img)
out.release()
For someone whoe still struggle with the problem. According this article I used this sample and it works for me:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'X264')
out = cv2.VideoWriter('output.mp4',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()
So I had to use cv2.VideoWriter_fourcc(*'X264') codec. Tested with OpenCV 3.4.3 compiled from sources.
Anyone who's looking for most convenient and robust way of writing MP4 files with OpenCV or FFmpeg, can see my state-of-the-art VidGear Video-Processing Python library's WriteGear API that works with both OpenCV backend and FFmpeg backend and even supports GPU encoders. Here's an example to encode with H264 encoder in WriteGear with FFmpeg backend:
# import required libraries
from vidgear.gears import WriteGear
import cv2
# define suitable (Codec,CRF,preset) FFmpeg parameters for writer
output_params = {"-vcodec":"libx264", "-crf": 0, "-preset": "fast"}
# Open suitable video stream, such as webcam on first index(i.e. 0)
stream = cv2.VideoCapture(0)
# Define writer with defined parameters and suitable output filename for e.g. `Output.mp4`
writer = WriteGear(output_filename = 'Output.mp4', logging = True, **output_params)
# loop over
while True:
# read frames from stream
(grabbed, frame) = stream.read()
# check for frame if not grabbed
if not grabbed:
break
# {do something with the frame here}
# lets convert frame to gray for this example
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# write gray frame to writer
writer.write(gray)
# Show output window
cv2.imshow("Output Gray Frame", gray)
# check for 'q' key if pressed
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
# close output window
cv2.destroyAllWindows()
# safely close video stream
stream.release()
# safely close writer
writer.close()
Source: https://github.com/abhiTronix/vidgear
Docs:
https://abhitronix.github.io/vidgear/
More FFmpeg backend examples:https://abhitronix.github.io/vidgear/latest/gears/writegear/compression/usage/
OpenCV backend examples:
https://abhitronix.github.io/vidgear/gears/writegear/non_compression/usage/
The problem such as OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 13 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x00000020/' ???' maybe that your output video size is not the same as original video. You can look over the frame size of video first.
You need to set the codec to 'mp4v' (lowercase). If set in uppercase, an error would be thrown saying that is not supported, suggesting to use lowercase instead: OpenCV:FFMPEG:fallback to use tag 0x7634706d/'mp4v'. You may also want to have a look at the documentation of VideoWriter, as well as the examples given here. Also, please make sure your output video's size is equal to your input frame size (the below takes care of this, using the dimensions of the VideoCapture object).
cap = cv2.VideoCapture(0)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('output.mp4', fourcc, fps, (int(w),int(h)))
You can get the entire list of codecs available for mp4, etc., by setting fourcc=-1. For instance:
out = cv2.VideoWriter('output.mp4', -1, fps, (int(w),int(h)))
The OpenCV documentation is not very rich with regard to the VideoWriter, however I managed to get it working in the following way (by looking at the stacktrace):
import cv2
HEIGHT = 480
WIDTH = 640
FPS = 30.0
cap = cv2.VideoCapture(0, cv2.CAP_ANY)
cap.set(cv2.CAP_PROP_FPS, FPS)
cap.set(cv2.CAP_PROP_CONVERT_RGB , 1)
cap.set(cv2.CAP_PROP_BUFFERSIZE, 100)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, WIDTH)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, HEIGHT)
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# output parameters such as fps and size can be changed
output = cv2.VideoWriter("output.mp4", fourcc, FPS, (WIDTH, HEIGHT))
while True:
if cap.isOpened():
(ret, frame) = cap.read()
if ret:
output.write(frame)
cv2.imshow("frame", frame)
if cv2.waitKey(10) == ord('q'):
break
output.release()
cap.release()
cv2.destroyAllWindows()
The stacktrace error was:
OpenCV: FFMPEG: tag 0x5634504d/'MP4V' is not supported with codec id 12 and
format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
Unfortunately, it is difficult to find a list of the official codecs used by OpenCV, or at least I could not find them. In any case, it appears that you have to enter the codec 'mp4v' written in lower case.
https://docs.opencv.org/3.4/dd/d01/group__videoio__c.html#gac005718f121379beffdbdbfb44f2646a
One important thing I noticed is that the aspect ratio of the frame and the output video must be the same, which is why I use two variables for height and width. If these two are different, the file is created, but the frames are not saved (you always end up with a 1KB mp4 file). To avoid any problems you could do the same for FPS.
just change the codec to "DIVX". This codec works with all formats.
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
i hope this works for you!