0, 주문
face_recognition은 역사상 가장 강력하고 간단한 얼굴 인식 프로젝트라고 주장합니다. 이 프로젝트는 소프트웨어 엔지니어링 개발자이자 컨설턴트 인 Adam Geitgey가 개발 한 것으로 알려졌으며, 그 강점은 업계 최고의 C ++ 오픈 소스 라이브러리 dlib의 딥 러닝 모델뿐만 아니라 대학에서 사용하는 얼굴 데이터 세트를 기반으로합니다. of Massachusetts Amn Labeled Faces in the Wild는 맨체스터 대학에서 제작했으며 99.38 %의 정확도로 인터넷에서 수집 한 13,000 개 이상의 얼굴 이미지를 포함하고 있습니다. 또한이 프로젝트에는 특히 Raspberry Pi 시스템과 호환되는 완전한 개발 문서 및 애플리케이션 케이스가 포함되어 있습니다. 단순함은 운영자가 Python 및 명령 줄 도구를 직접 사용하여 사람의 얼굴을 추출, 인식 및 조작 할 수 있다는 것입니다.
github 프로젝트의 포털 : https://github.com/ageitgey/face_recognition
카메라의 실시간 이미지 데이터를 얻기 위해 opencv를 통해 다음 데모 관련 이미지 처리 리소스를 얻은 다음 opencv 및 관련 요구 사항을 opencv 작업은 기본적으로 설치되어 있습니다. 일부 종속 라이브러리 및 구성 요소.
1. 환경 준비
1.1. face_recognition 라이브러리 설치 :
pip3 install face_recognition
1.2. dlib 라이브러리를 설치합니다 :
wget http://dlib.net/files/dlib-19.17.tar.bz2
tar jxvf dlib-19.17.tar.bz2
cd dlib-19.17
修改在dlib/cuda/目录下的该 cudnn_dlibapi.cpp文件中
gedit dlib/cuda/cudnn_dlibapi.cpp
找到对应的一行代码,进行删除(可以采用注释的方式删除)
forward_algo = forward_best_algo;
//forward_algo = forward_best_algo;
编译安装
sudo python3 setup.py install
1.3. 피클 설치
pip3 install pickle
2, 코딩
2.1. 얼굴 등록 및 분류 데이터 저장
import face_recognition
import cv2
import os
import pickle
print(cv2.__version__)
Encodings=[]
Names=[]
image_dir='/home/colin/works/face_recognition_dlib/face_register'
for root, dirs, files in os.walk(image_dir):
print(files)
for file in files:
path=os.path.join(root,file)
print(path)
name=os.path.splitext(file)[0]
print(name)
person=face_recognition.load_image_file(path)
encoding=face_recognition.face_encodings(person)[0]
Encodings.append(encoding)
Names.append(name)
print(Names)
with open('train.pkl', 'wb') as f:
pickle.dump(Names, f)
pickle.dump(Encodings, f)
2.2, 실시간 얼굴 인식
import os
import face_recognition
import cv2
import time
import numpy as np
import pickle
import image_shop
save_switch = 0
catch_max = 50
Encodings=[]
Names=[]
font = cv2.FONT_HERSHEY_SIMPLEX
#640 480 320 240
def gstreamer_pipeline(
capture_width=640,
capture_height=480,
display_width=640,
display_height=480,
framerate=30,
flip_method=0,
):
return (
"nvarguscamerasrc ! "
"video/x-raw(memory:NVMM), "
"width=(int)%d, height=(int)%d, "
"format=(string)NV12, framerate=(fraction)%d/1 ! "
"nvvidconv flip-method=%d ! "
"video/x-raw, width=(int)%d, height=(int)%d, format=(string)BGRx ! "
"videoconvert ! "
"video/x-raw, format=(string)BGR ! appsink"
% (
capture_width,
capture_height,
framerate,
flip_method,
display_width,
display_height,
)
)
def train_data_load( ):
global Names, Encodings
with open('train.pkl','rb') as f:
Names=pickle.load(f)
Encodings=pickle.load(f)
def catch_face(startX, endX, startY, endY, image):
global save_switch
face_pic = image[startY -50: endY + 50, startX-50 : endX + 50]
face_name = 'Unkown'
if face_pic.size > 0:
face_name = face_recognition_frame(face_pic)
return face_name
def face_recognition_frame(frame):
global Names, Encodings, font
frameSmall =cv2.resize(frame,(0,0),fx=.25, fy=.25)
frameRGB=cv2.cvtColor(frameSmall,cv2.COLOR_BGR2RGB)
facePositions=face_recognition.face_locations(frameRGB,model='cnn')
allEncodings=face_recognition.face_encodings(frameRGB,facePositions)
for (top,right,bottom,left),face_encoding in zip(facePositions,allEncodings):
name='Unkown'
matches=face_recognition.compare_faces(Encodings,face_encoding, tolerance=0.5)
if True in matches:
#first_match_index=matches.index(True)
#name=Names[first_match_index]
face_distance = face_recognition.face_distance(Encodings, face_encoding)
best_match_index = np.argmin(face_distance)
name = Names[best_match_index]
top = top * 4
right = right * 4
bottom = bottom * 4
left = left * 4
if top - 6 > 10:
mark_loc = (left, top-6)
else:
mark_loc = (left, bottom-6)
if name == 'Unkown':
cv2.rectangle(frame, (left, top), (right, bottom), (0,0,255), 2)
cv2.putText(frame, name, mark_loc, font, .5, (255,0,0), 2)
else:
cv2.rectangle(frame, (left, top), (right, bottom), (0,255,0), 2)
cv2.putText(frame, name, mark_loc, font, .5, (0,0,255), 2)
frame = image_shop.mark_add(left, right, top, bottom, frame)
#return name
resImage = frame
return resImage
def CatchVideo(window_name, camera_idx):
global save_switch, catch_switch, catch_max
cv2.namedWindow(window_name)
#CSI Camera for get pipeline
cap = cv2.VideoCapture(gstreamer_pipeline(flip_method=camera_idx), cv2.CAP_GSTREAMER)
while cap.isOpened():
ok, frame = cap.read() #read 1 frame
if not ok:
break
resImage = face_recognition_frame(frame)
#display
cv2.imshow(window_name, resImage)
c = cv2.waitKey(1)
if c & 0xFF == ord('q'):
break
#close
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
print('main menu:\n\t1 -reload face register\n\t2 -run\n\t3 -exit\n')
choose = input("input your choose:")
train_data_load()
CatchVideo("Find face", 0)
3. 데모 효과
참조 부록
1) 젯슨 나노 (
https://toptechboy.com/
) 와 같은 관련 오픈 소스 하드웨어 학습 영상을하고있는 유투브의 위인도있다. 2) 역사상 가장 단순한 얼굴 인식 프로젝트가 GitHub 트렌드리스트에있다.