人脸识别代码,当人脸占比大于40%时,人动就截取图片,人离开也截取图片
时间: 2024-03-19 13:45:25 浏览: 122
好的,我可以为您提供一种基于Python的人脸识别代码,可以实现您的需求。您需要安装OpenCV和dlib库。
首先,导入必要的库:
```python
import cv2
import dlib
```
然后,使用dlib库的人脸检测器和68个关键点检测器来识别人脸:
```python
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
cap = cv2.VideoCapture(0) # 打开摄像头
while True:
ret, frame = cap.read() # 读取视频流
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 转换为灰度图像
faces = detector(gray)
for face in faces:
landmarks = predictor(gray, face) # 获取68个关键点
left_eye_ratio = get_eye_ratio(landmarks, [36, 37, 38, 39, 40, 41])
right_eye_ratio = get_eye_ratio(landmarks, [42, 43, 44, 45, 46, 47])
eye_ratio = (left_eye_ratio + right_eye_ratio) / 2
if eye_ratio > 0.3: # 如果眼睛开着
x, y, w, h = face.left(), face.top(), face.width(), face.height()
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # 绘制矩形框
cv2.imwrite("face.jpg", frame) # 保存图片
else:
cv2.imwrite("no_face.jpg", frame) # 保存图片
cv2.imshow("Video", frame) # 显示视频流
if cv2.waitKey(1) == ord('q'): # 按q键退出
break
cap.release()
cv2.destroyAllWindows()
```
其中,get_eye_ratio函数用于计算眼睛的长宽比:
```python
def get_eye_ratio(landmarks, eye_points):
left_eye = []
right_eye = []
for i in eye_points:
x = landmarks.part(i).x
y = landmarks.part(i).y
left_eye.append((x, y))
left_eye = np.array(left_eye, dtype=np.int32)
mask = np.zeros((gray.shape[0], gray.shape[1]))
cv2.fillConvexPoly(mask, left_eye, 1)
eye = cv2.bitwise_and(gray, gray, mask=mask)
_, thresh = cv2.threshold(eye, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if len(contours) == 0:
return 0
cnt = contours[0]
area = cv2.contourArea(cnt)
if area == 0:
return 0
x, y, w, h = cv2.boundingRect(cnt)
ratio = w / h
return ratio
```
最后,当人脸占比大于40%时,保存图片,当没有检测到人脸时,也保存图片。
希望这个代码对您有所帮助!
阅读全文