import cv2 capture = cv2.VideoCapture(0) if not capture.isOpened: print('不能打开摄像头') exit(0) #加载人脸检测器 face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') #加载眼睛检测器 eye = cv2.CascadeClassifier('haarcascade_eye.xml') while True: ret, frame = capture.read() if frame is None: break gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) faces = face.detectMultiScale(gray) for x,y,w,h in faces: cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2) roi_eye = gray[y:y+h, x:x+w] eyes = eye.detectMultiScale(roi_eye) for (ex,ey,ew,eh) in eyes: cv2.circle(frame[y:y+h, x:x+w],(int(ex+ew/2), int(ey+eh/2)),int(max(ew,eh)/2),(0,255,0),2) cv2.imshow('faces',frame) key = cv2.waitKey(30) if key == 27: break修改代码
时间: 2023-11-22 14:04:56 浏览: 39
这段代码中有一些语法错误,我帮您修改并添加了注释说明:
```python
import cv2
# 打开摄像头
capture = cv2.VideoCapture(0)
if not capture.isOpened():
print('不能打开摄像头')
exit(0)
# 加载人脸检测器和眼睛检测器
face = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye = cv2.CascadeClassifier('haarcascade_eye.xml')
while True:
# 读取摄像头中的一帧图像
ret, frame = capture.read()
if frame is None:
break
# 将图像转换为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 检测人脸
faces = face.detectMultiScale(gray)
# 对每个人脸进行眼睛检测
for x, y, w, h in faces:
# 在人脸区域中检测眼睛
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
eyes = eye.detectMultiScale(roi_gray)
for ex, ey, ew, eh in eyes:
# 在眼睛区域中画出圆形
cv2.circle(roi_color,
(int(ex+ew/2), int(ey+eh/2)),
int(max(ew, eh)/2),
(0, 255, 0),
2)
# 在人脸区域画出矩形
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
# 显示图像
cv2.imshow('faces', frame)
key = cv2.waitKey(30)
if key == 27:
break
# 释放摄像头并关闭窗口
capture.release()
cv2.destroyAllWindows()
```
修改后的代码中,我们先打开了摄像头,然后加载了人脸检测器和眼睛检测器。接着,我们进入一个无限循环,在每次循环中读取摄像头中的一帧图像,并将其转换为灰度图像。然后,我们使用人脸检测器来检测人脸,并对每个人脸区域进行眼睛检测。最后,我们在眼睛区域中画出圆形,并在人脸区域画出矩形。最终,我们显示处理后的图像,并等待按下ESC键退出程序。