【问题标题】:How to read Youtube Videos with OpenCV at specific timestamps and set duration without downloading it?如何在特定时间戳下使用 OpenCV 阅读 Youtube 视频并设置持续时间而不下载它?
【发布时间】:2021-11-22 19:30:26
【问题描述】:

我尝试使用 pafy,但它从头开始播放视频,我想在视频的特定部分运行我的模型。如果可以的话,请指导我怎么做。

任何帮助表示赞赏,在此先感谢:)

【问题讨论】:

  • 下载它,然后在本地文件上使用 VideoCapture,并希望set(CAP_PROP_POS_MSEC, ...) 可以工作,因为在视频文件中查找很棘手,而且 OpenCV 是为计算机视觉而设计的,而不是用于处理视频文件

标签: python opencv youtube youtube-dl pafy


【解决方案1】:

其实很简单,我想通了:)

代码如下:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-09
    • 2019-07-15
    • 2020-06-05
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多