zoukankan      html  css  js  c++  java
  • python3使用opencv haarcascade_frontalface_alt 检测人脸

    #! /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

    不论你在什么时候开始,重要的是开始之后就不要停止。 不论你在什么时候结束,重要的是结束之后就不要悔恨。
  • 相关阅读:
    HashTable和HashMap
    TreeSet的剖析
    TreeMap--左旋右旋
    TreeMap的实现--红黑树
    AarryList和LinkedList比较
    由浅入深解析HashMap系列二---扩容
    由浅入深解析HashMap系列一---HashMap简单实现 增、删、查。
    由浅入深解析HashMap
    重入锁----ReentrantLock
    系统多语言实现
  • 原文地址:https://www.cnblogs.com/yunhgu/p/15263015.html
Copyright © 2011-2022 走看看