需要准备一个人物朗诵MP4格式的视频和一张需要更换的JPG图片,小编测试了,视频背景确实可以更换,遗憾的是视频没有声音!
pip install opencv-python mediapipe numpy
import cv2import numpy as npimport mediapipe as mp
# 初始化MediaPipe自拍分割模型mp_selfie_segmentation = mp.solutions.selfie_segmentationselfie_segmentation = mp_selfie_segmentation.SelfieSegmentation(model_selection=1)
def replace_video_background(input_video, output_video, background_image): # 读取视频 cap = cv2.VideoCapture(input_video) fps = int(cap.get(cv2.CAP_PROP_FPS)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 创建视频写入对象 fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_video, fourcc, fps, (width, height))
# 读取背景图并调整尺寸 bg_image = cv2.imread(background_image) bg_image = cv2.resize(bg_image, (width, height))
while cap.isOpened(): ret, frame = cap.read() if not ret: break
# 转换颜色空间为RGB frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 执行分割 results = selfie_segmentation.process(frame_rgb) mask = results.segmentation_mask
# 生成二值掩膜(调整阈值) binary_mask = (mask > 0.8).astype(np.uint8) * 255
# 优化掩膜边缘 blurred_mask = cv2.GaussianBlur(binary_mask, (5, 5), 0)
# 提取前景 foreground = cv2.bitwise_and(frame, frame, mask=blurred_mask)
# 处理背景 background = cv2.bitwise_and(bg_image, bg_image, mask=255 - blurred_mask)
# 合成图像 combined = cv2.add(foreground, background)
# 写入视频 out.write(combined)
cap.release() out.release() cv2.destroyAllWindows()
# 使用示例replace_video_background( input_video="11.mp4", output_video="output.mp4", background_image="11.jpg")