简体   繁体   中英

Saving video from camera get syntax error

I am trying to save video from face cam in my dir.

I think I did everything correct. But I am getting syntax error in variable declaration.

Here's the error

Traceback (most recent call last): File "camera1.py", line 15, in cv2.imshow('frame', frame) cv2.error: OpenCV(4.2.0) /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow' ^

  1 from cv2 import *
  2 
  3 cap = cv2.VideoCapture()
  4 
  5 width = int(cap.get((cv2.CAP_PROP_FRAME_WIDTH))))
  6 height = int(cap.get((cv2.CAP_PROP_FRAME_HEIGHT)))
  7 
  8 writer = cv2.VideoWriter('mysupervideo.mp4', cv2.VideoWriter_fourcc(*'XVID'), 20, (width, height))
  9                                                                                                                  
 10 while True:
 11     ret, frame = cap.read()
 12     writer.write(frame)
 13     cv2.imshow('frame', frame)
 14 
 15     if cv2.waitKey(1) & 0xFF == ord('q'):
 16         break
 17 
 18 cap.release()
 19 writer.release()
 20 cv2.destroyAllWindows()                                                                                                                                                                                                                                                                        

Thanks for any help

There are multiple issues with the above code snippet.

1) There are extra parenthesis at the ends of line 5. It should be:

width = int(cap.get((cv2.CAP_PROP_FRAME_WIDTH)))

2) The error that you get here is because in lines 5 and 6 the values of width and height that you get is " 0 and 0". This is because in code above at line 3 you are creating "cap" object but its not capturing from camera hence height width is 0, 0. Instead modify the line to:

cap = cv2.VideoCapture(0)

This (0) indicates capture from camera. and hence you will get proper width and height.

3) I ran the following code snippet and it is working for me and it dumps a result video "mysupervideo.mp4" in present working directory:

from cv2 import *
cap = cv2.VideoCapture(0)
width = int(cap.get((cv2.CAP_PROP_FRAME_WIDTH)))
height = int(cap.get((cv2.CAP_PROP_FRAME_HEIGHT)))
print(width, height)
writer = cv2.VideoWriter('mysupervideo.mp4', cv2.VideoWriter_fourcc(*'XVID'), 20, (width, height))
while True:
    ret, frame = cap.read()
    writer.write(frame)
    cv2.imshow('frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
writer.release()
cv2.destroyAllWindows()  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM