Path: blob/master/FaceDetectionComparison/face_detection_dlib_hog.py
3118 views
import argparse1import os2import time34import cv25import dlib678def detectFaceDlibHog(detector, frame, inHeight=300, inWidth=0):910frameDlibHog = frame.copy()11frameHeight = frameDlibHog.shape[0]12frameWidth = frameDlibHog.shape[1]13if not inWidth:14inWidth = int((frameWidth / frameHeight) * inHeight)1516scaleHeight = frameHeight / inHeight17scaleWidth = frameWidth / inWidth1819frameDlibHogSmall = cv2.resize(frameDlibHog, (inWidth, inHeight))2021frameDlibHogSmall = cv2.cvtColor(frameDlibHogSmall, cv2.COLOR_BGR2RGB)22faceRects = detector(frameDlibHogSmall, 0)23print(frameWidth, frameHeight, inWidth, inHeight)24bboxes = []25for faceRect in faceRects:2627cvRect = [28int(faceRect.left() * scaleWidth),29int(faceRect.top() * scaleHeight),30int(faceRect.right() * scaleWidth),31int(faceRect.bottom() * scaleHeight),32]33bboxes.append(cvRect)34cv2.rectangle(35frameDlibHog,36(cvRect[0], cvRect[1]),37(cvRect[2], cvRect[3]),38(0, 255, 0),39int(round(frameHeight / 150)),404,41)42return frameDlibHog, bboxes434445if __name__ == "__main__":4647parser = argparse.ArgumentParser(description="Face detection")48parser.add_argument("--video", type=str, default="", help="Path to video file")49args = parser.parse_args()5051source = args.video52hogFaceDetector = dlib.get_frontal_face_detector()5354outputFolder = "output-hog-videos"55if not os.path.exists(outputFolder):56os.makedirs(outputFolder)5758if source:59cap = cv2.VideoCapture(source)60outputFile = os.path.basename(source)[:-4] + ".avi"61else:62cap = cv2.VideoCapture(0, cv2.CAP_V4L)63outputFile = "grabbed_from_camera.avi"64hasFrame, frame = cap.read()6566vid_writer = cv2.VideoWriter(67os.path.join(outputFolder, outputFile),68cv2.VideoWriter_fourcc("M", "J", "P", "G"),6915,70(frame.shape[1], frame.shape[0]),71)7273frame_count = 074tt_dlibHog = 07576while True:77hasFrame, frame = cap.read()78if not hasFrame:79break8081frame_count += 182t = time.time()8384outDlibHog, bboxes = detectFaceDlibHog(hogFaceDetector, frame)85tt_dlibHog += time.time() - t86fpsDlibHog = frame_count / tt_dlibHog8788label = "DLIB HoG; FPS : {:.2f}".format(fpsDlibHog)89cv2.putText(90outDlibHog,91label,92(10, 50),93cv2.FONT_HERSHEY_SIMPLEX,941.3,95(0, 0, 255),963,97cv2.LINE_AA,98)99100cv2.imshow("Face Detection Comparison", outDlibHog)101102vid_writer.write(outDlibHog)103104if frame_count == 1:105tt_dlibHog = 0106107k = cv2.waitKey(5)108if k == 27:109break110111cv2.destroyAllWindows()112vid_writer.release()113114115