代码:
import cv2 import numpy as np import os import random from concurrent.futures import ProcessPoolExecutor from tqdm.auto import tqdm # 图片文件夹路径 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}") # 定义处理视频的函数 def process_video(video_file, random_image_path, video_folder, output_folder): # 构建完整的视频和图片路径 video_path = os.path.join(video_folder, video_file) output_video_path = os.path.join(output_folder, 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)) # 读取图片,并确保以 np.uint8 类型读取 image = cv2.imread(random_image_path, cv2.IMREAD_UNCHANGED) if image is None: print(f"图片加载失败:{random_image_path}") return # 将图片转换为 np.uint8 类型,如果需要的话 if image.dtype != np.uint8: image = image.astype(np.uint8) # 将图片缩放到视频帧的尺寸 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到0.1 # 处理视频的每一帧 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}") # 使用多进程执行视频处理 if __name__ == "__main__": with ProcessPoolExecutor(max_workers=4) as executor: # 可以根据CPU核心数调整工作进程数 futures = [] for video_file in os.listdir(video_folder_path): if video_file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')): futures.append(executor.submit(process_video, video_file, random_image_path, video_folder_path, output_folder_path)) # 使用tqdm显示整体进度 for future in tqdm(futures, total=len(futures), desc="Overall Progress", unit="video"): try: future.result() # 等待任务完成 except Exception as e: print(f"视频处理出现错误:{e}") print("所有视频处理完成。")
加上执行时长代码:
import cv2 import numpy as np import os import random from concurrent.futures import ProcessPoolExecutor from tqdm.auto import tqdm from datetime import datetime # 图片文件夹路径 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}") # 打印代码开始执行的时间 start_time = datetime.now() print(f"代码开始执行时间:{start_time.strftime('%Y-%m-%d %H:%M:%S')}") # 定义处理视频的函数 def process_video(video_file, random_image_path, video_folder, output_folder): # 构建完整的视频和图片路径 video_path = os.path.join(video_folder, video_file) output_video_path = os.path.join(output_folder, 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)) # 读取图片,并确保以 np.uint8 类型读取 image = cv2.imread(random_image_path, cv2.IMREAD_UNCHANGED) if image is None: print(f"图片加载失败:{random_image_path}") return # 将图片转换为 np.uint8 类型,如果需要的话 if image.dtype != np.uint8: image = image.astype(np.uint8) # 将图片缩放到视频帧的尺寸 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 # 根据需要调整透明度 # 处理视频的每一帧 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}") # 使用多进程执行视频处理 if __name__ == "__main__": with ProcessPoolExecutor(max_workers=4) as executor: # 可以根据CPU核心数调整工作进程数 futures = [] for video_file in os.listdir(video_folder_path): if video_file.lower().endswith(('.mp4', '.avi', '.mov', '.mkv')): futures.append(executor.submit(process_video, video_file, random_image_path, video_folder_path, output_folder_path)) # 使用tqdm显示整体进度 for future in tqdm(futures, total=len(futures), desc="Overall Progress", unit="video"): try: future.result() # 等待任务完成 except Exception as e: print(f"视频处理出现错误:{e}") # 打印代码结束执行的时间并计算总耗时 end_time = datetime.now() print(f"代码结束执行时间:{end_time.strftime('%Y-%m-%d %H:%M:%S')}") total_time = end_time - start_time hours, remainder = divmod(total_time.seconds, 3600) minutes, seconds = divmod(remainder, 60) print(f"总耗时时长:{hours}时{minutes}分{seconds}秒") print("所有视频处理完成。")
分类:
python小程序
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
2022-04-28 人脸训练
2020-04-28 Vue -路由(Vue -Router)
2020-04-28 Vue常用的UI组件-Elment(PC端Vue组件库)(饿了么组件)(推荐)
2020-04-28 Vue常用的UI组件-ant-design-vue
2020-04-28 Vue常用的UI组件-Mint UI(移动端Vue组件库)(饿了么组件)
2020-04-28 Vue常用的UI组件-vant(轻量、可靠的移动端Vue组件库)(推荐)