这篇文章主要介绍了Python如何实现人脸识别并进行视频跟踪打码的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Python如何实现人脸识别并进行视频跟踪打码文章都会有所收获,下面我们一起来看看吧。
准备工作
首先需要一些素材,大家可以自己准备
这个是要用的工具
代码实战
使用的模块
import cv2 import face_recognition import matplotlib.pyplot as plt # %matplotlib inline # 在 jupyter 中使用的时候,去掉注释 import ffmpy3 import subprocess import os from PIL import Image
将视频转为音频
def video2mp3(file_name): outfile_name = file_name.split('.')[0] + '.mp3' cmd = 'ffmpeg -i ' + file_name + ' -f mp3 ' + outfile_name print(cmd) subprocess.call(cmd, shell=True)
视频添加音频
def video_add_mp3(file_name, mp3_file): outfile_name = file_name.split('.')[0] + '-f.mp4' subprocess.call('ffmpeg -i ' + file_name + ' -i ' + mp3_file + ' -strict -2 -f mp4 ' + outfile_name, shell=True)
主要代码
def mask_video(input_video, output_video, mask_path='mask.jpg'): # 打码图片 # 完整源码、视频讲解 # Python学习交流群:708525271 # 直接加它领取 mask = cv2.imread(mask_path) # 读取视频 cap = cv2.VideoCapture(input_video) # 读取视频参数,fps、width、heigth CV_CAP_PROP_FPS = 5 CV_CAP_PROP_FRAME_WIDTH = 3 CV_CAP_PROP_FRAME_HEIGHT = 4 v_fps = cap.get(CV_CAP_PROP_FPS) v_width = cap.get(CV_CAP_PROP_FRAME_WIDTH) v_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT) # 设置写视频参数,格式为 mp4 size = (int(v_width), int(v_height)) fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') out = cv2.VideoWriter(output_video, fourcc, v_fps, size) # 已知人脸 known_image = face_recognition.load_image_file("tmr.jpg") biden_encoding = face_recognition.face_encodings(known_image)[0] # 读取视频 cap = cv2.VideoCapture(input_video) while (cap.isOpened()): ret, frame = cap.read() if ret: # 检测人脸 face_locations = face_recognition.face_locations(frame) # print(face_locations) # 检测每一个人脸 for (top_right_y, top_right_x, left_bottom_y, left_bottom_x) in face_locations: unknown_image = frame[top_right_y - 50:left_bottom_y + 50, left_bottom_x - 50:top_right_x + 50] print(face_recognition.face_encodings(unknown_image)) if face_recognition.face_encodings(unknown_image) != []: unknown_encoding = face_recognition.face_encodings(unknown_image)[0] # 对比结果 results = face_recognition.compare_faces([biden_encoding], unknown_encoding) # 是仝卓,就将打码贴图。 if results[0] == True: mask = cv2.resize(mask, (top_right_x - left_bottom_x, left_bottom_y - top_right_y)) frame[top_right_y:left_bottom_y, left_bottom_x:top_right_x] = mask # 写入视频 out.write(frame) else: break
将音频保存为cut.mp3
video2mp3(file_name='cut.mp4')
处理视频,自动打码,输出视频为output.mp4
mask_video(input_video='cut.mp4', output_video='output.mp4')
为 output.mp4 处理好的视频添加声音
video_add_mp3(file_name='output.mp4', mp3_file='cut.mp3')