Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

import uuid import cv2 import numpy as np from libs.facerecognition import ALG class…

  1. User

    import uuid

    import cv2 import numpy as np

    from libs.face_recognition import ALG

    class FaceRecognition: """Service for using face recognition.""" def init(self, video_path, threshold=80): """ Sets model's parameters. Args: video_path (str): path to video threshold (int): model's threshold """ self.face_cascade_path = cv2.data.haarcascades + ALG self.face_cascade = cv2.CascadeClassifier(self.face_cascade_path) self.faces_list = [] self.names_list = [] self.threshold = 80 self.video = cv2.VideoCapture(video_path)

    def process(self):
        """
        Process of recognition faces in video by frames.
        Writes id as uuid4.
        Returns:
            tuple: with list of faces and list of names
        """
        name = uuid.uuid4()
        while True:
            ret, frame = self.video.read()
            if not ret:
                break
    
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = self.face_cascade.detectMultiScale(
                gray, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100))
    
            for (x, y, w, h) in faces:
                cur_face = gray[y:y + h, x:x + w]
                rec = cv2.face.LBPHFaceRecognizer.create()
                rec.train([cur_face], np.array(0))
                f = True
                for face in self.faces_list:
                    _, confidence = rec.predict(face)
                    if confidence < self.threshold:
                        f = False
    
                if f:
                    label = name
                    name = uuid.uuid4()
                    self.faces_list.append(cur_face)
                    self.names_list.append(label)
        self._close()
        return self.faces_list, self.names_list
    
    def _close(self):
        """
        Closes video and destroys all windows.
        Returns:
            None:
        """
        self.video.release()
        cv2.destroyAllWindows()
    

    Разбей обработку каждого кадра по 8 потокам

  2. Assistant

    To split the processing of each frame into 8 threads, you can use the multiprocessing module in Python. Here's an updated version of the FaceRecognition class that incorporates multiprocessing:

    import uuid
    import cv2
    import numpy as np
    from multiprocessing import Pool
    
    from libs.face_recognition import ALG
    
    
    class FaceRecognition:
        """Service for using face recognition."""
        def __init__(self, video_path, threshold=80, num_threads=8):
            """
            Sets model's parameters.
            Args:
                video_path (str): path to video
                threshold (int): model's threshold
                num_threads (int): number of threads to use for processing frames
            """
            self.face_cascade_path = cv2.data.haarcascades + ALG
            self.face_cascade = cv2.CascadeClassifier(self.face_cascade_path)
            self.faces_list = []
            self.names_list = []
            self.threshold = threshold
            self.video = cv2.VideoCapture(video_path)
            self.num_threads = num_threads
    
        def process_frame(self, frame):
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = self.face_cascade.detectMultiScale(
                gray, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100))
    
            for (x, y, w, h) in faces:
                cur_face = gray[y:y + h, x:x + w]
                rec = cv2.face.LBPHFaceRecognizer.create()
                rec.train([cur_face], np.array(0))
                f = True
                for face in self.faces_list:
                    _, confidence = rec.predict(face)
                    if confidence < self.threshold:
                        f = False
    
                if f:
                    label = uuid.uuid4()
                    self.faces_list.append(cur_face)
                    self.names_list.append(label)
    
        def process(self):
            """
            Process of recognition faces in video by frames.
            Writes id as uuid4.
            Returns:
                tuple: with list of faces and list of names
            """
            pool = Pool(self.num_threads)
            while True:
                ret, frame = self.video.read()
                if not ret:
                    break
                pool.apply_async(self.process_frame, args=(frame,))
    
            pool.close()
            pool.join()
            self._close()
            return self.faces_list, self.names_list
    
        def _close(self):
            """
            Closes video and destroys all windows.
            Returns:
                None:
            """
            self.video.release()
            cv2.destroyAllWindows()
    

    In this updated code, a Pool object from the multiprocessing module is created with the specified number of threads (num_threads). The process_frame method is modified to accept a single frame as an argument and perform the face recognition processing on that frame. The apply_async method of the Pool object is used to asynchronously apply the process_frame method to each frame in the video. Finally, the close and join methods of the Pool object are called to properly terminate the threads.

    Note that the actual speedup achieved will depend on the hardware configuration and the specific video being processed. Additionally, please ensure that the libs.face_recognition.ALG variable is correctly imported and used for the face recognition algorithm.