尝试使用pafy和openCv捕获youtube视频时出现错误:(-215:断言失败)错误

时间:2019-06-13 10:05:33

标签: python opencv youtube pafy

我正在尝试使用opencv和pafy访问youtube视频。我按照此处Is it possible to stream video from https:// (e.g. YouTube) into python with OpenCV? 的说明进行操作。但是按照说明我得到以下提到的错误- cv2。错误:OpenCV(4.0.0)/io/opencv/modules/highgui/src/window.cpp:350:错误:(-215:断言失败)size.width> 0 && size.height> 0在功能“ imshow”中

import cv2 
import pafy

url = "https://www.youtube.com/watch?v=_p9VEKecHKI"
live = pafy.new(url)
stream = live.getbest(preftype="mp4")

cap = cv2.VideoCapture(stream.url)

#cap = cv2.VideoCapture()
#cap.open(stream.url)

while True:
        ret, frame = cap.read()
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) == ord('q'):
                break

cap.release()
cv2.destroyAllWindows()

我得到的错误-

Traceback (most recent call last):
  File "videoCapture.py", line 20, in <module>
  cv2.imshow('frame', frame)
cv2.error: OpenCV(4.0.0) /io/opencv/modules/highgui/src/window.cpp:350: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'

当我在此行给preftype =“ webm”-

stream = live.getbest(preftype="webm") 

我遇到了以下错误-

Traceback (most recent call last):
   File "videoCapture.py", line 11, in <module>
   cap = cv2.VideoCapture(stream.url)
AttributeError: 'NoneType' object has no attribute 'url'

2 个答案:

答案 0 :(得分:0)

你也可以试试这个 在这里,我们首先检查是否有框架,然后才调用 cv.imshow('Video', frames) 否则它将退出循环。

while True:
    ret, frames = capture.read()

    # for preventing warning (-255 assertion failed)
    if ret:
        cv.imshow('Video', frames)
    else:
        break
    
    # for stopping the window manullaly
    if cv.waitKey(1) & 0xFF == ord('e'):
        break

答案 1 :(得分:-1)

import cv2 
import pafy
import time

url = "https://www.youtube.com/watch?v=_p9VEKecHKI"
live = pafy.new(url)
stream = live.getbest(preftype="mp4")

cap = cv2.VideoCapture(stream.url)

#cap = cv2.VideoCapture()
#cap.open(stream.url)

while True:
        ret, frame = cap.read()
        if ret:
            cv2.imshow('frame', frame)

        if cv2.waitKey(1) == ord('q'):
                break

cap.release()
cv2.destroyAllWindows()

enter image description here