Opencv Q&A_4
2022/03/08 (晚了一天作笔记)
基于opencv和face_recognition模型的脸部识别
代码
import face_recognition import cv2 as cv import os import numpy as np def translocation(list_location): # 获取左上角坐标和右下角坐标 x_1 = list_location[3] #左上角x y_1 = list_location[0] #左上角y x_2 = list_location[1] #右下角x y_2 = list_location[2] #右下角y list = [x_1,y_1,x_2,y_2] return list dir_path = 'D:\work\\automation\Skill\Python\pythonWORK\cv\material\\face_recognition\AVENGERS' img_code_set = [] img_name = [] cap = cv.VideoCapture(0) cap.set(3,640) cap.set(4,480) dir = os.listdir(dir_path) for file in dir: img = face_recognition.load_image_file(dir_path + '\\' + file) img = cv.cvtColor(img,cv.COLOR_BGR2RGB) code = face_recognition.face_encodings(img)[0] name = file.rstrip('.jpg') img_code_set.append(code) img_name.append(name) while True: flag,img = cap.read() code = face_recognition.face_encodings(img) loc = face_recognition.face_locations(img) if len(code) != 0 and len(loc) != 0: code = code[0] loc = loc[0] distance = face_recognition.face_distance(img_code_set,code) the_most = np.argmin(distance) #返回最小值对应的序号 result_name = img_name[the_most] #对应识别结果列表的名字 cv.rectangle(img,(translocation(loc)[0],translocation(loc)[1]),(translocation(loc)[2],translocation(loc)[3]),(0,255,0),2) cv.rectangle(img,(translocation(loc)[0]-1,translocation(loc)[3]),(translocation(loc)[2]+1,translocation(loc)[3]+80), (0, 255, 0), cv.FILLED) cv.putText(img,result_name,(translocation(loc)[0]+10,translocation(loc)[3]+50),cv.FONT_HERSHEY_SIMPLEX, 2,color=(255, 255, 255), thickness=2) cv.imshow('img',img) cv.waitKey(1)
运行效果
遇到的问题
Q1:AttributeError: partially initialized module 'face_recognition' has no attribute 'load_image_file' (most likely due to a circular import)
A1:注意括号内(很可能是因为循环import),发现我的主函数文件名字和module:face_recognition重名了,导致自己对自己import
解决方法:改名
Q2:face_recognition模块函数使用注意事项
A2:
1. face_recognition.load_image_file()进行读取图片后需要进行色域转换(本次代码未使用)
2. face_recognition.face_locations()获得边框坐标带有多余的[],需去除多余的[],且获得坐标不规律,依次为:左上y、右下x、右下y、左上x
face_recognition.face_encodings()同理
3. face_recognition.compare_faces()输入:(样品图片集,待测试图片),所以输入图片集应为列表如:
result = face_recognition.compare_faces([jr_endcode],test_encode)
face_recognition.face_distance()同理
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通