简体   繁体   中英

Cannot save video using python and opencv

I'm trying to change a video to grayscale and save it but the video only shows up during the run process after it finishes running I click on the saved file but I only get a cannot render file message

import cv2
import numpy as np
import matplotlib.pyplot as plt


import numpy as np
import cv2



    cap = cv2.VideoCapture ('DJI_0055.mov')

    ret, frame = cap.read()
    print('ret =', ret, 'W =', frame.shape[1], 'H =', frame.shape[0], 
    'channel =', frame.shape[2])


     FPS= 60.0
     FrameSize=(frame.shape[1], frame.shape[0])
     fourcc = cv2.VideoWriter_fourcc(*'MJPG')
     out = cv2.VideoWriter('Video_output3.mov', fourcc, FPS, FrameSize, 
      0)

     while(cap.isOpened()):
     ret, frame = cap.read()

     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     frame = gray

     # Save the video
     out.write(frame)

     cv2.imshow('frame',frame)
     if cv2.waitKey(1) & 0xFF == ord('q'):
     break

     cap.release()
     out.release()
     cv2.destroyAllWindows()

Aside from the cannot render file message I also get this message after the video finishes running on IDLE

     Traceback (most recent call last):
     File "C:\Users\fido\Desktop\Practice\E-1-00pm-12m-1mps- 
     8wp\BlackAndWhite.py", line 25, in <module>
     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     cv2.error: OpenCV(4.1.1) C:\projects\opencv- 
     python\opencv\modules\imgproc\src\color.cpp:182: error: 
    (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'

after the last frame, ret ---> False and Frame ---> [], this is what you will get. That is the reason cvtColor is showing this error.

So, if you add

if not ret:
    break

It will get out of the loop properly and your video will be saved.

Edit your code like this:

while(cap.isOpened()):
     ret, frame = cap.read()

     if not ret:
         break

     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
     frame = gray

     # Save the video
     out.write(frame)

     cv2.imshow('frame',frame)
     if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
out.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