安装python包
pip install cvzone
pip install mediapipe
# main
# 2022/2/15
import cv2
import cvzone
from cvzone.FaceMeshModule import FaceMeshDetector
# 检测人脸
detector = FaceMeshDetector(maxFaces=1)
cap = cv2.VideoCapture(0)
while True:
success, img = cap.read()
img, faces = detector.findFaceMesh(img)
if faces:
face = faces[0]
pointLeft = face[145] # 左眼中心点坐标
pointRight = face[375] # 右眼中心点坐标
# 绘制人眼中心点并连线
cv2.line(img, pointLeft, pointRight, (0, 200, 0), 3)
cv2.circle(img, pointLeft, 5, (255, 0, 255), cv2.FILLED)
cv2.circle(img, pointRight, 5, (255, 0, 255), cv2.FILLED)
w, _ = detector.findDistance(pointLeft, pointRight) # 保持人脸到摄像头50cm下测量
W = 6.3 # 真实人脸间距 6.3cm
# Finding the Focal Length
# d= 50 # 保持人脸到摄像头50cm的距离
# f=(w*d)/W
# print(f)
# Finding distance
f = 840 # 根据相机标定的结果
d = (W * f) / w
print(d)
cvzone.putTextRect(img, f'Depth:{int(d)}cm', (face[10][0] - 100, face[10][1] - 50), scale=2)
cv2.imshow("Image", img)
cv2.waitKey(5)