0
votes

I am trying to access youtube video using opencv and pafy. I followed the instruction given here Is it possible to stream video from https:// (e.g. YouTube) into python with OpenCV? . But after following the instructions i got below mentioned error - 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'

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

Error which i got -

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'

When i give preftype="webm" at this line -

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

i got below error -

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

2 Answers

0
votes

You can also try this here we are first checking if we have a frame then only we are calling cv.imshow('Video', frames) otherwise it will come out of the loop.

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
votes
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