简体   繁体   中英

Error when saving video recorded with opencv

I am recording with openCV , at first the recording goes well, but I want that when I hit the spacebar, everything that is recorded then is saved on the device (this is where it gets damaged). I get the following errors:

OpenCV: FFMPEG: tag 0x4745504d/'MPEG' is not supported with codec id 2 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'

and then the window freezes.

this is the code:

def record_video():

     capture = cv2.VideoCapture(0)

     while capture.isOpened():

     res, video = capture.read()
     cv2.imshow("Recording Window", video)

     if cv2.waitKey(1) == 27: #ESC key to stop recording
         break
    
     elif cv2.waitKey(1) == 32: #SPACE key to start recording and save it to the device

         width = int(capture.get (cv2.CAP_PROP_FRAME_WIDTH))
         height = int(catch.get (cv2.CAP_PROP_FRAME_HEIGHT))

         code = cv2.VideoWriter_fourcc (* 'MPEG') #format
         recorder = cv2.VideoWriter("video.mp4",code,20,(width, height))

         while True:
             result, video_record = capture.read()
             recorder.write(video_record)
        
             if cv2.waitKey(1) & 0xFF == ord("q"): #q key to stop recording
                 break

         recorder.release()
         capture.release()
         cv2.destroyAllWindows()
        
    capture.release()
    cv2.destroyAllWindows()

For.mp4 video creation, you need to initialize as *mp4v

code = cv2.VideoWriter_fourcc(*'mp4v') #format

But if the above initialization won't work for you, then you need to compile ffmpeg with opencv . Other option is using Motion-JPEG video format, which is much lower quality compared to .mp4

code = cv2.VideoWriter_fourcc(*'MJPG') #format
recorder = cv2.VideoWriter("video.avi",code,20,(width, height))

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