opencv-python人臉識別初探
阿新 • • 發佈:2018-11-10
推薦博文:
3、《Face Recognition with Python》
程式碼:
import cv2 import sys # Get user supplied values imagePath = 'test.png' # sys.argv[1] cascPath = "haarcascade_frontalface_default.xml" #訓練後的分類器 # Create the haar cascade faceCascade = cv2.CascadeClassifier(cascPath) # Read the image image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the image faces = faceCascade.detectMultiScale( gray, scaleFactor=1.2, #比例因子 minNeighbors=2, #最小鄰臉數 minSize=(30, 30) #視窗大小 #flags = cv2.CV_HAAR_SCALE_IMAGE ) print("Found {0} faces!".format(len(faces))) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow("Faces found", image) cv2.waitKey(0)
效果:
修改成實時人臉識別模式(有點容易誤判)
程式碼:
import cv2 import sys import numpy as np # Get user supplied values cap =cv2.VideoCapture(0) # sys.argv[1] cascPath = "haarcascade_frontalface_default.xml" #訓練後的分類器 # Create the haar cascade faceCascade = cv2.CascadeClassifier(cascPath) while(True): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, #比例因子 minNeighbors=3, #最小鄰距 minSize=(30, 30) #視窗大小 ) print("Found {0} faces!".format(len(faces))) for (x, y, w, h) in faces: cv2.rectangle( frame, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow("Faces found", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
效果: