【问题标题】:OpenCV ret=False, is it reading the video, or not?OpenCV ret=False,是看视频还是不看视频?
【发布时间】:2020-11-18 17:15:38
【问题描述】:

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

这是我的代码。我检查了cap.isOpened(),它返回True,但ret 确实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()

【问题讨论】:

  • ret 必须为真,以便您可以使用它。这是关于如何在 OpenCV 中处理视频文件的文档;docs.opencv.org/4.3.0/dd/d43/tutorial_py_video_display.html
  • 从控制台复制:ret Out[16]: False 这很令人困惑。 ://
  • 您是否以适当的方式将参数设置为cv2.VideoCapture() 方法?您是否能够播放任何其他视频文件?
  • 是的,灰度视频播放

标签: python opencv video edge-detection


【解决方案1】:

你的代码应该这样修改

# 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() 

如果对你有帮助的话给?

【讨论】:

    猜你喜欢
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    相关资源
    最近更新 更多