python3.6 open3.4 人臉定位案例

python3.6 open3.4 人臉識別。搞了半天,記錄下走過的坑。
能夠檢測人臉,還有眼睛。
先上效果:
python

代碼以下:code

import cv2
import sys
import os
# Get user supplied values
imagePath = './heying5.jpg'#sys.argv[1]
# Create the haar cascade

faceCascade=cv2.CascadeClassifier('D:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')#
eyeCascade = cv2.CascadeClassifier("D:\opencv\sources\data\haarcascades\haarcascade_eye.xml")
if 
# Read the image
image = cv2.imread(imagePath)#2
# cv2.imshow("frame" , image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)#3
# cv2.imshow("frame" , gray)
# Detect faces in the image
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.15,minNeighbors=5,minSize=(5,5))
    #flags=cv2.CASCADE_SCALE_IMAGE

#faceCascade.detectMultiScale(gray, scaleFactor = 1.3, minNeighbors = 4, minSize = (32, 32))
print("Found {0} faces!".format(len(faces)))#5
for (x, y, w, h) in faces:
    cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) #6
    roi_gray_img = gray[y:y + h, x:x + w]
    roi_img = image[y:y + h, x:x + w]
    eyes = eyeCascade.detectMultiScale(roi_gray_img, 1.3, 5)
    for eye_x, eye_y, eye_w, eye_h in eyes:
        cv2.rectangle(roi_img, (eye_x, eye_y), (eye_x + eye_w, eye_y + eye_h), (255, 0, 0), 2)

cv2.imshow("Faces found", image)#7
cv2.waitKey(0) #8


注意:
坑1:orm

faceCascade=cv2.CascadeClassifier('D:\opencv\sources\data\haarcascades\haarcascade_frontalface_default.xml')

不少文章直接寫成:xml

faceCascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

假如代碼運行出錯,找不到haarcascade_frontalface_default.xml文件,必需要單獨安裝opencv的exe的壓縮包,解壓縮後,裏面會有此xml文件,而後把全地址填到這裏。博客

坑2:
不少博客是基於opencv2.x版本的,個人環境是opencv3.4的。3.4中cv2.cv已經沒了....通常狀況直接把cv2.cv.xxx改爲cv2.xxx就行。假如不行的,百度看看換成其餘什麼了。it

相關文章
相關標籤/搜索