本文共 1853 字,大约阅读时间需要 6 分钟。
首先,安装必要的Python库。可以通过以下命令安装:
pip install dlib
dlib提供了丰富的预训练模型,用于人脸检测和关键点定位。在官方网站或GitHub上下载以下文件:
将文件解压后,模型即可使用。
以下是基本的实现代码,供您参考:
import cv2import dlib# 获取人脸检测器detector = dlib.get_frontal_face_detector()# 读取图片def detect_faces(img_path): img = cv2.imread(img_path) if not img: return [] # 将图片转换为灰度格式 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 检测人脸 dets = detector(gray, 1) faces = [] for det in dets: left = det.left() top = det.top() right = det.right() bottom = det.bottom() # 在图片上画出人脸区域 cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 2) faces.append((left, top, right, bottom)) return faces# 示例使用img_path = "your_image.jpg"faces = detect_faces(img_path)print(f"检测到 {len(faces)} 个人脸") 以下是关键点定位的实现代码:
import cv2import dlib# 加载预训练模型predictor_path = "C:\\Python36\\Lib\\site-packages\\dlib-data\\shape_predictor_68_face_landmarks.dat"predictor = dlib.shape_predictor(predictor_path)# 读取图片img_path = "img/meinv.png"img = cv2.imread(img_path)# 转换为灰度gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)# 初始化人脸检测器detector = dlib.get_frontal_face_detector()# 检测人脸dets = detector(gray, 1)for face in dets: # 获取关键点位置 shape = predictor(img, face) for part in shape.parts(): x, y = part.x, part.y cv2.circle(img, (x, y), 2, (0, 255, 0), 1) cv2.imshow("image", img) cv2.waitKey(0)cv2.destroyAllWindows() 安装问题:如果安装过程中出现错误,请检查网络连接并尝试重新安装。
模型加载失败:确保模型文件路径正确,并且文件名与预期一致。
图片读取失败:检查图片路径是否正确,且图片格式支持(JPG、PNG等)。
检测不到人脸:调整阈值或检查图片质量,确保人脸区域清晰可见。
以下是一些有用的资源链接:
欢迎加入我们的技术交流群,和同行一起探讨计算机视觉相关技术。请扫描下方微信二维码并备注昵称+学校/公司+研究方向,例如:张三+上海交大+视觉SLAM。
以上就是使用dlib库进行人脸检测与关键点定位的完整实践指南,希望对您有所帮助!
转载地址:http://gzaq.baihongyu.com/