Let me start with the problems in your code.
-
-
out = cv2.VideoWriter("newImage.jpg, fourcc=0, fps=0)#line7`
You initialize the filename
variable to the image format ("newImage.jpg").
This is wrong. You need to initialize the filename
by choosing one of the video-formats i.e. .avi
, .mp4
..
You initialize fourcc
to 0. I can't say it is wrong, but I can give a suggestion for a better initialization.
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
As you can see above, I initialized my fourcc
parameter for mp4
video files.
You initialized fps
to 0. Why? fps
means frames-per-second meaning how many frames will you display in one second. My suggestion is set to 20. Of course, you can choose any other positive-integer.
- Now, what will be the dimension of your output video?
You have to set while declaring the VideoWriter
. If you don't know and you would like to set the same dimension with the input video. You could do:
ret, frame = cap.read()
(h, w) = frame.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter("newVid.mp4", fourcc, 20, (w, h))
but, it seems you would like to set your dimensions to the (640, 480)
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter("newVid.mp4", fourcc, 20, (640, 480))
One last thing is, specifying whether the output video is color or not.
out = cv2.VideoWriter("newVid.mp4", fourcc, 20, (w, h), isColor=True)
-
-
if not (cap.isOpened()):
print("Could not open video device")
You are checking whether the video will be opened or not. But what happens if the video fails to open? According to the current logic it will continue. We should put an else statement.
if not cap.isOpened():
print("Could not open video device")
else
.
.
-
-
while(True):
ret, frame = cap.read()
snapShot = frame
Now what happens if ret
is False? Application will throws an exception. Therefore you should do:
while(True):
ret, frame = cap.read()
if ret:
snapShot = frame
Now why did you set snapShot
variable to the frame?
You can directly write the input frames' copy. Like:
while True:
ret, frame = cap.read()
if ret:
cv2.imshow("preview", frame)
out.write(frame.copy())
One last thing, when you finish make sure to relase VideoWriter
object too.
out.release()
cap.release()
Code:
import cv2
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
(h, w) = frame.shape[:2]
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
out = cv2.VideoWriter("newVid.mp4", fourcc, 20, (640, 480), isColor=True)
if not cap.isOpened():
print("Could not open video device")
else:
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
while True:
ret, frame = cap.read()
if ret:
cv2.imshow("preview", frame)
out.write(frame.copy())
if cv2.waitKey(1) & 0xFF == ord('q'):
break
out.release()
cap.release()