face detection from an image in python
Environment
- Python 2.7.15
- Windows 10
- opencv 3.4.3
Steps
- Start command prompt
- Install opencv. Reference the post face detection in python using webcam
- Create folder Image-Face-Detect
- Change to Image-Face-Detect folder
cd Image-Face-Detect
- Copy files haarcascade_frontalface_default.xml and haarcascade_eye.xml from C:\Users\user\Downloads\opencv\sources\data\haarcascades folder to D:\Temp\Image-Face-Detect
- Create file image_cv3.py
import numpy as np
import cv2
from matplotlib import pyplot as plt
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('harry-meghan-15.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
# waitKey(0) will display the window infinitely until any keypress
cv2.waitKey(0)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
- Start face detection
c:\Python27\python.exe image_cv3.py
- If I decrease the scaleFactor parameter to 1.01, I will get more detect regions.
Parameters
- scaleFactor: Parameter specifying how much the image size is reduced at each image scale.
- minNeighbors: Parameter specifying how many neighbors each candidate rectangle should have to retain it.This parameter will affect the quality of the detected faces: higher value results in less detections but with higher quality.
- minSize : Minimum possible object size. Objects smaller than that are ignored.