YOLOでYouTubeの映像から物体検出する

YouTubeのライブ映像を取り込んで物体検出してみる。応用すると風景のライブ映像に野生動物が写ったらアラートを出す。録画するなど出来ると思う。

前回の下記部分のカメラ映像読み込み部分をYouTubeに置き換える。

# Load image source
cap = cv2.VideoCapture(0)

前回のパッケージに加えて「pip install yt-dlp」を実行しておく。

実装

モジュールの読み込み
from yt_dlp import YoutubeDL
YouTubeのライブ配信ページURLから、再生用の実URL(多くはHLSのm3u8)を取得する関数
def get_best_live_url(youtube_url: str) -> str:
    ydl_opts = {
        'quiet': True,
        'no_warnings': True,
        'skip_download': True,
        # Filters in order of ease of live performance
        'format': 'best[protocol^=m3u8]/best[ext=mp4]/best'
    }
    with YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(youtube_url, download=False)
        # `url` contains a URL that can be played directly (assuming m3u8)
        stream_url = info.get('url')
        if not stream_url:
            for f in info.get('formats', []):
                if 'm3u8' in (f.get('protocol') or ''):
                    stream_url = f.get('url')
                    break
        if not stream_url:
            raise RuntimeError('Unable to get live playback URL.')
        return stream_url
YouTubeの動画、ライブ配信を開く関数
def open_live_capture(stream_url: str) -> cv2.VideoCapture:
    cap = cv2.VideoCapture(stream_url)
    # Latency reduction (enabled builds only)
    try:
        cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
    except Exception:
        pass
    return cap
前回コードの変更部分

前回のコードの「cap = cv2.VideoCapture(0)」を下記に置き換える。「youtube_url」に取り込みたい動画やライブ映像のURLを入力する。

youtube_url = 'https://www.youtube.com/watch?v=好きな動画のURL'

stream_url = get_best_live_url(youtube_url)
print('stream:', stream_url)
cap = open_live_capture(stream_url)

if not cap.isOpened():
    raise RuntimeError('Failed to open VideoCapture. Please use an FFmpeg-enabled build of OpenCV.')

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です