- import face_recognition
- import cv2
- import os
- import shutil
- """
- 根据失踪儿童照片所在目录known_children,获取人脸特征
- 匹配判断unknown_pic目录中人脸
- a1.jpg a2.jpg a3.jpg 是匹配的同一个人
- 图片来源可以是摄像头拍的照片、百度微博上爬取(比如搜索 街道 热闹)
- 结果输出到result目录(匹配的图片以 'A_' 前缀)
- 处理后的图片放入finish目录
- """
- # 当前目录
- GlobalDir = os.getcwd()
- # 储存失踪儿童的名字,取自文件名(不要使用中文,会乱码。需要的自行修改代码),用于标注
- names = []
- # 失踪儿童的脸型数据
- face_encodings = []
- # 脸型数据匹配的阈值
- recognizeTolerance=0.50
- def recognizeFace(unknown_image,filename, outputUnknow=False):
- """
- :param unknown_image: 需要进行判断的图片
- :param outputUnknow: 未找到匹配时,是否还输出图片
- """
- print(filename)
- unknown_face_encodings = face_recognition.face_encodings(unknown_image)
- face_locations = face_recognition.face_locations(unknown_image)
- finded=False
- for i in range(len(unknown_face_encodings)):
- unknown_encoding = unknown_face_encodings[i]
- face_location = face_locations[i]
- top, right, bottom, left = face_location
- results = face_recognition.compare_faces(face_encodings, unknown_encoding, tolerance=recognizeTolerance)
- for j in range(len(results)):
- if results[j]:
- finded=True
- name = names[j]
- cv2.putText(unknown_image, name, (left - 10, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
- cv2.rectangle(unknown_image, (left, top), (right, bottom), (0, 255, 0), 2)
- if (outputUnknow or finded):
- unknown_image_rgb = cv2.cvtColor(unknown_image, cv2.COLOR_BGR2RGB)
- # filename = time.strftime('%m%d_%H%M%S', time.localtime(time.time()))
- if finded:
- filename = 'A_'+filename # 有匹配脸型的文件名前缀 A
- cv2.imwrite(GlobalDir + "\\result\" + filename, unknown_image_rgb)
- def main():
- rootdir = GlobalDir + '\\known_children'
- list = os.listdir(rootdir)
- for i in range(0, len(list)):
- path = os.path.join(rootdir, list[i])
- if os.path.isfile(path) and path.endswith('.jpg'):
- image = face_recognition.load_image_file(path)
- # images.append(image)
- encoding = face_recognition.face_encodings(image)[0]
- face_encodings.append(encoding)
- names.append(path.split("\")[-1].split(".")[0])
- # unknown_image = face_recognition.load_image_file(GlobalDir + "\\unknown_pic\\a4.jpg")
- # analyzeFace(unknown_image, False)
- rootdir = GlobalDir+'\\unknown_pic'
- list = os.listdir(rootdir) # 列出文件夹下所有的目录与文件
- for i in range(0, len(list)):
- path = os.path.join(rootdir, list[i])
- if os.path.isfile(path) and path.endswith('.jpg'):
- unknown_image = face_recognition.load_image_file(path)
- recognizeFace(unknown_image,path.split("\")[-1], False)
- shutil.move(path, GlobalDir + '\\finish\\'+path.split("\")[-1])
- if __name__ == '__main__':
- main()
复制代码 |