python - 如何使用面部识别在opencv上获得人脸的侧面视图?
问题描述
我尝试使用 Haar 级联haarcascade_profileface.xml
并 lbpcascade_profileface.xml
一起调用,但相机甚至根本没有打开。在我希望两个 haar 级联工作的情况下,如何解决这个问题?这是在树莓派上完成的,也可以在 Linux 和 Windows 上运行。请尽量解释清楚!这是代码:
import numpy as np
import cv2
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
face_cascade = cv2.CascadeClassifier('Haarcascade_profileface.xml')
side_face_cascade = cv2.CascadeClassifier('lbpcascade_frontalface_improved.xml')
prevTime = 0
## This will get our web camera
cap = cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
while True:
retval, frame = cap.read()
if not retval:
break
_, img = cap.read() ## This gets each frame from the video, cap.read returns 2 variables flag - indicate frame is correct and 2nd is f
##img = cv2.imread('Z.png') Then we get our image we want to use
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # This method only works on gray skin images, so we have to convert the gray scale to rgb image
faces = face_cascade.detectMultiScale(gray, 1.1, 5) ## Next, we detect the faces
if len(faces) > 0:
print("[INFO] found {0} faces!".format(len(faces)))
GPIO.output(18,GPIO.HIGH)
else:
print("No face")
GPIO.output(18,GPIO.LOW)
curTime = time.time()
sec = curTime - prevTime
prevTime = curTime
fps = 1/(sec)
str = "FPS : %0.1f" % fps
for (x, y, w, h) in faces: ## We draw a rectangle around the faces so we can see it correctly
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0)) ## The faces will be a list of coordinates
cv2.putText(img, 'Myface', (x, y), font, fontScale=1, color=(255,70,120),thickness=2)
side_faces = side_face_cascade.detectMultiScale(gray, 1.1, 5)
for (ex, ey, ew, eh) in side_faces: ## We draw a rectangle around the faces so we can see it correctly
cv2.rectangle(img, (ex, ey), (ex+ew, ey+eh), (255, 0, 0)) ## The faces will be a list of coordinates
cv2.putText(img, 'Myface', (ex, ey), font, fontScale=1, color=(255,70,120),thickness=2)
cv2.putText(frame, 'Number of Faces Detected: ' + str, (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))
cv2.imshow('img', img) ## Last we show the image
x = cv2.waitKey(30) & 0xff
if x==27:
break
## Press escape to exit the program
cap.release()
解决方案
OpenCV 实际上提供了一个“侧面”检测器。它被称为“haarcascade_profileface.xml”。你可以做:
side_face_cascade = cv2.CascadeClassifier('haarcascade_profileface.xml')
side_faces = side_face_cascade.detectMultiScale(gray, 1.1, 5)
推荐阅读
- python - 如何将字符串转换为原始十六进制?
- asp.net-mvc - 在 Azure 上部署 ASP.NET MVC 初始化字符串的格式不符合从索引 0 开始的规范
- flutter - Flutter:未处理的异常:尝试获取 PlacesAutocomplete 时参数无效
- c++ - 如果通过在 C++ 中输入值仍然“更改”了 const 值,我该怎么办?
- javascript - 如何在网页上测试静态 javascript?
- push-notification - 如何注册展会推送通知设备
- django-views - /view_appointment/make_appointment/ 处的 UnboundLocalError
- javascript - 如何使用javascript使多个div一个接一个地出现?
- python - 训练期间的 Huggingface 错误:AttributeError: 'str' object has no attribute 'size'
- flutter - Flutter:更改 URL 策略会导致应用重新加载