OpenCV ret=False,是在读视频,还是不读?

OpenCV ret=False, is it reading the video, or not?

我想检测视频文件 (640x640 9sn.) 的边缘并保存结果。我遵循了 OpenCV 文档和其他一些示例。我发现的大多数示例都是从相机读取的。

这是我的代码。我检查了 cap.isOpened(),它 returns Trueret 确实 FalseframeNoneType 对象.令人困惑的是,我有 gray 数组,它取决于条件 if ret == True。如果 ret = False?

如何获得灰度矩阵

(我安装了ffmpeg pip install ffmpeg-python

(andy.avi 已保存在文件夹中,但已损坏,为空)

import cv2
import numpy as np


cap = cv2.VideoCapture("...\video.mp4")

while(cap.isOpened()):
    ret, frame = cap.read()
    
    frame_width = int(cap.get(3)) 
    frame_height = int(cap.get(4)) 
   
    size = (frame_width, frame_height) 
    
    result = cv2.VideoWriter('andy.avi',  
                         cv2.VideoWriter_fourcc(*'DIVX'), 
                         30, size) 
    
    if ret == True:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        edges = cv2.Canny(gray, 45, 90)
        result.write(edges)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
       break
                    
cap.release()
result.release()
cv2.destroyAllWindows()

你的代码应该这样改

# importing the module 
import cv2 
import numpy as np
  
# reading the vedio 
source = cv2.VideoCapture("...\video.mp4") 

# We need to set resolutions. 
# so, convert them from float to integer. 
frame_width = int(source.get(3)) 
frame_height = int(source.get(4)) 
   
size = (frame_width, frame_height) 

result = cv2.VideoWriter('andy.avi',  
            cv2.VideoWriter_fourcc(*'DIVX'), 
            30, size, 0) 
  
# running the loop 
while True: 
  
    # extracting the frames 
    ret, img = source.read() 
      
    # converting to gray-scale 
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
    edges = cv2.Canny(gray, 45, 90)

    # write to gray-scale 
    result.write(edges)

    # displaying the video 
    cv2.imshow("Live", gray) 
  
    # exiting the loop 
    key = cv2.waitKey(1) 
    if key == ord("q"): 
        break
      
# closing the window 
result.release()
source.release()
cv2.destroyAllWindows() 

如果这对你有帮助就给