将视频帧写入另一个视频 Python OpenCV

Write video frames to another video Python OpenCV

我正在阅读来自 YouTube 的视频(出于测试目的。真实案例将来自摄像机馈送)并拍摄每一帧并在其上注入徽标,然后使用这些帧创建另一个视频。我还需要将这些帧保存为图像(这对我来说已经有效)。我尝试了以下,

img = cv2.imread('logo.png')
img_height, img_width, _ = img.shape
url = "https://www.youtube.com/watch?v=vDHtypVwbHQ"
video = pafy.new(url)
best = video.getbest(preftype="mp4")
frame_no = 1

width = 1280
hieght = 720
fps = 30
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
videoW = cv2.VideoWriter('image_to_video.mp4', fourcc, float(fps), (width, hieght))

while True:
    _, frame = video.read()
    frame[y:y + img_height , x:x + img_width ] = img          
    videoW.write(frame)
    frame_no += 1

这写了一个视频,但它说视频已损坏或扩展名不正确。使用 OpenCV 在 Python 中将这些帧写入新视频的最佳方法是什么?

实现中有很多不合逻辑的地方,例如“video”是 pafy.Stream 没有读取方法。

你应该做什么使用Stream url 与VideoCapture 一起获取帧,复制徽标的像素,然后用VideoWriter 写入。

import cv2
import pafy


def apply_logo(url, logo, filename):
    video = pafy.new(url)
    best = video.getbest(preftype="mp4")
    reader = cv2.VideoCapture(best.url)
    if not reader.isOpened():
        return False

    fourcc = cv2.VideoWriter_fourcc(*"MP4V")
    writer = cv2.VideoWriter(filename, fourcc, 60.0, best.dimensions)

    logo_width, logo_height = [min(x, y) for x, y in zip(best.dimensions, logo.shape)]

    i = 0
    while True:
        ret, frame = reader.read()
        if ret:
            frame[:logo_width, :logo_height] = logo[:logo_width, :logo_height]
            writer.write(frame)
            i += 1
            print(i)
        else:
            break

    reader.release()
    writer.release()
    return True

url = "https://www.youtube.com/watch?v=vDHtypVwbHQ"
logo = cv2.imread("logo.png")
apply_logo(url, logo, "output.mp4")