from pathlib import Pathimport cv2import os
def video2mp3_img(video_path, save_path): def video_split(video_path, save_path):
if not os.path.exists(save_path): os.makedirs(save_path) cap = cv2.VideoCapture(video_path) i = 0 while True: ret, frame = cap.read() if ret: cv2.imwrite(save_path + '/' + str(i) + '.jpg', frame) i += 1 else: break cap.release() if not os.path.exists(save_path): os.makedirs(save_path) # 视频分割 video_split(video_path, save_path) # 视频转音频 os.system("ffmpeg -i {} -q:a 0 -map a {}/audio.mp3".format(video_path, save_path))
def face_replace(user_path=""):
from pathlib import Path import cv2 from modelscope.outputs import OutputKeys from modelscope.pipelines import pipeline from modelscope.utils.constant import Tasks import os os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
def my_function(img_path): image_face_fusion = pipeline(Tasks.image_face_fusion, model='damo/cv_unet-image-face-fusion_damo') template_path = img_path filename = os.path.splitext(os.path.basename(img_path))[0] # 替换面部依赖 result = image_face_fusion(dict(template=template_path, user=user_path)) cv2.imwrite(f'video_imgout/{filename}.jpg', result[OutputKeys.OUTPUT_IMG]) threads = [] BASE_PATH = os.path.dirname(__file__) for dirpath, dirnames, filenames in os.walk(r"D:\3code\3Python\modelscope\mv_face_change-main"): for filename in filenames: print(filename) if filename.endswith('.jpg'): file_path = Path(os.path.join(dirpath, filename)) print(file_path) my_function(str(file_path))
def img2mp4(video_path, save_name): BASE_PATH = "D:\3code\3Python\modelscope\mv_face_change-main" img = cv2.imread("video_img/0.jpg") imgInfo = img.shape size = (imgInfo[1], imgInfo[0]) files = [] for dirpath, dirnames, filenames in os.walk(r"D:\3code\3Python\modelscope\mv_face_change-main\video_imgout"): for filename in filenames: fileName = Path(os.path.join(dirpath, filename)) files.append(os.path.join(dirpath, filename)) files = [file.replace('\\', '/') for file in files] files.sort(key=lambda x: int(x.split('/')[-1].split('.')[0])) fourcc = cv2.VideoWriter_fourcc(*'mp4v') videoWrite = cv2.VideoWriter(r"D:\3code\3Python\modelscope\mv_face_change-main\videos\ldh.mp4", fourcc, 25, size) # 写入对象 1 file name 3: 视频帧率 for i in files: print(i) img = cv2.imread(str(i)) videoWrite.write(img) # 将video_img中的音频文件添加到视频中 os.system("ffmpeg -i {} -i {} -c:v copy -c:a aac -strict experimental {}".format("videos/ldh.mp4", "audio/audio.mp3", "videos/newlest_ldh.mp4"))
if __name__ == '__main__': BASE = os.path.dirname(__file__) video_path = os.path.join(BASE, "videos/demo.mp4") save_path = os.path.join(BASE, "video_img")
# 视频 ==> imgs video2mp3_img(video_path, save_path) # 人脸替换 face_replace(user_path='zsy.jpg') # imgs ==> 视频 img2mp4(video_path, save_name='zsy')
评论