Skip to content

Instantly share code, notes, and snippets.

@cymerrad
Created November 18, 2019 16:04
Show Gist options
  • Save cymerrad/0a1883b2d7b4599c0fec2c113e995a68 to your computer and use it in GitHub Desktop.
Save cymerrad/0a1883b2d7b4599c0fec2c113e995a68 to your computer and use it in GitHub Desktop.
Script for detecting faces with argparse options
#!python3
import sys
import os
import numpy as np
import cv2
import argparse
METHOD = "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + METHOD)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Script for detecting and counting faces in the picture.")
parser.add_argument("file", help="Image file location.")
parser.add_argument("-s", "--scale", help="Scale up the image. Helps finding smaller faces.", type=int, default=1)
args = parser.parse_args()
image_location = args.file
assert(os.path.isfile(image_location))
image = cv2.imread(image_location)
scale = args.scale
dim = (image.shape[1] * scale, image.shape[0] * scale)
image_procured = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
# grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(image_procured)
if len(faces) == 0:
print("No faces found")
exit(1)
else:
print(f"Number of faces detected: {faces.shape[0]}")
for (x_, y_, w_, h_) in faces:
(x, y, w, h) = (x_ // scale, y_ // scale, w_ // scale, h_ // scale)
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 1)
cv2.imshow("Image with faces", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment