保姆级教程:用Python的face_recognition库,5分钟搞定人脸检测+特征点标记
零基础玩转Python人脸识别5分钟实现智能美颜与表情分析记得第一次接触人脸识别技术时我盯着手机相册里自动分类的人物相册发了半天呆——这玩意儿到底是怎么认出我换了发型还长了胡子的作为Python初学者你可能觉得这种黑科技离自己很远但其实用face_recognition这个神器库5行代码就能让电脑学会看脸。今天我们就来场人脸识别极速入门不仅教你画框标点还会解锁几个让朋友惊呼这也行的趣味玩法。1. 环境配置避开99%新手会踩的坑在开始写代码前我们需要先搭建好工作环境。很多教程会直接让你pip install但根据我的教学经验有三大隐形杀手会导致安装失败Python版本陷阱face_recognition对3.6-3.9版本支持最稳定用3.10可能会遇到dlib编译错误操作系统差异Windows用户建议先安装CMakeMac用户需要Xcode命令行工具镜像源选择国内用户推荐使用清华源加速安装# 适用于Windows/Mac的万能安装命令 python -m pip install cmake python -m pip install face_recognition pillow opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple验证安装是否成功可以跑个简单测试import face_recognition print(face_recognition.__version__) # 应该输出类似1.3.0的版本号注意如果遇到dlib相关错误可以先尝试pip install dlib19.22.0指定版本2. 人脸检测实战从静态图片到动态捕捉2.1 基础版给照片画美颜框我们先实现最基础的人脸框标记功能。准备一张包含人脸的jpg图片比如自拍保存为test.jpg。from PIL import Image, ImageDraw import face_recognition def mark_faces(image_path): image face_recognition.load_image_file(image_path) face_locations face_recognition.face_locations(image) pil_image Image.fromarray(image) draw ImageDraw.Draw(pil_image) for top, right, bottom, left in face_locations: # 画半透明粉色矩形框类似美颜相机效果 draw.rectangle(((left, top), (right, bottom)), outline(255, 105, 180, 128), width5, fill(255, 182, 193, 32)) pil_image.show() return pil_image marked_image mark_faces(test.jpg)这段代码会用粉色半透明矩形标出人脸区域自动显示处理后的图片返回Pillow图像对象方便后续处理2.2 进阶版实时摄像头人脸追踪想让你的笔记本摄像头变成智能监控只需增加OpenCV支持import cv2 import numpy as np video_capture cv2.VideoCapture(0) while True: ret, frame video_capture.read() rgb_frame frame[:, :, ::-1] # BGR转RGB face_locations face_recognition.face_locations(rgb_frame) for top, right, bottom, left in face_locations: cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2) cv2.imshow(Video, frame) if cv2.waitKey(1) 0xFF ord(q): break video_capture.release() cv2.destroyAllWindows()3. 面部特征点解锁表情识别黑科技face_recognition最强大的功能之一是68点面部特征识别。这些关键点可以玩出很多花样特征点范围对应面部区域应用场景0-16下巴轮廓脸型分析17-21右眉毛情绪识别22-26左眉毛疲劳检测27-35鼻梁整形模拟36-41右眼眨眼计数42-47左眼视线追踪48-67嘴唇唇语识别def analyze_expression(image_path): image face_recognition.load_image_file(image_path) landmarks face_recognition.face_landmarks(image) if not landmarks: print(未检测到人脸) return for landmark in landmarks: # 计算嘴巴张开程度 mouth_top landmark[top_lip][0] mouth_bottom landmark[bottom_lip][0] mouth_open mouth_bottom[1] - mouth_top[1] # 计算眉毛上扬程度 left_eyebrow landmark[left_eyebrow] right_eyebrow landmark[right_eyebrow] eyebrow_raise (left_eyebrow[0][1] right_eyebrow[0][1]) / 2 print(f嘴巴张开度: {mouth_open:.2f} 像素) print(f眉毛上扬度: {eyebrow_raise:.2f} 像素) if mouth_open 15: print(检测到惊讶表情) elif eyebrow_raise 100: print(检测到皱眉表情) analyze_expression(selfie.jpg)4. 创意应用让人脸识别好玩起来4.1 自动添加虚拟眼镜利用特征点可以轻松实现AR效果def add_glasses(image_path, glasses_pathglasses.png): image Image.open(image_path) landmarks face_recognition.face_landmarks(np.array(image)) if not landmarks: return image glasses Image.open(glasses_path).convert(RGBA) for landmark in landmarks: # 计算眼镜位置和大小 left_eye landmark[left_eye] right_eye landmark[right_eye] eye_width right_eye[3][0] - left_eye[0][0] glasses glasses.resize((int(eye_width * 2.5), int(eye_width * 1.2))) # 放置在眼睛上方 pos_x left_eye[0][0] - eye_width//4 pos_y min(left_eye[0][1], right_eye[0][1]) - eye_width//3 image.paste(glasses, (pos_x, pos_y), glasses) return image4.2 人脸相似度PK想看看自己像哪个明星试试这个def compare_celebrities(your_image, celeb_images): your_face face_recognition.load_image_file(your_image) your_encoding face_recognition.face_encodings(your_face)[0] results [] for name, path in celeb_images.items(): celeb_face face_recognition.load_image_file(path) celeb_encoding face_recognition.face_encodings(celeb_face)[0] distance face_recognition.face_distance([your_encoding], celeb_encoding)[0] similarity (1 - distance) * 100 results.append((name, similarity)) return sorted(results, keylambda x: x[1], reverseTrue) # 示例用法 celeb_db { 刘德华: liudehua.jpg, 周杰伦: jay.jpg, 吴彦祖: daniel.jpg } print(compare_celebrities(my_photo.jpg, celeb_db)) # 输出类似[(周杰伦, 78.32), (刘德华, 65.41), (吴彦祖, 59.87)]5. 性能优化与常见问题当处理大量图片时这几个技巧能显著提升速度GPU加速安装dlib时启用CUDA支持批量处理使用batch_face_locations方法分辨率调整先缩小图片检测再在原图定位# 高性能处理示例 def fast_detection(image_paths): images [face_recognition.load_image_file(path) for path in image_paths] # 缩放到1/4大小检测 small_images [cv2.resize(img, (0,0), fx0.25, fy0.25) for img in images] # 批量检测 batch_locations face_recognition.batch_face_locations(small_images, number_of_times_to_upsample0) results [] for i, locations in enumerate(batch_locations): # 转换回原图坐标 orig_locations [(top*4, right*4, bottom*4, left*4) for (top, right, bottom, left) in locations] results.append((image_paths[i], orig_locations)) return results遇到问题先检查这几点图片是否包含正脸侧脸识别率较低光照是否充足暗光环境效果差人脸大小是否合适建议占图片1/4以上最后分享一个实用技巧用face_recognition.api直接调用底层功能可以绕过一些限制比如face_recognition.api.face_landmarks(face_image, modellarge)能获取更精细的68点特征。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2489505.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!