faceswap icon indicating copy to clipboard operation
faceswap copied to clipboard

Batch face extraction from video using CNN (GPU with CUDA) and recognition with HoG ... boom!

Open facepainter opened this issue 8 years ago • 19 comments

tl;dr - use super-fast precomputed CNN model in CPU to check a video (or whole bunch of images ) for faces (upto 128 fames at a time), then a really a well-optimised HoG face recognition method to extract any of those found faces as images.

As discussed in https://github.com/deepfakes/faceswap/pull/109

Just a stand alone proof of concept but really well tested. Best example I tried -with 2 reference images of Russell Crowe and the compeate HD Gladiator movie.

Using batch_size=128, skip_frames=12 - it spat out 698 perfect images of his face with 0 false positives in 8:34

No chopping videos, no sorting through extracted frames - just good shots of a recognised person in double quick time.

Should be self explanatory and I am already looking to add it using the current plug-in architecture for this project.

NB: As noted this requires dlib 19.9.99+ compiled with CUDA (and preferably AVX)

There is also a gist of this here that I will tweak some: https://gist.github.com/facepainter/adfaabe25831a7c9300bafd1b886e1c8

'''
Extract a known face from a video.

This class uses a combination of a deep learning CNN model to batch detect faces
in video frames, or a sequence of images in GPU with CUDA.
It then uses HoG to compare the detected faces with a computed reference set of face encodings.
'''

from os import path, listdir
from tqdm import tqdm

import cv2
import numpy
import face_recognition

class FaceGrab():
    '''Holds common settings for the reference encodings and processing parameters.
    so that multiple videos can be processed against them'''
    def __init__(self, reference, batch_size=128, skip_frames=1, tolerance=.5):
        self.batch_size = numpy.clip(batch_size, 2, 128)
        self.skip_frames = 0 if skip_frames < 0 else skip_frames + 1
        self.tolernace = numpy.clip(tolerance, .1, 1)
        self._process_frames = []
        self._orignal_frames = []
        self._reference_encodings = []
        self._total_extracted = 0
        # reference could be a single image or a directory of images
        # in either case we need the encoding data from the image(s)
        if path.isdir(reference):
            for file in listdir(reference):
                self.__parse_encoding(path.join(reference, file))
        elif path.isfile(reference):
            self.__parse_encoding(reference)
        if not self._has_encodings:
            print('Warning: no references have been detected')
            print('Are you sure the reference path is correct? {}'.format(reference))
            print('If you process a video *all* detected faces will be extracted')

    def __parse_encoding(self, image_path):
        image = face_recognition.load_image_file(image_path)
        encoding = face_recognition.face_encodings(image)
        if numpy.any(encoding):
            self._reference_encodings.append(encoding[0])
            print('Found ref #{} in {}'.format(len(self._reference_encodings), image_path))

    @property
    def _has_encodings(self):
        return numpy.any(self._reference_encodings)

    @staticmethod
    def __downsample(frame):
        '''Downscale frame of video by 4 for faster recognition processing.
        also converts cv2's BGR to face_recognition's RGB'''
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        small_frame = small_frame[:, :, ::-1] # BGR->RGB for detect (fuck I love numpy)
        return small_frame

    @staticmethod
    def __extract(frame, location):
        '''Upscale coordinates in face_location by 4 and extract face'''
        top, right, bottom, left = location
        return frame[top * 4:bottom * 4, left * 4:right * 4] # I mean it is awesome

    def __recognise(self, encoding):
        '''Checks the unknown_encoding exits and compares against the known encoding(s).
        With the current tolerance settings.
        If no encodings at all are present then all faces are classed as recognized.'''
        if not self._has_encodings:
            return True
        if numpy.any(encoding):
            return numpy.any(face_recognition.compare_faces(self._reference_encodings,
                                                            encoding[0],
                                                            self.tolernace))
        return False

    def __batch(self, batch_count, frame_count, output_directory):
        '''Finds all faces in batch of frames using precomputed CNN model (in GPU)
        Then checks all the found faces against a set of known reference encodings.
        If there is a match it saves the found face to the output directory'''
        # we use _process_frames to do the *opposite* of number_of_times_to_upsample
        location_sets = face_recognition.batch_face_locations(self._process_frames,
                                                              batch_size=self.batch_size)
        extracted = 0
        with tqdm(total=len(location_sets)) as progress:
            for position, locations in enumerate(location_sets):
                frame = frame_count - self.batch_size + position
                progress.update(1)
                progress.set_description('Batch #{} (recognized {})'.format(batch_count, extracted))
                for face_number, face_location in enumerate(locations):
                    face = self.__extract(self._orignal_frames[position], face_location)
                    if self.__recognise(face_recognition.face_encodings(face)):
                        extracted += 1
                        self._total_extracted += 1
                        output_path = path.join(output_directory,
                                                '{}-{}-{}.jpg'.format(frame,
                                                                      position,
                                                                      face_number))
                        face = cv2.resize(face, (256, 256))
                        cv2.imwrite(output_path, face)
                        # frame v.unlikely to have target face more than once
                        break

    def process(self, input_path, output_directory='.'):
        '''Opens a input and hands of batches off images/frames for processing'''
        self._total_extracted = 0
        frame_count = 0
        batch_count = 0
        sequence = cv2.VideoCapture(input_path)
        total_frames = int(sequence.get(cv2.CAP_PROP_FRAME_COUNT))
        total_to_process = int(total_frames/self.skip_frames)
        total_batches = int(total_frames / self.skip_frames / self.batch_size)
        total_refs = len(self._reference_encodings)
        print('Opening {}'.format(input_path))
        print('Checking faces against {} reference{}'.format(total_refs,
                                                             's' if total_refs > 1 else ''))
        print('Processing {}/{} frames. {} batches of {}'.format(total_to_process,
                                                                 total_frames,
                                                                 total_batches,
                                                                 self.batch_size))
        with tqdm(total=total_frames) as progress:
            while sequence.isOpened():
                ret, frame = sequence.read()
                if not ret:
                    break
                frame_count += 1
                progress.update(1)
                progress.set_description('Total (extracted {})'.format(self._total_extracted))
                if self.skip_frames > 0 and frame_count % self.skip_frames:
                    continue
                self._process_frames.append(self.__downsample(frame))
                self._orignal_frames.append(frame)
                if len(self._process_frames) == self.batch_size:
                    batch_count += 1
                    self.__batch(batch_count, frame_count, output_directory)
                    self._process_frames = []
                    self._orignal_frames = []
        progress.close()
        print('\nFound and grabbed {} faces'.format(self._total_extracted))

