OpenCV-Python Cheat Sheet: From Importing Images to Face Detection

https://heartbeat.fritz.ai/opencv-python-cheat-sheet-from-importing-images-to-face-detection-52919da36433

Face Detection

Can’t have dog pictures here, sadly 🙁

Photo by Free-Photos from Pixabay
import cv2
image_path = "./Path/To/Photo.extension"
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
image = cv2.imread(image_path)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(
gray,
scaleFactor= 1.1,
minNeighbors= 5,
minSize=(10, 10)
)
faces_detected = format(len(faces)) + " faces detected!"
print(faces_detected)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (255, 255, 0), 2)
viewImage(image,faces_detected)

The detectMultiScale function is a general function that detects objects. Since we’re calling it on the face cascade, that’s what it detects.

The detectMultiScale function takes 4 parameters

  • The first parameter is the grayscale image.
  • The second parameter is the scaleFactor. Since some faces may be closer to the camera, they would appear bigger than the faces in the back. The scale factor compensates for this.
  • The detection algorithm uses a moving window to detect objects. minNeighbors defines how many objects are detected near the current one before it declares the face found.
  • minSize, meanwhile, gives the size of each window.

2 faces detected!

Leave a Reply

Your email address will not be published. Required fields are marked *

Next Post

mattdesl/canvas-sketch

Sat Apr 20 , 2019
https://github.com/mattdesl/canvas-sketch

You May Like