\

PythonとOpenCV(cv2)を使用して音声付きの動画を作成する方法について説明します。しかし、OpenCV単体では音声付きの動画を作成することはできないようです。

そのため、音声付きの動画を作成するためには他のライブラリが必要となります。その一つがpyavです。

以下に、pyavを使用して音声付きの動画を作成するサンプルコードを示します。

import av
import numpy as np

input_ = av.open("./videos/01_smile.mp4")
output = av.open('./videos/sample02.mp4', 'w')

in_stream = input_.streams.get(audio=0, video=0)
out_stream_video = output.add_stream("h264", rate=30, width=1920, height=1080)
out_stream_audio = output.add_stream("aac", rate=44100, layout="stereo")

for i, packet in enumerate(input_.demux(in_stream)):
    if packet.dts is None:
        continue

    if packet.stream.type == 'video':
        for frame in packet.decode():
            image = frame.to_image()
            image = np.array(image)
            image[:, :, 1] = 255
            new_frame = av.VideoFrame.from_ndarray(image, format='rgb24')
            for new_packet in out_stream_video.encode(new_frame):
                output.mux(new_packet)
    elif packet.stream.type == 'audio':
        for audio_frame in packet.decode():
            arr = audio_frame.to_ndarray()
            arr = arr * 0.1
            new_audio_frame = av.AudioFrame.from_ndarray(arr, format="fltp")
            new_audio_frame.rate = 44100
            for new_packet in out_stream_audio.encode(new_audio_frame):
                output.mux(new_packet)

input_.close()
output.close()

このコードは、入力の動画を加工し別の動画ファイルを出力するものです。具体的には、元の動画のRGBのうちGの値を全ての時間で最大値 (255)にし、音量を1/10にします。

以上がPythonとOpenCVを使用して音声付きの動画を作成する方法になります。この情報が役立つことを願っています。.

投稿者 admin

コメントを残す

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