if __name__ == '__main__':
    # Just for example...
    OUTPUT_DIR = r'.\output'
    REF_DIR = r'D:\ref'
    TEST_VIDEO = TEST_VIDEO = r'D:\Videos\Movies\Gladiator (2000)\Gladiator (2000).avi'
    # reference can be a path to a single file (e.g.  D:\images\someone.jpg)
    # or a path to an directory an images sequence (e.g.  D:\images)
    FG = FaceGrab(reference=REF_DIR, batch_size=128, skip_frames=12)
    # input_video can be a path to a single file (e.g.  D:\video\foo.mp4)
    # or a path to an image sequence (e.g.  D:\frames\img_%04d.jpg)
    # which will read image like img_0000.jpg, img_0001.jpg, img_0002.jpg, ...)
    FG.process(input_path=TEST_VIDEO, output_directory=OUTPUT_DIR)

facepainter avatar Feb 09 '18 03:02 facepainter

i tried it. extracted faces are not same dimension?

3xtr3m3d avatar Feb 10 '18 16:02 3xtr3m3d

Yea get the code from the gist, the bit posted here has a couple of bugs https://gist.github.com/facepainter/adfaabe25831a7c9300bafd1b886e1c8

facepainter avatar Feb 10 '18 17:02 facepainter

yeah thats the one i'm using. it works perfectly. only problem im having is images are different size

3xtr3m3d avatar Feb 10 '18 17:02 3xtr3m3d

@3xtr3m3d - Ah try it now...was just missing

face = cv2.resize(face, (256, 256))

before

cv2.imwrite(output_path, face)

have updated it here too :)

facepainter avatar Feb 10 '18 17:02 facepainter

great 👍 now its extracting images in 256x256 dimension

3xtr3m3d avatar Feb 10 '18 17:02 3xtr3m3d

edit: solved it. i had dlib from the pip. updated dlib from pip first then changed the dlib.cp36-win_amd64.pyd file with the one i compiled with cuda.

gonna leave this here in case someone has the same problem.

Didnt use ref file and got this error any ideas?

pip list gave me: face-recognition (1.2.1) face-recognition-models (0.3.0)

Traceback (most recent call last): File "FaceGrab.py", line 182, in FG.process(input_path=TEST_VIDEO, output_directory=OUTPUT_DIR) File "FaceGrab.py", line 157, in process output_directory) File "FaceGrab.py", line 98, in __batch batch_size=self.batch_size) File "C:\IntelPython3\lib\site-packages\face_recognition\api.py", line 144, in batch_face_locations raw_detections_batched = _raw_face_locations_batched(images, number_of_times_to_upsample, batch_size) File "C:\IntelPython3\lib\site-packages\face_recognition\api.py", line 127, in _raw_face_locations_batched return cnn_face_detector(images, number_of_times_to_upsample, batch_size=batch_size) Boost.Python.ArgumentError: Python argument types in cnn_face_detection_model_v1.call(cnn_face_detection_model_v1, list, int) did not match C++ signature: call(class cnn_face_detection_model_v1 {lvalue}, class boost::python::list {lvalue} imgs, int upsample_num_times=0, int batch_size=128) call(class cnn_face_detection_model_v1 {lvalue}, class boost::python::api::object img, int upsample_num_times=0)

