Last active
October 3, 2020 14:56
-
-
Save RoshanTanisha/f2883a18a7017c10321f8230aef9de0c to your computer and use it in GitHub Desktop.
Simple script to detect face from camera using OpenCV
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
import numpy as np | |
import os, sys, math | |
import matplotlib.pyplot as plt | |
import cv2 | |
import copy | |
def convert_image_to_BW(image): | |
bw_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
return cv2.cvtColor(bw_img, cv2.COLOR_GRAY2BGR) | |
class FaceDetection(object): | |
def __init__(self, haar_cascade_file_path): | |
self.hcfp = haar_cascade_file_path | |
self._load_classifier() | |
def _load_classifier(self): | |
self.classifier = cv2.CascadeClassifier(self.hcfp) | |
def detect_faces(self, image): | |
copied_image = copy.deepcopy(image) | |
gray = convert_image_to_BW(image) | |
faces = self.classifier.detectMultiScale(gray, 1.3, 5) | |
for (x, y, w, h) in faces: | |
tagged_image = cv2.rectangle(copied_image, (x, y), (x + w, y + h), (255, 0, 0), 2) | |
return copied_image | |
def read_video(video_path: os.path = 0, process_frame = lambda x: x, save_processed_video=False): | |
video_stream = cv2.VideoCapture(video_path) | |
if save_processed_video: | |
fourcc = cv2.VideoWriter_fourcc(*'MJPG') | |
video_writer = cv2.VideoWriter(os.path.join(data_dir_path, 'processed_video.avi'), fourcc, video_stream.get(5), (int(video_stream.get(3)), int(video_stream.get(4)))) | |
print(video_stream.isOpened()) | |
try: | |
while True: | |
ret, frame = video_stream.read() | |
processed_frame = process_frame(frame) | |
if save_processed_video: | |
video_writer.write(processed_frame) | |
horizontal_show = np.concatenate((frame, processed_frame), axis=1) | |
cv2.imshow('processed_frame', horizontal_show) | |
if cv2.waitKey(1) & 0xFF == ord('q'): | |
break | |
finally: | |
video_stream.release() | |
cv2.destroyAllWindows() | |
if __name__ == '__main__': | |
data_dir_path = os.path.join(os.path.dirname(os.getcwd()), 'data') | |
fd_obj = FaceDetection(os.path.join(data_dir_path, 'haarcascade_frontalface_default.xml')) | |
read_video(process_frame=fd_obj.detect_faces, save_processed_video=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment