当前位置:网站首页>Opencv face detection Haar cascade (1)

Opencv face detection Haar cascade (1)

2022-07-08 02:20:00 So come on

The goal is : Determine the position of the face in the picture , And draw a rectangular box .

1. The core principle

1) Use Haar-like Feature detection

Be careful : The characteristic value is the sum of white rectangular pixels minus the sum of black rectangular pixels

2Integral Image : Integral graph accelerates feature calculation

3AdaBoost : Select key features , Face and non face classification

4Cascade : cascade , Weak classifiers become strong classifiers

It provides four cascaded classifiers ( For the front of the face ):

(1)haarcascade_frontalface_alt.xml (FA1):  22 stages and 20 x 20 haar features

(2)haarcascade_frontalface_alt2.xml (FA2): 20 stages and 20 x 20 haar features

(3)haarcascade_frontalface_alt_tree.xml (FAT):  47 stages and 20 x 20 haar features

(4)haarcascade_frontalface_default.xml (FD):  25 stages and 24 x 24 haar features

# 1  Import library 
import cv2
import numpy as np
import matplotlib.pyplot as plt

# 2  Method : display picture 
def show_iamge(image, title, pos):
    # BGR to RGB
    img_RGB = image[:,:,::-1]
    plt.subplot(1, 1, pos)
    plt.title(title)
    plt.imshow(img_RGB)
    plt.axis("off")  #  Turn off the axis 

# 3  Method : Draw the face detected in the picture 
def plot_rectangle(image, faces):
    #  Get the detected face data , return 4 It's worth : coordinate (x,y),  Wide and high width, height
    for (x, y, w, h) in faces:
        cv2.rectangle(image, (x, y), (x+w, y+h), (255, 0, 0), 3)
    return image

# 4  The main function 
def main():
    #  5  Read a picture 
    image = cv2.imread("wedding photos.jpg")

    # 6  Convert to grayscale images 
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 7  adopt OpenCV Own method cv2.CascadeClassifier() Load cascade classifiers 
    face_alt2 = cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")

    # 8  Pass the first 7 Step , Detect the face in the image 
    face_alt2_detect = face_alt2.detectMultiScale(gray)

    # 9  Draw the face detected in the picture 
    face_alt2_result = plot_rectangle(image.copy(), face_alt2_detect)

    # 10  Create a canvas 
    plt.figure(figsize=(9, 6))
    plt.suptitle("Face detection with Haar Cascade", fontsize=14, fontweight="bold")

    # 11  Finally, the whole detection effect is displayed 
    show_iamge(face_alt2_result, "face_alt2", 1)

    plt.show()
# 12  Main program entry 
if __name__ == '__main__':
    main()

原网站

版权声明
本文为[So come on]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130539412335.html