Jack29913 avatar Feb 10 '18 19:02 Jack29913

@Apollo122 - yeah it doesn't do much checking of paths or anything...incidentally - if you want to match all faces in the input you can just pass an empty directory as the reference.

facepainter avatar Feb 10 '18 22:02 facepainter

Could you maybe take image folder as an argument? We often use pictures from various sources so filenames are different.

Another thing is that sometimes output image is too zoomed in.

Jack29913 avatar Feb 10 '18 23:02 Jack29913

Hi, thanks for this post. You can bring this to this repo, but as a new command more than as a plugin. Let me explain. Actual extracting is done like this:

  • script/extract.py reads images (read logic)
  • FaceFilter filters out unrecognised faces (filter logic)
  • extract plugins apply the extraction on it (extract logic)

In the code you posted there is:

  • a big part of read logic that reads a video
  • a part of face filtering logic
  • no real extract logic, just a crop (As far as I understand)

So your code is interesting, but the read logic has to be put in some scripts/extract-video.py . The face filter logic has to be check to be merged with FaceFilter existing logic.

In the #54 PR, I started doing a convert-video in order to be able to directly process a video, so your code is the same but for the extract step.

I don't know if you understood, as it is not that easy to explain. Feel free to discuss it here. In case it is too much of work, just create a folder tools/, put the file in it, and do a PR. We will see what we can do with it later on.

Clorr avatar Feb 11 '18 17:02 Clorr

@Clorr - hey :)

Yes - totally understand - was really just to show what I mean in terms of functionality rather than actual code that would be used - a general gist :)

  • a big part of read logic that reads a video sure, here cv2 reads video (or images as long as they are sequentially named and the same dimensions e.g. %04d.jpg - like the output of ffmpeg or whatever) - this can be broken up easily, the updated gist is much clearer in this... but I will implement as "scripts/extract-video.py" as suggested for any pull request.

  • no real extract logic Yeah I just did the crop as it simplifies it massively - but the principal is the same - use the landmarks to rotate and align, just using the encoding/crop here for simplicity.

  • The face filter logic has to be check to be merged with FaceFilter existing logic. This bit I have working it tests already so hopefully I will pull soon - just super busy!

Top work on all the other stuff the project is looking (and working) great :)

Hopefully I will pull request this week with "this kind of thing" implemented.

facepainter avatar Feb 13 '18 04:02 facepainter

cannot understand what differences versus existing recognition

iperov avatar Feb 13 '18 09:02 iperov

@iperov it takes a whole video with multiple filter images. so its useful to extract faces lets say from a movie.

@facepainter output images are too zoomed in. could you please check this discussion and if possible implement face_alignment pytorch cnn.

Jack29913 avatar Feb 14 '18 20:02 Jack29913

Took a shot and added an option (-ps 1.25) to FacePainters Gist to add padding around detected faces: https://gist.github.com/k3erg/a042265da4649e5a2b688f393db217a6

It basically scales the detected rect AFTER doing all detection stuff and reextracts the face with padding. It takes care of keeping the rect inside the movie frame as well. So, no changes in the behaviour, just adaptable zoom.

k3erg avatar Feb 16 '18 21:02 k3erg

@Clorr @k3erg @Apollo122 @3xtr3m3d @iperov

Just to note I added the extract align features by slightly porting the Umeyama algorithm from scikit and the DetectedFace class from here. Now the recognition rate is much higher and as long as landmarks can be detected then it spits out transformed/aligned faces as needed.

You can test in the gist.

Again hope to actually integrate this into a pull request here this week (work is just silly atm :()

facepainter avatar Feb 21 '18 00:02 facepainter

@facepainter Have you implemented pytorch face_alignment cnn? dlib's CNN is buggy. Check the referenced discussion

Jack29913 avatar Feb 21 '18 06:02 Jack29913

@facepainter what is gist ?

iperov avatar Feb 21 '18 07:02 iperov

What's the status here? Can it be PRed? let me know when we can close this

Clorr avatar Mar 10 '18 10:03 Clorr

No movement on this for a long time, and plugin structure has changed significantly, so closing. If anyone wants to adapt and PR this, please feel free.

torzdf avatar Nov 04 '18 17:11 torzdf