fanfuhan OpenCV 教學091 ~ opencv-091-對象檢測(HAAR級聯檢測器使用) [人臉 定位/偵測/抓取/擷取]
fanfuhan OpenCV 教學091 ~ opencv-091-對象檢測(HAAR級聯檢測器使用) [人臉 定位/偵測/抓取/擷取]
資料來源: https://fanfuhan.github.io/
https://fanfuhan.github.io/2019/05/09/opencv-091/
GITHUB:https://github.com/jash-git/fanfuhan_ML_OpenCV
HAAR級聯檢測器,OpenCV中的HAAR級聯檢測器支持人臉檢測、微笑、眼睛與嘴巴檢測等,通過加載這些預先訓練的HAAR模型數據可以實現相關的對象檢測。
C++
#include <opencv2/opencv.hpp> #include <iostream> using namespace cv; using namespace std; CascadeClassifier faceDetector; String haar_data_file = "D:/opencv-4.0.0/opencv/build/etc/haarcascades/haarcascade_frontalface_alt_tree.xml"; int main(int artc, char** argv) { Mat frame, gray; vector<Rect> faces; VideoCapture capture(0); faceDetector.load(haar_data_file); namedWindow("frame", WINDOW_AUTOSIZE); while (true) { capture.read(frame); cvtColor(frame, gray, COLOR_BGR2GRAY); equalizeHist(gray, gray); faceDetector.detectMultiScale(gray, faces, 1.2, 1, 0, Size(30, 30), Size(400, 400)); for (size_t t = 0; t < faces.size(); t++) { rectangle(frame, faces[t], Scalar(0, 0, 255), 2, 8, 0); } char c = waitKey(10); if (c == 27) { break; } imshow("frame", frame); } waitKey(0); return 0; }
Python
""" 对象检测(HAAR级联检测器使用) """ import cv2 as cv capture = cv.VideoCapture(0) detector = cv.CascadeClassifier(cv.data.haarcascades + "haarcascade_frontalface_alt.xml") while True: ret, image = capture.read() if not ret: break faces = detector.detectMultiScale(image, scaleFactor=1.05, minNeighbors=1, minSize=(30, 30), maxSize=(200, 200)) for x, y, width, height in faces: cv.rectangle(image, (x, y), (x + width, y + height), (0, 0, 255), 2, cv.LINE_8, 0) cv.imshow("faces", image) c = cv.waitKey(50) if c == 27: break cv.destroyAllWindows()