Playing YouTube videos using OpenCV

So far, we have dealt with many examples of playing video files such as mp4, avi, or frames captured using an input device such as a webcam. In this post, we will learn how to play YouTube videos using OpenCV.

You can download the source codes here(https://github.com/raspberry-pi-maker/OpenCV)

prerequisite

You only need to install the papy, youtube-dl packages.


pip3 install papy
pip3 install --upgrade youtube-dl 

Pafy Objects and Stream Objects

Pafy objects relate to videos hosted on YouTube. They hold metadata such as title, viewcount, author and video ID. Stream objects relate to individual streams of a YouTube video. They hold stream-specific data such as resolution, bitrate and url. Each Pafy object contains multiple stream objects.

If you use papy, you can get information about youtube videos as follows.


import pafy 
url = 'https://www.youtube.com/watch?v=M-UKXCUI0rE'
video = pafy.new(url)
#The author of the video (str)
print(video.author)
#The url of the video’s display image (not always available)
print(video.bigthumb)
#The url of the video’s larger display image (not always available) (str)
print(video.bigthumbhd)
#The category of the video (str)
print(video.category)
#The title of the video (str)
print(video.title)


Playing Youtube videos



import cv2
import time
import pafy #pip install --upgrade youtube-dl
url = 'https://www.youtube.com/watch?v=xFrGuyw1V8s'
video = pafy.new(url)
best = video.getbest(preftype="mp4")
FPS = 30.0
SLEEP = 1.0 / FPS
cap = cv2.VideoCapture()
cap.open(best.url)
while True:
    s = time.time()
    retval, frame = cap.read()
    if not retval:
        break
    cv2.imshow('frame', frame)
    key = cv2.waitKey(1)
    if key == 27:   #Press Esc to exit
        break
    elapsed = time.time() - s
    time.sleep(max(0, SLEEP - elapsed))
cv2.destroyAllWindows()
<play_youtube.py>

Run the above code.


python3 play_youtube.py


Of course, if you can find the above url on YouTube.



Wrapping up

It's very simple to process YouTube videos using OpenCV. With a little application of the above code, you can create a YouTube video download program or add subtitles.

You can download the source codes here(https://github.com/raspberry-pi-maker/OpenCV)

댓글

이 블로그의 인기 게시물

Image Processing #7 - OpenCV Text

OpenCV Installation - Rasbian Buster, Jessie, DietPi Buster