亲宝软件园·资讯

展开

Python opencv人脸检测 Python3.6.0+opencv3.3.0人脸检测示例

mumu_1233 人气:1

网上有很多关于Python+opencv人脸检测的例子,并大都附有源程序。但是在实际使用时依然会遇到这样或者那样的问题,在这里给出常见的两种问题及其解决方法。

先给出源代码:(如下)

import cv2
import numpy as np

cv2.namedWindow("test")
cap=cv2.VideoCapture(0)
success,frame=cap.read()

classifier=cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")

while success:
 success,frame=cap.read()
 size=frame.shape[:2]
 image=np.zeros(size,dtype=np.float16)
 image=cv2.cvtColor(frame,cv2.cv.CV_BGR2GRAY)
 cv2.equalizeHist(image,image)
 divisor=8
 h,w=size
 minSize=(w/divisor,h/divisor)
 faceRects=classifier.detectMultiScale(image,1.2,2,cv2.CASCADE_SCALE_IMAGE,minSize)
 if len(faceRects)> 0:
 for faceRect in faceRects:
  x,y,w,h=faceRect
  cv2.circle(frame,(x+w/2,y+h/2),min(w/2,h/2),(255,0,0))
  cv2.circle(frame,(x+w/4,y+h/4),min(w/8,h/8),(255,0,0))
  cv2.circle(frame,(x+3*w/4,y+h/4),min(w/8,h/8),(255,0,0))
  cv2.rectangle(frame,(x+3*w/4,y+3*h/4),(x+5*w/8,y+7*h/8),(255,0,0))
 cv2.imshow("test",frame)
 key=cv2.waitKey(10)
 c=chr(key&255)
 if c in ['q','Q',chr(27)]:
 break
 cv2.destroyWindow("test")

运行后出现问题一:

Traceback (most recent call last):
File “E:/facepy/m.py”, line 14, in
image=cv2.cvtColor(frame,cv2.cv.CV_BGR2GRAY)
AttributeError: module ‘cv2.cv2' has no attribute ‘cv'

解决方法:

cv2.cv.CV_BGR2GRAY是Opencv 2.x的变量,在Opencv 3.3中无法识别,所以应该替换成:

image=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

修改完成后,继续运行,又出现问题二:

Traceback (most recent call last):
File “E:/facepy/m.py”, line 19, in
faceRects=classifier.detectMultiScale(image,1.2,2,cv2.CASCADE_SCALE_IMAGE,minSize)
TypeError: integer argument expected, got float

解决方法:

由于minSize传到detectMultiScale函数的值不是整数导致的导致出现错误,所以这里我们需要强制转换minSize的值为整数: minSize =(w//divisor, h//divisor)  或者 minSize=(int(w/divisor),int(h/divisor))

加载全部内容

相关教程
猜你喜欢
用户评论