如何阅读Youtube视频与OpenCV在特定的时间戳,并设置持续时间,而不下载它?

zour9fqk  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(149)

我试过使用pafy,但它从一开始就播放视频,我想在视频的特定部分运行我的模型。如果可能的话,请指导我如何做。
任何帮助都是感激不尽的,提前感谢:)

huwehgph

huwehgph1#

其实很容易,我想通了:)
代码如下:

import cv2
import pafy

#Ask the user for url input
url = input("Enter Youtube Video URL: ")

#Getting video id from the url string
url_data = urlparse.urlparse(url)
query = urlparse.parse_qs(url_data.query)
id = query["v"][0]
video = 'https://youtu.be/{}'.format(str(id))

#Using the pafy library for youtube videos
urlPafy = pafy.new(video)
videoplay = urlPafy.getbest(preftype="any")

cap = cv2.VideoCapture(videoplay.url)

#Asking the user for video start time and duration in seconds
milliseconds = 1000
start_time = int(input("Enter Start time: "))
end_time = int(input("Enter Length: "))
end_time = start_time + end_time

# Passing the start and end time for CV2
cap.set(cv2.CAP_PROP_POS_MSEC, start_time*milliseconds)

#Will execute till the duration specified by the user
while True and cap.get(cv2.CAP_PROP_POS_MSEC)<=end_time*milliseconds:
        success, img = cap.read()
        cv2.imshow("Image", img)
        cv2.waitKey(1)
mccptt67

mccptt672#

python 3.11更新
(对URL解析的更改)

import cv2
import pafy
import urllib

#Ask the user for url input
url = input("Enter Youtube Video URL: ")

#Getting video id from the url string
url_data = urllib.parse.urlparse(url)
query = urllib.parse.parse_qs(url_data.query)
id = query["v"][0]
video = 'https://youtu.be/{}'.format(str(id))

#Using the pafy library for youtube videos
urlPafy = pafy.new(video)
videoplay = urlPafy.getbest(preftype="any")

cap = cv2.VideoCapture(videoplay.url)

#Asking the user for video start time and duration in seconds
milliseconds = 1000
start_time = int(input("Enter Start time: "))
end_time = int(input("Enter Length: "))
end_time = start_time + end_time

# Passing the start and end time for CV2
cap.set(cv2.CAP_PROP_POS_MSEC, start_time*milliseconds)

#Will execute till the duration specified by the user
while True and cap.get(cv2.CAP_PROP_POS_MSEC)<=end_time*milliseconds:
        success, img = cap.read()
        cv2.imshow("Image", img)
        cv2.waitKey(1)

此外,由于like_count不可靠,我不得不从git源代码安装pafy包

pip install git+https://github.com/mps-youtube/pafy.git

查看此问题

相关问题