代码:
import cv2 import numpy as np import os import random # 图片文件夹路径 image_folder_path = 'path_to_your_images_folder' # 视频文件所在的文件夹路径 video_folder_path = 'path_to_your_videos_folder' # 输出视频文件夹路径(如果不存在则创建) output_folder_path = 'path_to_your_output_folder' if not os.path.exists(output_folder_path): os.makedirs(output_folder_path) # 确保图片文件夹路径存在 if not os.path.exists(image_folder_path): print("图片文件夹路径不存在。") else: # 获取图片文件夹中所有图片文件的列表 image_files = [f for f in os.listdir(image_folder_path) if f.lower().endswith(('.jpg', '.jpeg', '.png'))] if not image_files: print("图片文件夹中未找到图片。") else: # 随机选择一张图片 random_image_file = random.choice(image_files) random_image_path = os.path.join(image_folder_path, random_image_file) print(f"选定用于叠加的图片:{random_image_file}") # 确保视频文件夹路径存在 if not os.path.exists(video_folder_path): print("视频文件夹路径不存在。") else: # 遍历视频文件夹中的所有视频文件 for video_file in os.listdir(video_folder_path): if video_file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')): print(f"正在处理视频:{video_file}") # 视频文件的完整路径 video_path = os.path.join(video_folder_path, video_file) # 输出视频文件的完整路径,保存到新的输出文件夹中 output_video_path = os.path.join(output_folder_path, video_file) # 打印视频路径信息 print(f"视频文件路径:{video_path}") print(f"输出视频路径:{output_video_path}") # 尝试读取随机选择的图片 image = cv2.imread(random_image_path) if image is None: print(f"图片加载失败:{random_image_path}") continue # 尝试打开视频文件 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)) print(f"帧宽度:{frame_width}, 帧高度:{frame_height}, 帧率:{fps}") # 创建视频写入对象 fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 根据视频格式可能需要更改编解码器 out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height)) # 处理视频的每一帧 while True: ret, frame = cap.read() if not ret: break # 将图片放在帧的底层 frame[:frame_height, :frame_width, :] = image # 将处理后的帧写入输出视频 out.write(frame) # 释放视频读取和写入对象 cap.release() out.release() print(f"完成处理 {video_file}") else: print(f"跳过文件:{video_file}(不支持的格式)")
标签:视频,python,image,video,print,path,folder,frame,底层 From: https://www.cnblogs.com/jingzaixin/p/18163696