G1Pola/face_detect.py

110 lines
3.3 KiB
Python

#!/usr/bin/python3
################################################################################
# Authors: Fred (support@qo-op.com) + Mark
# Version: 0.1
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
################################################################################
import cv2
import os
import time
import subprocess
import numpy as np
cascPath = "./haarcascade_frontalface_default.xml"
shot_images_path = "./tmp/"
processed_images_path = "./processed_images"
#if directories dont exist, make them
if not os.path.isdir(shot_images_path):
os.mkdir(shot_images_path)
if not os.path.isdir(processed_images_path):
os.mkdir(processed_images_path)
print("FaceDetect READY...")
sleep_count = 20
while 1:
files = os.listdir(shot_images_path)
if not files:
time.sleep(0.1)
if sleep_count ==20:
#print("sleeping ...")
sleep_count = 0
sleep_count+=1
else:
for file in files:
# Get user supplied values
imagePath = os.path.join(shot_images_path,file)
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
#may read while image is not finished loading thus this work-around
try:
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
except Exception:
print("Could not read image... Retrying...")
break
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
#scaleFactor=1,
minNeighbors=1,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE#cv.CV_HAAR_SCALE_IMAGE
)
print("Found {0} face(s)!".format(len(faces)))
#iterate through the found faces
count = 0
for (x, y, w, h) in faces:
x1 = int(x - w*0.05)
y1 = int(y - h*0.1)
x2 = int(x + w*1.1)
y2 = int(y + h*1.25)
#check if 'face' is really a face...
check_gray = gray[y1:y2,x1:x2]
check = faceCascade.detectMultiScale(
check_gray,
#scaleFactor=1,
minNeighbors=1,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE
)
if len(faces)==1:
#We found ONE face :D
#reshape to print width and height and write to ./processed_images
(img_h,img_w) = check_gray.shape
fw = 384/img_w
img_out = cv2.resize(check_gray,(0,0), fx = fw, fy = fw )
#brighten up the image
added_brightness = 10
img_out = img_out +added_brightness
img_out = np.where((255-img_out)<added_brightness, 255, img_out + added_brightness )
file_name = "./processed_images/face.jpg"
cv2.imwrite(file_name, img_out)
count+=1
os.remove(imagePath)