运行程序时报如下错误
Traceback (most recent call last):
File "c:\Users\Administrator\AppData\Roaming\steamcode/project//_pty.temp.py", line 1, in <
module>
File "<string>", 1ine 14, in <module>
File "D:\教学文件\SteamCode\resources\app\python-env\win\lib\site-packages\mediapipe\python\
solutions\face_detection.py", line 82, in _init
super().init(
File"D:\教学文件\steamCode\resources\app\python-env\win\lib\site-packages\mediapipe\python\
solution_base.py", line 234, ininit
validated_graph.initialize(
FileNotFoundError: The path does not exist: D:\教学文件\steamCode\resources\app\python-env\win
\lib\site-packages\mediapipe/modules/face_detection/face_detection_short_range_cpu.binarypb
解决方法:发现安装目录中有中文,也不用重新安装,直接将中文“教学文件”改为英文“jxwj”就可以了。
import mediapipe as mp
import cv2
# 初始化摄像头
cap = cv2.VideoCapture(0)
# 初始化MediaPipe人脸检测
mp_face = mp.solutions.face_detection
face_scanner = mp_face.FaceDetection(min_detection_confidence=0.5)
# 定义绘图工具
mp_drawing = mp.solutions.drawing_utils # MediaPipe的绘图工具
# 开始实时检测
while cap.isOpened():
success, frame = cap.read()
if not success:
break
# 镜像翻转画面(让操作方向更自然)
frame = cv2.flip(frame, 1)
# 转换颜色格式(MediaPipe需要RGB格式)
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 进行人脸检测
results = face_scanner.process(rgb_frame)
# 如果有检测到人脸
if results.detections:
for detection in results.detections: # 遍历所有检测到的人脸
# 方法一:使用MediaPipe自带绘图工具快速绘制(紫色框+关键点)
mp_drawing.draw_detection(frame, detection)
# 方法二:手动绘制自定义效果(可选)
# 获取人脸位置信息
bbox = detection.location_data.relative_bounding_box
ih, iw, _ = frame.shape # 获取画面实际尺寸
x = int(bbox.xmin * iw)
y = int(bbox.ymin * ih)
w = int(bbox.width * iw)
h = int(bbox.height * ih)
# 绘制绿色矩形框(参数:画面,左上角坐标,右下角坐标,颜色,线宽)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 绘制可信度分数(参数:画面,文字内容,位置,字体,大小,颜色,线宽)
cv2.putText(frame,
f"{detection.score[0]:.0%}", # 格式化百分比显示
(x, y - 10),
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(0, 255, 0),
2)
# 显示实时画面
cv2.imshow('Face Tracking', frame)
# 按ESC键退出
if cv2.waitKey(5) & 0xFF == 27:
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
运行感受效果_人脸检测时
安装好库文件后,提示这个不存在。
Traceback (most recent call last):
File "c:\Users\Administrator\AppData\Roaming\steamcode/project//_pty.temp.py", line 1, in <
module>
File "<string>", 1ine 14, in <module>
File "D:\教学文件\SteamCode\resources\app\python-env\win\lib\site-packages\mediapipe\python\
solutions\face_detection.py", line 82, in _init
super().init(
File"D:\教学文件\steamCode\resources\app\python-env\win\lib\site-packages\mediapipe\python\
solution_base.py", line 234, ininit
validated_graph.initialize(
FileNotFoundError: The path does not exist: D:\教学文件\steamCode\resources\app\python-env\win
\lib\site-packages\mediapipe/modules/face_detection/face_detection_short_range_cpu.binarypb
安装好库文件后,运行感受效果_人脸检测时。提示这个不存在。