OpenCV 人臉檢測(一)
- 2019 年 10 月 7 日
- 筆記
OpenCV的Haar級聯分類器可以通過對比分析相鄰影像區域的特徵來判斷給定影像或子影像與已知對象是否匹配,從而給影像進行分類。提取影像的細節對產生穩定可靠的分類結果很有用。這些提取的結果被稱為特徵。特徵的數量通常應該比像素數少得多。兩個影像的相似程度可以通過它們的特徵向量的距離來計算。
OpenCV的Haar級聯分類器具有尺度不變型(通過循環縮放影像再進行特徵比對來實現),即它在尺度縮放上具有魯棒性。但是,它不具備旋轉不變形。例如,Haar級聯分離器認為倒置的人臉影像和正立的人臉影像不一樣,且認為側面的人臉影像和正面的人臉影像也不一樣。
在OpenCV的源程式碼的副本中會有一個文件夾 sourcesdatahaarcascades。該文件夾包含了所有OpenCV的人臉檢測的XML文件,這些文件可用於檢測靜止影像、影片和攝影機所得到的影像中的人臉。

假設我們已將上述文件夾都拷貝到了項目文件夾中。下面的例子我們來檢測靜止影像中人臉,影片幀流中人臉檢測的方法也大致一樣。

import cv2 import numpy as np from matplotlib import pyplot as plt def detect(filename): img = cv2.imread(filename) gray =cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #檢測正臉 front_face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_frontalface_default.xml') faces0 = front_face_cascade.detectMultiScale(gray, 1.022, 5) print("共檢測到%d張人的正臉" %len(faces0)) #檢測側臉 profile_face_cascade = cv2.CascadeClassifier('./cascades/haarcascade_profileface.xml') faces1 = profile_face_cascade.detectMultiScale(gray, 1.2, 6) print("共檢測到%d張人的側臉" %len(faces1)) for (x, y, w, h) in faces0: cv2.rectangle(img, (x,y), (x+w,y+h), (0,0,255), 1) #畫紅色矩形框標記正臉 for (x, y, w, h) in faces1: cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 1) #畫綠色矩形框標記側臉 return img img = detect("physicists.jpg") plt.subplot(1,1,1) plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.title("OpenCV 人臉檢測",fontSize =16, color="b") plt.show()
檢測的結果如下(圖中不看鏡頭的那位大牛是發表「泡利不相容」原理的泡利,被檢測出了側臉):

附上detectMultiScale函數的參數說明:
''' detectMultiScale(...) method of cv2.CascadeClassifier instance detectMultiScale(image[, scaleFactor[, minNeighbors[, flags[, minSize[, maxSize]]]]]) -> objects . @brief Detects objects of different sizes in the input image. The detected objects are returned as a list . of rectangles. . . @param image Matrix of the type CV_8U containing an image where objects are detected. . @param objects Vector of rectangles where each rectangle contains the detected object, the . rectangles may be partially outside the original image. . @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. . @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have . to retain it. . @param flags Parameter with the same meaning for an old cascade as in the function . cvHaarDetectObjects. It is not used for a new cascade. . @param minSize Minimum possible object size. Objects smaller than that are ignored. . @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. . . The function is parallelized with the TBB library. . . @note . - (Python) A face detection example using cascade classifiers can be found at . opencv_source_code/samples/python/facedetect.py '''
- scaleFactor是每次迭代的縮放比例,越小(比1大)越可能檢測到更多的人臉,但更可能重複。
- minNeighbors 是每個人臉矩形保留盡量數目的最小值,整數。越小越可能檢測到更多的人臉。
- minSize 和maxSize 可以加入尺寸過濾。