代码:

 

import cv2
import numpy as np
import os
import random
from concurrent.futures import ThreadPoolExecutor

# 图片文件夹路径
image_folder_path = r'F:\jingguan\tu'
# 视频文件所在的文件夹路径
video_folder_path = r'F:\jingguan\yuan'
# 输出视频文件夹路径
output_folder_path = r'F:\jingguan\hou'

# 确保输出文件夹存在
os.makedirs(output_folder_path, exist_ok=True)

# 从图片文件夹中随机选择一张图片
image_files = [f for f in os.listdir(image_folder_path) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
if not image_files:
    print("图片文件夹中未找到图片。")
    exit()

random_image_file = random.choice(image_files)
random_image_path = os.path.join(image_folder_path, random_image_file)
print(f"选定用于叠加的图片:{random_image_file}")

# 读取图片并进行预处理
image = cv2.imread(random_image_path, cv2.IMREAD_UNCHANGED)
if image is None:
    print(f"图片加载失败:{random_image_path}")
    exit()

# 确保图片以 np.uint8 类型读取
if image.dtype != np.uint8:
    image = image.astype(np.uint8)

# 将图片转换为与视频兼容的格式
image = cv2.cvtColor(image, cv2.COLOR_RGBA2BGR).astype(np.uint8)

def process_frame(frame, image, alpha):
    # 确保 image 大小与 frame 一致
    image_resized = cv2.resize(image, (frame.shape[1], frame.shape[0]), interpolation=cv2.INTER_AREA)
    # 将图片以半透明的方式叠加到视频帧上
    return cv2.addWeighted(frame, 1, image_resized, alpha, 0)

def process_video(video_file, image, alpha):
    # 构建完整的视频路径
    video_path = os.path.join(video_folder_path, video_file)
    # 构建完整的输出视频路径
    output_video_path = os.path.join(output_folder_path, video_file)

    # 打开视频文件
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        print(f"视频打开失败:{video_path}")
        return

    # 获取视频的帧率和尺寸
    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # 创建视频写入对象
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height), isColor=True)

    # 逐帧处理视频
    while True:
        ret, frame = cap.read()
        if not ret:
            break

        # 使用多线程处理帧
        with ThreadPoolExecutor() as executor:
            future = executor.submit(process_frame, frame.copy(), image, alpha)
            processed_frame = future.result()

        out.write(processed_frame)

    # 释放资源
    cap.release()
    out.release()
    print(f"完成处理 {video_file}")

# 设置图片的透明度
alpha = 0.0  #0.0到1.0

# 遍历并处理视频文件夹中的所有视频文件
for video_file in os.listdir(video_folder_path):
    if video_file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
        process_video(video_file, image, alpha)

 

 

代码2

import cv2
import numpy as np
import os
import random

# 图片和视频文件夹路径
image_folder_path = r'F:\jingguan\tu'
video_folder_path = r'F:\jingguan\yuan'
output_folder_path = r'F:\jingguan\hou'

# 确保输出文件夹存在
os.makedirs(output_folder_path, exist_ok=True)

# 随机选择一张图片
image_files = [f for f in os.listdir(image_folder_path) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
if not image_files:
    print("图片文件夹中未找到图片。")
    exit()

random_image_file = random.choice(image_files)
random_image_path = os.path.join(image_folder_path, random_image_file)
print(f"选定用于叠加的图片:{random_image_file}")

# 读取图片
image = cv2.imread(random_image_path, cv2.IMREAD_UNCHANGED)
if image is None:
    print(f"图片加载失败:{random_image_path}")
    exit()

# 将图片转换为与视频兼容的格式
image = cv2.cvtColor(image, cv2.COLOR_RGBA2BGR).astype(np.uint8)

# 遍历并处理视频文件夹中的所有视频文件
for video_file in os.listdir(video_folder_path):
    if video_file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')):
        video_path = os.path.join(video_folder_path, video_file)
        output_video_path = os.path.join(output_folder_path, video_file)

        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            print(f"视频打开失败:{video_path}")
            continue

        # 获取视频的帧率和尺寸
        fps = cap.get(cv2.CAP_PROP_FPS)
        frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

        # 将图片缩放到视频帧的尺寸
        image = cv2.resize(image, (frame_width, frame_height), interpolation=cv2.INTER_AREA)

        # 创建视频写入对象
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height), isColor=True)

        alpha = 0.0  # 设置图片的透明度 ,0.0到1.0
        while True:
            ret, frame = cap.read()
            if not ret:
                break

            # 将图片以半透明的方式叠加到视频帧上
            frame = cv2.addWeighted(frame, 1, image, alpha, 0)

            out.write(frame)

        cap.release()
        out.release()
        print(f"完成处理 {video_file}")

 

posted on 2024-04-28 16:54  大话人生  阅读(1)  评论(0编辑  收藏  举报