我在我的VidGear Python 库中添加了 Youtube URL 源支持,该库仅通过提供 URL 即可自动将 YouTube 视频传输到 OpenCV 中。这是一个完整的 python 示例:
# import libraries
from vidgear.gears import CamGear
import cv2
stream = CamGear(source='https://youtu.be/dQw4w9WgXcQ', stream_mode = True, logging=True).start() # YouTube Video URL as input
# infinite loop
while True:
frame = stream.read()
# read frames
# check if frame is None
if frame is None:
#if True break the infinite loop
break
# do something with frame here
cv2.imshow("Output Frame", frame)
# Show output window
key = cv2.waitKey(1) & 0xFF
# check for 'q' key-press
if key == ord("q"):
#if 'q' key-pressed break out
break
cv2.destroyAllWindows()
# close output window
# safely close video stream.
stream.stop()
Run Code Online (Sandbox Code Playgroud)
我确定您现在已经知道答案了,但是我会为其他搜索相同主题的人解答。您可以使用Pafy做到这一点。首先你需要
import pafy
然后添加这个
url = "https://www.youtube.com/watch?v=_9OBhtLA9Ig"
video = pafy.new(url)
best = video.getbest(preftype="mp4")
capture = cv2.VideoCapture()
capture.open(best.url)
Run Code Online (Sandbox Code Playgroud)
就是这样。