-
-
Save re4388/0cac9877922859b254a7cbb890afb118 to your computer and use it in GitHub Desktop.
a2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # code origin: https://www.kaggle.com/timesler/facial-recognition-model-in-pytorch | |
| class DetectionPipeline: | |
| """Pipeline class for detecting faces in the frames of a video file.""" | |
| def __init__(self, detector, n_frames=None, batch_size=60, resize=None): | |
| """Constructor for DetectionPipeline class. | |
| Keyword Arguments: | |
| n_frames {int} -- Total number of frames to load. These will be evenly spaced | |
| throughout the video. If not specified (i.e., None), all frames will be loaded. | |
| (default: {None}) | |
| batch_size {int} -- Batch size to use with MTCNN face detector. (default: {32}) | |
| resize {float} -- Fraction by which to resize frames from original prior to face | |
| detection. A value less than 1 results in downsampling and a value greater than | |
| 1 result in upsampling. (default: {None}) | |
| """ | |
| self.detector = detector | |
| self.n_frames = n_frames | |
| self.batch_size = batch_size | |
| self.resize = resize | |
| def __call__(self, filename): | |
| """Load frames from an MP4 video and detect faces. | |
| Arguments: | |
| filename {str} -- Path to video. | |
| """ | |
| # Create video reader and find length | |
| v_cap = cv2.VideoCapture(filename) | |
| v_len = int(v_cap.get(cv2.CAP_PROP_FRAME_COUNT)) | |
| # Pick 'n_frames' evenly spaced frames to sample | |
| if self.n_frames is None: | |
| sample = np.arange(0, v_len) | |
| else: | |
| sample = np.linspace(0, v_len - 1, self.n_frames).astype(int) | |
| # Loop through frames | |
| faces = [] | |
| frames = [] | |
| for j in range(v_len): | |
| success = v_cap.grab() | |
| if j in sample: | |
| # Load frame | |
| success, frame = v_cap.retrieve() | |
| if not success: | |
| continue | |
| frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) | |
| frame = Image.fromarray(frame) | |
| # Resize frame to desired size | |
| if self.resize is not None: | |
| frame = frame.resize([int(d * self.resize) for d in frame.size]) | |
| frames.append(frame) | |
| # When batch is full, detect faces and reset frame list | |
| if len(frames) % self.batch_size == 0 or j == sample[-1]: | |
| faces.extend(self.detector(frames)) | |
| frames = [] | |
| v_cap.release() | |
| return faces | |
| # ---------------- | |
| # Define face detection pipeline | |
| detection_pipeline = DetectionPipeline(detector=mtcnn, batch_size=60, resize=0.25) | |
| # Load filenameand find faces | |
| faces = detection_pipeline(filename) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment