I've been trying to trying to write MP4 video files using OpenCV, in python.
AVI creation works fine, both on linux and windows, when I use both:
out = cv2.VideoWriter('x.avi', 0, 30, (640, 480))
and
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x.avi', fourcc, 30, (640, 480))
and even
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('x', fourcc, 30, (640, 480))
.
When I try to save an MP4 however nothing ever saves - using:
fourcc = cv2.VideoWriter_fourcc(*"H264")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))
and
fourcc = cv2.VideoWriter_fourcc(*"AVC1")
out = cv2.VideoWriter('x.mp4', fourcc, 30, (640, 480))
No errors occur, just nothing saves.
I've tried everything over the past few days, doing everything to avoid creating the AVI and then converting it to MP4 using ffmpeg as I find that to be horrible practice.
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()
Give right values of the high and width of the frames:
import cv2
print ('Press [ESC] to quit demo')
# Read from the input video file
# input_file = 'Your path to input video file'
# camera = cv2.VideoCapture(input_file)
# Or read from your computer camera
camera = cv2.VideoCapture(0)
# Output video file may be with another extension, but I didn't try
# output_file = 'Your path to output video file' + '.avi'
output_file = "out.avi"
# 4-byte code of the video codec may be another, but I did not try
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
is_begin = True
while camera.isOpened():
_, frame = camera.read()
if frame is None:
break
# Your code
processed = frame
if is_begin:
# Right values of high and width
h, w, _ = processed.shape
out = cv2.VideoWriter(output_file, fourcc, 30, (w, h), True)
print(out.isOpened()) # To check that you opened VideoWriter
is_begin = False
out.write(processed)
cv2.imshow('', processed)
choice = cv2.waitKey(1)
if choice == 27:
break
camera.release()
out.release()
cv2.destroyAllWindows()
This code works for me.
Related
I am saving frames from live stream to a video with h264 codec. I tried this with openCV (versions 3.4 and 4.4) in python but I am not able to save it. I can save video in XVID and many other codecs but I am not successful in h264 and h265.
I am using windows opencv 4.4 in Python.
My sample code is as follow
cap = cv2.VideoCapture(0)
while(cap.isOpened()):
ret,frame = cap.read()
if ret == True:
width = int(cap.get(3)) # float
height = int(cap.get(4)) # float
# fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
fourcc = cv2.VideoWriter_fourcc(*'H264')
out = cv2.VideoWriter(filename, fourcc, 30, (width,height))
out.write(frame)
out.release()
Can anyone help me how can I save video in h264 and h265.
You are recreating the VideoWriter at each frame which in the end only stores a single frame. You need to create the writer first, write the frames to it in the loop then terminate it after you're finished with the video. As a precaution you'll also want to break out of the loop if we detect any problems in the video when you read a frame. To make sure you do this right, let's read in the first frame, set up the VideoWriter then only write to it once we've established its creation:
cap = cv2.VideoCapture(0)
out = None
while cap.isOpened():
ret, frame = cap.read()
if ret == True:
if out is None:
width = int(cap.get(3)) # float
height = int(cap.get(4)) # float
fourcc = cv2.VideoWriter_fourcc(*'H264')
out = cv2.VideoWriter(filename, fourcc, 30, (width, height))
else:
out.write(frame)
else:
break
if out is not None:
out.release()
I was working on saving live feed from USB webcam through opencv on Raspberry PI 4 B+ . Here is the code
import cv2
cap = cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(''D','I','V','X'')
out=cv2.VideoWriter('output.mp4',fourcc,25,(640,480))
while True:
ret, frame = cap.read()
cv2.imshow('frame', frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF== ord('q'):
break
cap.release()
cv2.destroyAllWindows()
The video file is created but I am not able to run that file. I also tried with different formats like 'XVID','MJPG','H264' but faced the same issue.
My opencv version is 4.3.038
There are two issues, I would like to address:
Issue #1: DIVX should be declared as:
fourcc = cv2.VideoWriter_fourcc('D', 'I', 'V', 'X')
Issue #2:
You have declared to create the video with the size (640, 480). Therefore each frame you returned should be also (640, 480)
frame = cv2.resize(frame, (640, 480))
But if you use it with DIVX you will have a warning:
OpenCV: FFMPEG: tag 0x58564944/'DIVX' is not supported with codec id 12 and format 'mp4 / MP4 (MPEG-4 Part 14)'
OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'
Instead of DIVX use mp4v for creating .mp4 videos.
Code:
import cv2
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter('output.mp4', fourcc, 25, (640, 480), isColor=True)
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, (640, 480))
cv2.imshow('frame', frame)
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
You can try this code. Works for me
import cv2
cap = cv2.VideoCapture(0)
video_speed = 15 #This frame rate works well on my case
video_name = 'output.avi'
writer = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc('M','J','P','G'),video_speed, (640,480))
while True:
ret , frame = cap.read()
if ret == True:
writer.writer(frame)
cv2.imshow('Frame', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
else:
break
cap.release()
writer.release()
cv2.destroyAllWindows()
This is my code to save web_cam streaming. It is working but the problem with output video file.
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()
Here's some simple code to save frames into a video file. I recommend creating another thread for obtaining the frames since cv2.VideoCapture.read() is blocking. This can be expensive and cause latency as the main thread has to wait until it has obtained a frame. By putting this operation into a separate thread that just focuses on grabbing frames and processing/saving the frames in the main thread, it dramatically improves performance due to I/O latency reduction. You also can experiment with other codecs but using MJPG should be safe since its built into OpenCV.
from threading import Thread
import cv2
class WebcamVideoWriter(object):
def __init__(self, src=0):
# Create a VideoCapture object
self.capture = cv2.VideoCapture(src)
# Default resolutions of the frame are obtained (system dependent)
self.frame_width = int(self.capture.get(3))
self.frame_height = int(self.capture.get(4))
# Set up codec and output video settings
self.codec = cv2.VideoWriter_fourcc('M','J','P','G')
self.output_video = cv2.VideoWriter('output.avi', self.codec, 30, (self.frame_width, self.frame_height))
# Start the thread to read frames from the video stream
self.thread = Thread(target=self.update, args=())
self.thread.daemon = True
self.thread.start()
def update(self):
# Read the next frame from the stream in a different thread
while True:
if self.capture.isOpened():
(self.status, self.frame) = self.capture.read()
def show_frame(self):
# Display frames in main program
if self.status:
cv2.imshow('frame', self.frame)
# Press Q on keyboard to stop recording
key = cv2.waitKey(1)
if key == ord('q'):
self.capture.release()
self.output_video.release()
cv2.destroyAllWindows()
exit(1)
def save_frame(self):
# Save obtained frame into video output file
self.output_video.write(self.frame)
if __name__ == '__main__':
webcam_videowriter = WebcamVideoWriter()
while True:
try:
webcam_videowriter.show_frame()
webcam_videowriter.save_frame()
except AttributeError:
pass
The output file is corrupted because of the wrong frame rate and frame resolution. Using this code :
out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))
We set the fps/frame rate per second 20. Which was not correct. Also, the frame width and height was wrong. I solved by getting fps, width, height from the captured web_cam profile.
cap = cv2.VideoCapture(0) #web-cam capture
fps = cap.get(cv2.CAP_PROP_FPS)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float
out = cv2.VideoWriter('output.avi', -1,fps, (int(width), int(height)))
I added codec parameter to function cv2.videowriter.
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))
fps = cap.get(cv2.CAP_PROP_FPS)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
codec = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
out = cv2.VideoWriter('output.avi',codec,fps, (int(width),\
int (height)))
#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()
I hope you may see what is different in my code and your code.
Mine works now. Using MJPG codec for .avi extention
the indention is a bit messed,please do forgive cause I am very first time user.
The video file is no longer corrupt.
I got the info from: Link
Why does the following code not save the video?
Also is it mandatory that the frame rate of the webcam matches exactly with the VideoWriter frame size?
import numpy as np
import cv2
import time
def videoaufzeichnung(video_wdth, video_hight, video_fps, seconds):
cap = cv2.VideoCapture(6)
cap.set(3, video_wdth) # wdth
cap.set(4, video_hight) #hight
cap.set(5, video_fps) #hight
# Define the codec and create VideoWriter object
fps = cap.get(5)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, video_fps, (video_wdth, video_hight))
#out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
start = time.time()
zeitdauer = 0
while(zeitdauer < seconds):
end = time.time()
zeitdauer = end - start
ret, frame = cap.read()
if ret == True:
frame = cv2.flip(frame, 180)
# 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()
videoaufzeichnung.videoaufzeichnung(1024, 720, 10, 30)
I suspect you're using the libv4l version of OpenCV for video I/O. There's a bug in OpenCV's libv4l API that prevents VideoCapture::set method from changing the video resolution. See links 1, 2 and 3. If you do the following:
...
frame = cv2.flip(frame,180)
print(frame.shape[:2] # check to see frame size
out.write(frame)
...
You'll notice that the frame size has not been modified to match the resolution provided in the function arguments. One way to overcome this limitation is to manually resize the frame to match resolution arguments.
...
frame = cv2.flip(frame,180)
frame = cv2.resize(frame,(video_wdth,video_hight)) # manually resize frame
print(frame.shape[:2] # check to see frame size
out.write(frame)
...
output-frame & input-frame sizes must be same for writing...
I cant figure out why this is not working.
The following code works perfectly using my webcam:
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()
Yet when I exchange the Webcam for a video file, the output does not generate a video. Only a 5.7kb file named output.avi:
import numpy as np
import cv2
cap = cv2.VideoCapture('Input.avi')
# 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()
I can see in my windows that the video is being processed but is not being saved. I have also tried changing the resolution to match the initial video file.
I'm using OpenCV on Ubuntu, and this worked for me:
out = cv2.VideoWriter("output.avi", cv.CV_FOURCC(*'DIVX'), fps, (640, 480))
See if it works on Windows.