OpenCV人脸检测_眼睛检测之在人脸以外找眼睛
今天在学习opencv人脸检测时,发现眼睛检测是在人脸以外寻找眼睛的,源代码如下:
import cv2
def detect():
face_cascade = cv2.CascadeClassifier('../cascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('../cascades/haarcascade_eye.xml')
camera = cv2.VideoCapture(0)
while (True):
ret , frame = camera.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)
roi_gray = gray[y: y+h, x: x+w]
eyes = eye_cascade.detectMultiScale(roi_gray, 1.8, 5, 0, (40,40))
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(img, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
cv2.imshow("camera", frame)
if cv2.waitKey(int(1000 / 12)) & 0xff == ord("q"):
break
camera.release()
cv2.destroyAllWindows()
detect()
效果图如下:
后来一检查代码才发现问题,
cv2.rectangle(img, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
这里面的img指的就是整张图片,而非人脸区域,因此要在该代码前面加上一句
roi_color = img[y:y + h, x:x + w]
完整代码如下:
import cv2
def detect():
face_cascade = cv2.CascadeClassifier('../cascades/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('../cascades/haarcascade_eye.xml')
camera = cv2.VideoCapture(0)
while (True):
ret , frame = camera.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
img = cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)
roi_gray = gray[y: y+h, x: x+w]
eyes = eye_cascade.detectMultiScale(roi_gray, 1.8, 5, 0, (40,40))
roi_color = img[y:y + h, x:x + w]
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
cv2.imshow("camera", frame)
if cv2.waitKey(int(1000 / 12)) & 0xff == ord("q"):
break
camera.release()
cv2.destroyAllWindows()
detect()
现在的效果图如下: