#! /usr/bin/env python
# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name: 视频人脸追踪
# Author: yunhgu
# Date: 2021/9/13 15:13
# Description:
# -------------------------------------------------------------------------------
from pathlib import Path
import moviepy.editor as mpy
from alive_progress import alive_bar
import cv2
def draw_face_rectangle(img_content):
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
# img = cv2.imdecode(np.fromfile(img_file, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
gray_img = cv2.cvtColor(img_content, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img)
for x, y, w, h in faces:
img_content = cv2.rectangle(img_content, (x, y), (x + w, y + h), (0, 255, 0), 1)
return img_content
def read_video(file):
frame_bgr_list = []
frame_rgb_list = []
cap = cv2.VideoCapture(file)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
fourcc = cap.get(cv2.CAP_PROP_FOURCC)
while cap.isOpened():
ret, frame = cap.read()
if ret:
frame_bgr_list.append(frame)
frame_rgb_list.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
else:
break
cap.release()
return frame_bgr_list, frame_rgb_list, width, height, fps, fourcc
def make_gif(images, name, duration=5):
def make_frame(t):
try:
x = images[int(len(images) / duration * t)]
except Exception as e:
x = images[-1]
print(f"make_gif:{e}")
return x
clip = mpy.VideoClip(make_frame, duration=duration)
clip.write_gif(name, fps=len(images) / duration)
def main(video_path, output_folder):
output_file = Path(output_folder).joinpath(f"{Path(video_path).stem}_draw{Path(video_path).suffix}")
output_file.parent.mkdir(parents=True, exist_ok=True)
frame_bgr_list, frame_rgb_list, width, height, fps, fourcc = read_video(video_path)
make_gif(
[cv2.resize(draw_face_rectangle(frame), (540, 360), interpolation=cv2.INTER_CUBIC) for frame in frame_rgb_list],
f"{output_file.stem}.gif")
fourcc = cv2.VideoWriter.fourcc(*"MJPG")
video = cv2.VideoWriter(str(output_file), int(fourcc), fps, (width, height))
with alive_bar(total=len(frame_bgr_list)) as bar:
for frame in frame_bgr_list:
new_img = draw_face_rectangle(frame)
new_img = cv2.resize(new_img, (width, height))
video.write(new_img)
bar()
video.release()
if __name__ == '__main__':
video_file = r"F:pythonProjectProject_OpenCVmp4 est.mp4"
output_path = r"F:pythonProjectProject_OpenCVmp4"
main(video_file, output_path)
https://files-cdn.cnblogs.com/files/yunhgu/haarcascade_frontalface_alt.xmlhaarcascade_frontalface_alt