OpenCV Python Notes - Face and Feature Detection

OpenCV Python Notes - Face and Feature Detection
In [1]:
import numpy as np
import cv2
import matplotlib.pyplot as plt
In [2]:
def show_image(title, bgr_image):
    rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
    plt.axis('off')
    plt.title(title)
    plt.imshow(rgb_image)
    plt.show()


def show_bgra_image(title, bgra_image):
    b = bgra_image[:,:,0]
    g = bgra_image[:,:,1]
    r = bgra_image[:,:,2]
    a = bgra_image[:,:,3]
    rgba_image = cv2.merge([r, g, b, a])
    
    plt.axis('off')
    plt.title(title)
    plt.imshow(rgba_image)
    plt.show()

Template Matching

In [5]:
template = cv2.imread('template.jpg', cv2.IMREAD_GRAYSCALE)
frame = cv2.imread("players.jpg", cv2.IMREAD_GRAYSCALE)

show_image("Frame",frame)
show_image("Template",template)

result = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED)

min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
print(max_val,max_loc)
cv2.circle(result,max_loc, 15,255,2)
show_image("Matching",result)
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
0.46597495675086975 (132, 243)

Haar Cascading

In [4]:
img = cv2.imread("faces.jpeg", cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
path = "haarcascade_frontalface_default.xml"

face_cascade = cv2.CascadeClassifier(path)

faces = face_cascade.detectMultiScale(gray, scaleFactor=1.10, minNeighbors=5, minSize=(40,40))
print("number of faces:", len(faces))

for (x, y, w, h) in faces:
	cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
show_image("Image",img)
number of faces: 24
In [6]:
img = cv2.imread("faces.jpeg", cv2.IMREAD_COLOR)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
path = "haarcascade_eye.xml"

eye_cascade = cv2.CascadeClassifier(path)

eyes = eye_cascade.detectMultiScale(gray, scaleFactor=1.02,minNeighbors=20,minSize=(10,10))
print("number of eyes:", len(eyes))

for (x, y, w, h) in eyes:
	xc = (x + x+w)/2
	yc = (y + y+h)/2
	radius = w/2
	cv2.circle(img, (int(xc),int(yc)), int(radius), (255,0,0), 2)
show_image("Eyes",img)
number of eyes: 43