I am trying to capture a video from webcam in 1440p but the output file cannot be opened. There aren't any problem when I captured in 1080p and 2592*1944 (5mp), only 1440p that has a problem. Does anybody knows how can I make it work with 1440p?
I am not sure is it about the fourCC but I tried changing it to DIVX and the result still the same.
import cv2
cap = cv2.VideoCapture(0)
framesize = '1440p'
if framesize=='5mp':
cap.set(3, 2592)
cap.set(4, 1944)
resolution = (2592,1944)
elif framesize=='1440p':
cap.set(3, 2560)
cap.set(4, 1440)
resolution = (2560, 1440)
else :
cap.set(3, 1920)
cap.set(4, 1080)
resolution = (1920, 1080)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('new_output.avi',fourcc, 20.0, resolution)
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
The output file is only 13 KB. When trying to play it, there's a message "This file isn't playable. That might be because the file type is unsupported, the file extension is incorrect, or the file is corrupt. 0xc10100be"
I think you have to resize each frame before passing it to the VideoWriter():
out = VideoWriter(outvid, fourcc, float(fps), size, is_color)
if size[0] != img.shape[1] and size[1] != img.shape[0]:
img = resize(img, size)
out.write(img)
More examples at https://www.programcreek.com/python/example/72134/cv2.VideoWriter
Related
Trying to record "time true" video with openCV. When recording video footage it seems to be slightly sped up. If I hold a timer up to the webcam and then play it back saved footage is 3 - 5 seconds too fast per minute of saved footage.
How can I get the saved video to be exactly 1 minute if I record 1 minute from my webcam? Or 2 minutes of recording to be an exported 2-minute video?
import cv2
cap = cv2.VideoCapture(0)
fps = cap.get(cv2.CAP_PROP_FPS)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH) # float `width`
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) # float `height`
fourcc = cv2.VideoWriter_fourcc(*'XVID')
videoWriter = cv2.VideoWriter('MYPATH\\video.avi', fourcc, fps, (int(width),int(height)))
while (True):
ret, frame = cap.read()
if ret:
cv2.imshow('video', frame)
videoWriter.write(frame)
if cv2.waitKey(1) == 27:
break
cap.release()
videoWriter.release()
cv2.destroyAllWindows()
I have no idea why this fixed it... but changing the forcc to fourcc = cv2.VideoWriter_fourcc(*'MP4V') and then changing the output file from .avi to .mp4 fixed the problem.
Your program may write additional frames because True sentence at line 16 in your while loop, then change that value to check as conditional ret, by:
...
ret, frame = cap.read()
while (ret):
cv2.imshow('video', frame)
videoWriter.write(frame)
ret, frame = cap.read()
if cv2.waitKey(1) == 27:
break
cap.release()
videoWriter.release()
cv2.destroyAllWindows()
I'm trying to re-size the video using opencv and then save it back to my system.The code works and does not give any error but output video file is corrupted. The fourcc I am using is mp4v works well with .mp4 but still the output video is corrupted. Need Help.
import numpy as np
import cv2
import sys
import re
vid=""
if len(sys.argv)==3:
vid=sys.argv[1]
compress=int(sys.argv[2])
else:
print("File not mentioned or compression not given")
exit()
if re.search('.mp4',vid):
print("Loading")
else:
exit()
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
def rescale_frame(frame, percent=75):
width = int(frame.shape[1] * percent/ 100)
height = int(frame.shape[0] * percent/ 100)
dim = (width, height)
return cv2.resize(frame, dim, interpolation =cv2.INTER_AREA)
FPS= 15.0
FrameSize=(frame.shape[1], frame.shape[0])
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('Video_output.mp4', fourcc, FPS, FrameSize, 0)
while(cap.isOpened()):
ret, frame = cap.read()
# check for successfulness of cap.read()
if not ret: break
rescaled_frame=rescale_frame(frame,percent=compress)
# Save the video
out.write(rescaled_frame)
cv2.imshow('frame',rescaled_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
The problem is the VideoWriter initialization.
You initialized:
out = cv2.VideoWriter('Video_output.mp4', fourcc, FPS, FrameSize, 0)
The last parameter 0 means, isColor = False. You are telling, you are going to convert frames to the grayscale and then saves. But there is no conversion in your code.
Also, you are resizing each frame in your code based on compress parameter.
If I use the default compress parameter:
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
rescaled_frame = rescale_frame(frame)
(h, w) = rescaled_frame.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
writer = cv2.VideoWriter('Video_output.mp4',
fourcc, 15.0,
(w, h), True)
else:
print("Camera is not opened")
Now we have initialized the VideoWriter with the desired dimension.
Full Code:
import time
import cv2
def rescale_frame(frame_input, percent=75):
width = int(frame_input.shape[1] * percent / 100)
height = int(frame_input.shape[0] * percent / 100)
dim = (width, height)
return cv2.resize(frame_input, dim, interpolation=cv2.INTER_AREA)
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
rescaled_frame = rescale_frame(frame)
(h, w) = rescaled_frame.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
writer = cv2.VideoWriter('Video_output.mp4',
fourcc, 15.0,
(w, h), True)
else:
print("Camera is not opened")
while cap.isOpened():
ret, frame = cap.read()
rescaled_frame = rescale_frame(frame)
# write the output frame to file
writer.write(rescaled_frame)
cv2.imshow("Output", rescaled_frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cv2.destroyAllWindows()
cap.release()
writer.release()
Possible Question: I don't want to change my VideoWriter parameters, what should I do?
Answer: Then you need to change your frames, to the gray image:
while cap.isOpened():
# grab the frame from the video stream and resize it to have a
# maximum width of 300 pixels
ret, frame = cap.read()
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
I have tried different methods but none of them works.
As video is running but and file output.avi is empty.
Here is code
import cv2
vid=cv2.VideoCapture(0)
if (not vid.isOpened()):
print 'Error'
size = (int(vid.get(3)), int(vid.get(4)))
fourcc = cv2.cv.CV_FOURCC('M','J','P','G')
newVideo=cv2.VideoWriter('output.avi',fourcc,20.0,(640,360))
while(vid.isOpened()):
ret,frame=vid.read()
if ret is True:
frame=cv2.flip(frame,0)
newVideo.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1)& 0xFF==ord('q'):
break
else:
break
vid.release()
newVideo.release()
cv2.destroyAllWindows()
The problem is simple, you are reading frame but you are trying to write them in a different size.
The solution is inside of your code. You defined:
size = (int(vid.get(3)), int(vid.get(4)))
But you didn't use it as like:
newVideo=cv2.VideoWriter('output.avi',fourcc,20.0,size)
You set the sizes as manually(640,360) which is not the size of captured frames.
You need to be sure that the output frame's dimension and initialized VideoWriter dimensions are the same.
cv2.resize(frame, (640, 360))
But, I'm not sure you are using python3. Since print 'Error' and fourcc = cv2.cv.CV_FOURCC('M','J','P','G') are not python3 statements.
For python2 the answer will be:
# Add true at the and of the parameter for specifying the frames are RGB.
newVideo = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 360), True)
.
.
if ret is True:
frame=cv2.flip(frame,0)
frame = cv2.resize(frame, (640, 360)) # missing statement
newVideo.write(frame)
cv2.imshow('frame',frame)
.
.
For python3 the answer will be:
import cv2
vid = cv2.VideoCapture(0)
if not vid.isOpened():
print('Error')
fourcc = cv2.VideoWriter_fourcc(*"MJPG")
newVideo = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 360), True)
while vid.isOpened():
ret, frame = vid.read()
if ret:
frame = cv2.flip(frame, 0)
frame = cv2.resize(frame, (640, 360))
newVideo.write(frame)
cv2.imshow('frame', frame)
if (cv2.waitKey(1) & 0xFF) == ord('q'):
break
else:
break
cv2.destroyAllWindows()
vid.release()
newVideo.release()
I have taken the following code from this website.
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if ret:
out.write(frame)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
The problem I am facing is that the video is being stored, but I am not able to open it. The video size is about 6KB, but the duration is 0 seconds. How can I fix this?
I did check the other questions similar to this, but none of them solve the issue I am facing.
I had problem with opening file if I saved frames with wrong size.
If camera gives frame with size ie. (800, 600) then you have to write with the same size (800, 600) or you have to use CV to resize frame to (640, 480) before you save it.
frame = cv2.resize(frame, (640, 480))
Full code
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'avc1') #(*'MP42')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))
while cap.isOpened():
ret, frame = cap.read()
if ret:
frame = cv2.resize(frame, (640, 480))
out.write(frame)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
Example on GitHub: furas/python-examples/cv2/record-file
One thing that I found out after much googling was that the VideoWriter fails silently.
In my case, I didn't have a VideoCapture object, but a list of frames. I followed the guide similar to what you have done, but the problem was that I was passing in the shapes of the array according to what img.shape[:2] was giving me. IIRC, OpenCV has a different ordering of the widths and heights than numpy arrays do which was the source of my problem. See below for the comment from here
As have been stated by #pstch, when creating VideoWriter in Python one should pass frame dimensions in form cv.VideoWriter(filename, fourcc, fps, (w, h), ...). And when creating frame itself - in reverse order: frame = np.zeros((h, w), ...)
I am trying to save a video file with opencv3 in python. The video that I want to save comes from another video file which I modify for tracking purposes. What I get is an empty .avi file, and I don't understand why.
If it helps, I'm on OSX.
Thanks for the help.
Here is the relevant part of the code:
import cv2
import numpy as np
cap = cv2.VideoCapture('Vid.avi')
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (width-110, heigh-210))
while (cap.isOpened()):
success, frame = cap.read()
if success:
hsv_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_frame,lower,upper) #lower and upper are defined in another part of the code
hsv_res = cv2.bitwise_and(hsv_frame,hsv_frame, mask= mask)
out.write(hsv_res)
cv2.imshow('Video', hsv_res)
if cv2.waitKey(50) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()