Face Recognition là việc nhận diện người dựa vào khuôn mặt của mình trong hình ảnh hoặc video. Hai trong những các việc của Face Recognition là:
Face Verification: Ánh xạ 1-1, giữa khuôn phương diện của một người đưa vào hệ thống nhận diện cùng với một người đã biết trước. Face Verification trả lời câu hỏi: Đây liệu có phải là anh/chị/ông/bà A không?Face Identification: Ánh xạ 1-nhiều, giữa giữa khuôn khía cạnh của một người đưa vào khối hệ thống nhận diện với cùng 1 tập những người đã biết trước vào CSDL. Face Identification trả lời câu hỏi: Đây là ai?
Trong bài bác này, họ sẽ thực hiện Face
Net mã sản phẩm để tiến hành bài toán Face Recognition.
Bạn đang xem: Hệ thống phát hiện khuôn mặt (Face detection system)
2. Face
Net model.
Face
Net là một mô hình nhận dạng khuôn mặt được phát triển bởi Florian Schroff với đồng nghiệp tại Google trong bài bác báo năm 2015 của họ gồm tiêu đề Face
Net: A Unified Embedding for Face Recognition và Clustering. Trong mô hình này, hình ảnh của một khuôn mặt sẽ được trích xuất những đặc điểm chất lượng cao và màn trình diễn thành vector 128 phần tử (Face Embedding vector 128 chiều).
Face
Net, that directly learns a mapping from face images to lớn a compact Euclidean space where distances directly correspond khổng lồ a measure of face similarity— Face
Net: A Unified Embedding for Face Recognition & Clustering, 2015.
Mô hình là một trong mạng CNN được đào tạo trải qua hàm Triplet Loss. Nó khuyến khích các Face Embedding vector của thuộc một tín đồ trở bắt buộc giống nhau hơn (khoảng cách nhỏ dại hơn), vào khi các Face Embedding vectơ của rất nhiều người không giống nhau sẽ trở nên ít tương đương nhau hơn (khoảng cách lớn hơn). Việc tập trung vào huấn luyện và đào tạo một quy mô để tạo thành các Face Embedding vector thẳng (thay vày trích xuất chúng từ một lớp trung gian của tế bào hình) là một trong đổi mới đặc biệt quan trọng của Face
Net so với VGGFace.
Our method uses a deep convolutional network trained to directly optimize the embedding itself, rather than an intermediate bottleneck layer as in previous deep learning approaches.— Face
Net: A Unified Embedding for Face Recognition & Clustering, 2015.
Các Face Embedding vectors này kế tiếp được sử dụng như thể Input để huấn luyện và giảng dạy một mô hình phân nhiều loại trên bộ dữ liệu tiêu chuẩn chỉnh về Face Recognition, đạt được hiệu quả state-of-the-art.
Bài báo cũng nói đến các ứng dụng khác của Face Embedding vector, ví dụ như phân nhiều để nhóm những khuôn mặt tương tự nhau dựa vào các đặc điểm được trích xuất của chúng. Có thể nó Face
Net là một mã sản phẩm rất khỏe mạnh và hiệu quả cho việc Face Recognition, với một loạt các ứng dụng khác.
3. Load a Face
Net model in Keras
Có một số dự án cung ứng các điều khoản để huấn luyện và giảng dạy các mô hình dựa trên Face
Net (sử dụng Pre-trained Face
Net model). Chắc rằng nổi nhảy nhất là dự án công trình Open
Face. Trong dự án náy, các mô hình Face
Net được xây dựng và giảng dạy bằng Py
Torch framework. Keras cũng có 1 dự án tương tự, gọi là Keras Open
Face, tuy vậy tại thời điểm viết bài, các quy mô đó yêu mong Python 2, vấn đề này hạn chế bọn họ rất các trong câu hỏi tiếp cận các tính ưng ưu việt của Python 3. Vì vậy mà Keras Open
Face không nhiều được sử dụng.
Một dự án trông rất nổi bật khác là facenet của David Sandberg. Nó cung ứng các quy mô Face
Net được tạo ra và đào tạo bằng Tensor
Flow framework. Dự án công trình có vẻ trả thiện, tuy vậy tại thời khắc viết bài này không cung cấp thiết lập cũng như cách sử dụng API của nó. Một dự án có vẻ có lợi hơn là Keras Face
Net của Hiroki Taniai. Trong dự án công trình này, tác giả hỗ trợ một tập lệnh để thay đổi mô hình Inception Res
Net v1 tự Tensor
Flow sang Keras. Một Pre-trained model bằng Keras cũng được cung cấp để chuẩn bị sẵn sàng để sử dụng. Chúng ta sẽ sử dụng mô hình Keras Face
Net của Hiroki Taniai trong bài viết này. Nó sẽ được đào tạo và giảng dạy trên tập tài liệu MS-Celeb-1M. Mô hình có thể được cài xuống tự đây.
4. Detect Faces
Phần này, bọn họ cũng áp dụng thư viện MTCNN tương tự như như trong bài xích trước. Code như sau:
# function for face detection with mtcnnfrom PIL import Imagefrom numpy import asarrayfrom mtcnn.mtcnn import MTCNN# extract a single face from a given photographdef extract_face(filename, required_size=(160, 160)): # load image from file image = Image.open(filename) # convert to RGB, if needed image = image.convert('RGB') # convert khổng lồ array pixels = asarray(image) # create the detector, using mặc định weights detector = MTCNN() # detect faces in the image results = detector.detect_faces(pixels) # extract the bounding box from the first face x1, y1, width, height = results<0><'box'> # bug fix x1, y1 = abs(x1), abs(y1) x2, y2 = x1 + width, y1 + height # extract the face face = pixels
Chúng ta sẽ thực hiện hàm này để trích xuất những Face Embedding vector để cung ứng làm đầu vào cho mô hình Face
Net vào phần tiếp theo.
5. Face Recognition
Trong phần này, bọn họ sẽ cải cách và phát triển một hệ thống Face Recongtion để dự đoán danh tính của một khuôn mặt. Mã sản phẩm sẽ được đào tạo và huấn luyện và kiểm tra bằng phương pháp sử dụng bộ dữ liệu 5 Celebrity Faces Dataset, bao hàm rất nhiều bức ảnh của năm người nổi tiếng khác nhau. Mô hình MTCNN vẫn được dùng làm thực hiện Face Detection, mô hình Face
Net được thực hiện để Face Embedding vector cho mỗi khuôn phương diện được phát hiện, sau đó chúng ta sẽ trở nên tân tiến một mô hình phân loại bằng thuật toán SVM để tham gia đoán tính danh của khuôn phương diện đó.
5.1 5 Celebrity Faces Dataset
5 Celebrity Faces Dataset là một trong bộ dữ liệu nhỏ dại chứa những bức hình ảnh của hồ hết người nổi tiếng khác nhau. Nó bao gồm các bức ảnh của: Ben Affleck, Elton John, Jerry Seinfeld, Madonna cùng **. Bộ tài liệu đã được cung ứng bởi Dan Becker, chúng ta có thể tải xuống miễn tầm giá từ Kaggle. Lưu giữ ý, nên phải có tài năng khoản Kaggle để download xuống tập tài liệu này.
Tải xuống tập dữ liệu, tệp tin data.zip 2.5MB cùng giải nén nó trong thư mục thao tác làm việc trên sản phẩm công nghệ tính của bạn với tên thư mục 5-Celeb-face-dataset. Bây giờ các bạn sẽ có một thư mục với kết cấu sau:
5-celebrity-faces-dataset├── train│ ├── ben_afflek│ ├── elton_john│ ├── jerry_seinfeld│ ├── madonna│ └── mindy_kaling└── val ├── ben_afflek ├── elton_john ├── jerry_seinfeld ├── madonna └── mindy_kaling
Chúng ta có thể thấy 2 thư mục: folder train chứa tài liệu để huấn luyện mã sản phẩm và folder val chứa tài liệu để chuẩn xác hoặc kiểm soát model. Quan sát vào một số bức ảnh trong từng thư mục, bạn cũng có thể thấy rằng các khuôn mặt có khá nhiều hướng, tia nắng và form size khác nhau. Điều quan trọng là mỗi bức ảnh chỉ tất cả một khuôn mặt của người đó. Nếu bạn muốn sử dụng dữ liệu của riêng bạn, hãy thu thập và tổ chức triển khai dữ liệu tương tự như vậy này.
5.2 Detect Faces
Bước đầu tiên cần có tác dụng là phát hiện nay khuôn mặt trong những bức ảnh. Ta sẽ sử dụng hàm extract_face() vào phần trước để gia công việc này.
# python extract_faces.py --dp '5-celebrity-faces-dataset/train/ben_afflek/'# demonstrate face detection on 5 Celebrity Faces Datasetfrom os import listdirfrom PIL import Imagefrom numpy import asarrayfrom matplotlib import pyplotfrom mtcnn.mtcnn import MTCNNimport argparseimport tensorflow as tfconfig_tf = tf.compat.v1.Config
Proto()config_tf.gpu_options.allow_growth = Truesession = tf.compat.v1.Session(config=config_tf)# extract a single face from a given photographdef extract_face(filename, required_size=(160, 160)):# load image from fileimage = Image.open(filename)# convert to lớn RGB, if neededimage = image.convert('RGB')# convert khổng lồ arraypixels = asarray(image)# create the detector, using default weightsdetector = MTCNN()# detect faces in the imageresults = detector.detect_faces(pixels)# extract the bounding box from the first facex1, y1, width, height = results<0><'box'># bug fixx1, y1 = abs(x1), abs(y1)x2, y2 = x1 + width, y1 + height# extract the faceface = pixels
Parser()ap.add_argument('-dp', '--data_path', required=True)args = vars(ap.parse_args())i = 1# enumerate filesfor filename in listdir(args<'data_path'>):# pathpath = args<'data_path'> + filename# get faceface = extract_face(path)print(i, face.shape)# plotpyplot.subplot(2, 7, i)pyplot.axis('off')pyplot.imshow(face)i += 1pyplot.show()if __name__ == '__main__':main()
Tiếp theo, họ sẽ không ngừng mở rộng ví dụ này để làm việc cùng với toàn album ảnh trong những thư mục train và val. Ta viết hàm load_faces() như sau:
# load images và extract faces for all images in a directorydef load_faces(directory):faces = list()# enumerate filesfor filename in listdir(directory):# pathpath = directory + filename# get faceface = extract_face(path)# storefaces.append(face)return faces
# load a dataset that contains one subdir for each class that in turn contains imagesdef load_dataset(directory):X, y = list(), list()# enumerate folders, on per classfor subdir in listdir(directory):# pathpath = directory + subdir + '/'# skip any files that might be in the dirif not isdir(path):continue# load all faces in the subdirectoryfaces = load_faces(path)# create labelslabels =
X.extend(faces)y.extend(labels)return asarray(X), asarray(y)
Việc còn lại là hotline hàm này với các thư mục train cùng val để tạo ra các Face Embedding của từng khuôn mặt và thực hiện chúng nhằm tạo model phân loại.
Gộp toàn bộ lại, ta tất cả code khá đầy đủ như sau:
# USEAGE python extract_faces_dataset.py --train_data 5-celebrity-faces-dataset/train/ --val_data 5-celebrity-faces-dataset/val/ --save_data 5-celebrity-faces-dataset.npz# face detection for the 5 Celebrity Faces Datasetfrom os import listdirfrom os.path import isdirfrom PIL import Imagefrom numpy import savez_compressedfrom numpy import asarrayfrom mtcnn.mtcnn import MTCNNimport argparseimport tensorflow as tfconfig_tf = tf.compat.v1.Config $ python extract_faces_dataset.py --train_data 5-celebrity-faces-dataset/train/ --val_data 5-celebrity-faces-dataset/val/ --save_data 5-celebrity-faces-dataset.npz >loaded 17 examples for class: elton_john>loaded 19 examples for class: madonna>loaded 13 examples for class: ben_afflek>loaded 22 examples for class: mindy_kaling>loaded 21 examples for class: jerry_seinfeld(92, 160, 160, 3) (92,)>loaded 5 examples for class: elton_john>loaded 5 examples for class: madonna>loaded 5 examples for class: ben_afflek>loaded 5 examples for class: mindy_kaling>loaded 5 examples for class: jerry_seinfeld Bước tiếp theo là tạo ra các Face Embedding vectors của mỗi khuôn mặt. Ghi nhớ lại rằng Face Embedding là 1 trong những vectơ thay mặt đại diện cho các điểm lưu ý được trích xuất tự khuôn mặt. Các vectors này sau đó rất có thể được dùng để tính toán, đối chiếu với nhau, hoặc tạo nên một cỗ phân các loại để định danh cho từng khuôn mặt. Ở phần này, chúng ta sẽ dùng quy mô Pre-trained Face Đầu tiên, bọn họ sẽ phát âm vào các khuôn mặt đã tạo ra ở bước trước. ...# load the face datasetdata = load('5-celebrity-faces-dataset.npz')train ...# load the facenet modelmodel = load_model('facenet_keras.h5')print('Loaded Model') ...# scale px valuesface_pixels = face_pixels.astype('float32')# standardize pixel values across channels (global)mean, std = face_pixels.mean(), face_pixels.std()face_pixels = (face_pixels - mean) / std...# transform face into one samplesamples = expand_dims(face_pixels, axis=0) ...# make prediction to get embeddingyhat = model.predict(samples)# get embeddingembedding = yhat<0> # get the face embedding for one facedef get_embedding(model, face_pixels):# scale px valuesface_pixels = face_pixels.astype('float32')# standardize px values across channels (global)mean, std = face_pixels.mean(), face_pixels.std()face_pixels = (face_pixels - mean) / std# transform face into one samplesamples = expand_dims(face_pixels, axis=0)# make prediction khổng lồ get embeddingyhat = model.predict(samples)return yhat<0> # USEAGE:# python predict_face_embeddings.py --face_dataset 5-celebrity-faces-dataset.npz --facenet_model facenet_keras.h5 --face_embedding 5-celebrity-faces-embeddings.npz# calculate a face embedding for each face in the dataset using facenetfrom numpy import loadfrom numpy import expand_dimsfrom numpy import asarrayfrom numpy import savez_compressedfrom tensorflow.keras.models import load_modelimport argparseimport tensorflow as tftf.get_logger().set $ python predict_face_embeddings.py --face_dataset 5-celebrity-faces-dataset.npz --facenet_model facenet_keras.h5 --face_embedding 5-celebrity-faces-embeddings.npz
Proto()config_tf.gpu_options.allow_growth = Truesession = tf.compat.v1.Session(config=config_tf)# extract a single face from a given photographdef extract_face(filename, required_size=(160, 160)):# load image from fileimage = Image.open(filename)# convert khổng lồ RGB, if neededimage = image.convert('RGB')# convert khổng lồ arraypixels = asarray(image)# create the detector, using mặc định weightsdetector = MTCNN()# detect faces in the imageresults = detector.detect_faces(pixels)# extract the bounding box from the first facex1, y1, width, height = results<0><'box'># bug fixx1, y1 = abs(x1), abs(y1)x2, y2 = x1 + width, y1 + height# extract the faceface = pixels
X.extend(faces)y.extend(labels)return asarray(X), asarray(y)def main():ap = argparse.Argument
Parser()ap.add_argument('-td', '--train_data', required=True)ap.add_argument('-vd', '--val_data', required=True)ap.add_argument('-sd', '--save_data', required=True)args = vars(ap.parse_args())# load train datasettrain
X, trainy = load_dataset(args<'train_data'>)print(train
X.shape, trainy.shape)# load demo datasettest
X, testy = load_dataset(args<'val_data'>)# save arrays to lớn one tệp tin in compressed formatsavez_compressed(args<'save_data'>, train
X, trainy, test
X, testy)if __name__ == '__main__':main()
Sẽ mất một chút thời gian để chấm dứt chương trình. Tất cả các khuôn mặt ở cả 2 tập train với test được lưu vào một trong những tệp mảng Num
Py nén mang tên là 5-Celeb-face-dataset.npz có dung lượng khoảng 7.5MB với được lưu trữ trong thư mục thao tác làm việc hiện tại của chương trình.
5.3 tạo ra Face Embedding vectors
Net để tạo nên các Face Embdding vectors đó.
X, trainy, test
X, testy = data<'arr_0'>, data<'arr_1'>, data<'arr_2'>, data<'arr_3'>print('Loaded: ', train
X.shape, trainy.shape, test
X.shape, testy.shape)
Level('ERROR')config_tf = tf.compat.v1.Config
Proto()config_tf.gpu_options.allow_growth = Truesession = tf.compat.v1.Session(config=config_tf)# get the face embedding for one facedef get_embedding(model, face_pixels):# scale pixel valuesface_pixels = face_pixels.astype('float32')# standardize pixel values across channels (global)mean, std = face_pixels.mean(), face_pixels.std()face_pixels = (face_pixels - mean) / std# transform face into one samplesamples = expand_dims(face_pixels, axis=0)# make prediction to get embeddingyhat = model.predict(samples)return yhat<0>def main():# load the face datasetdata = load(args<'face_dataset'>)train
X, trainy, test
X, testy = data<'arr_0'>, data<'arr_1'>, data<'arr_2'>, data<'arr_3'>print('Loaded: ', train
X.shape, trainy.shape, test
X.shape, testy.shape)# load the facenet modelmodel = load_model(args<'facenet_model'>)print('Loaded Model')# convert each face in the train set to lớn an embeddingnew
Train
X = list()for face_pixels in train
X:embedding = get_embedding(model, face_pixels)new
Train
X.append(embedding)new
Train
X = asarray(new
Train
X)print(new
Train
X.shape)# convert each face in the demo set to an embeddingnew
Test
X = list()for face_pixels in test
X:embedding = get_embedding(model, face_pixels)new
Test
X.append(embedding)new
Test
X = asarray(new
Test
X)print(new
Test
X.shape)# save arrays to lớn one tệp tin in compressed formatsavez_compressed(args<'face_embedding'>, new
Train
X, trainy, new
Test
X, testy)if __name__ == '__main__':ap = argparse.Argument
Parser()ap.add_argument('-fd', '--face_dataset', required=True)ap.add_argument('-fnm', '--facenet_model', required=True)ap.add_argument('-fe', '--face_embedding', required=True)args = vars(ap.parse_args())main()
Kết quả, toàn bộ ảnh khuôn mặt sẽ được chuyển đổi thành những Face Embedding vectors 128 chiều. Toàn bộ được gìn giữ thành file 5-celebrity-faces-embeddings.npz trong cùng thư mục có tác dụng việc.
5.4 thực hiện Face Classification
Trong phần này, bọn họ sẽ phát triển một quy mô để phân loại các Face Embedding vectors thành 5 nhãn là tên của các người nổi tiếng trong bộ tài liệu 5 Celebrity Faces Dataset. Đầu tiên, phát âm vào Face Embedding vectors tại vị trí trước:
...# load datasetdata = load('5-celebrity-faces-embeddings.npz')train
X, trainy, test
X, testy = data<'arr_0'>, data<'arr_1'>, data<'arr_2'>, data<'arr_3'>print('Dataset: train=%d, test=%d' % (train
X.shape<0>, test
X.shape<0>))
...# normalize input đầu vào vectorsin_encoder = Normalizer(norm='l2')train
X = in_encoder.transform(train
X)test
X = in_encoder.transform(test
X)..# label encode targetsout_encoder = Label
Encoder()out_encoder.fit(trainy)trainy = out_encoder.transform(trainy)testy = out_encoder.transform(testy)
Tiếp theo, họ sẽ chế tạo và đào tạo một SVM model. Thuật toán này vẫn được chứng mình tính công dụng trong vấn đề phân loại những Face Embedding vectors.
...# fit modelmodel = SVC(kernel='linear')model.fit(train
X, trainy)...# predictyhat_train = model.predict(train
X)yhat_test = model.predict(test
X)# scorescore_train = accuracy_score(trainy, yhat_train)score_test = accuracy_score(testy, yhat_test)# summarizeprint('Accuracy: train=%.3f, test=%.3f' % (score_train*100, score_test*100))
...# test model on a random example from the thử nghiệm datasetselection = choice(X.shape<0>)>)random_face_pixels = test # USEAGE:# python random_face_identity_classification.py --face_dataset 5-celebrity-faces-dataset.npz --face_embedding 5-celebrity-faces-dataset.npz# develop a classifier for the 5 Celebrity Faces Datasetfrom random import choicefrom numpy import loadfrom numpy import expand_dimsfrom sklearn.preprocessing import Label Dataset: train=93, test=25Accuracy: train=100.000, test=100.000Predicted: jerry_seinfeld (88.476)Expected: jerry_seinfeld 6. Kết luận Trong bài này, chúng ta đã khám phá cách phát triển khối hệ thống nhận diện khuôn phương diện bằng quy mô Face Toàn cỗ source code của bài bác này, các bạn có thể tham khảo trên đây Trong bài tiếp theo, chúng ta sẽ thuộc nhau tìm hiểu về mô hình Siamese. Mời chúng ta đón đọc. Như đang giới thiệu, phần đầu tiên này mình xin nói về hệ thống AI cho khối hệ thống nhé.Trong việc nhận diện khuôn phương diện này, có vài yêu cầu như sau: Vì thế, câu hỏi này mình sẽ chỉ dẫn hướng giải quyết là sử dụng quy mô object detection pretrain cho việc nhận diện khuôn mặt. Sau đó, ta đang trích xuất đặc trưng khuôn mặt bạn đó ra bởi một mạng tích chập pretrain nốt. Nói một cách dễ dàng nắm bắt là con bạn ta đang chỉ quan sát mặt fan đó, rồi search những điểm lưu ý như mũi cao, nốt ruồi đâu đó, ... để riêng biệt nhưng chỉ không giống là máy vi tính xử lý trên giá chỉ trị px ảnh. Sau đó ta sẽ sử dụng các cây search kiếm hoặc thiết bị thị kiếm tìm kiếm. Với mỗi cá nhân mới ta sẽ chuyển vào vật dụng thị đặc trưng của fan đó nhằm tìm tìm sau này. Ở đây, bản thân xin lý giải qua về một vài lý thuyết AI nhưng mình sử dụng. Nếu như khách hàng chỉ quan tâm đến phần code xin hãy vào phần code ngay. Lưu giữ ý, bỏ qua phần này không ảnh hưởng đến việc code. Ở đây, mình áp dụng MTCNN. Bản thân biết là các bạn sẽ kiểu: Ewww insert the meme here. Sao không xài Face MTCNN bao hàm 3 mạng:
X_faces
X
Encoderfrom sklearn.preprocessing import Normalizerfrom sklearn.svm import SVCfrom matplotlib import pyplotimport argparsedef main(): ap = argparse.Argument
Parser() ap.add_argument('-fd', '--face_dataset', required=True) ap.add_argument('-fe', '--face_embedding', required=True) args = vars(ap.parse_args()) # load faces data = load(args<'face_dataset'>) test
X_faces = data<'arr_2'> # load face embeddings data = load(args<'face_embedding'>) train
X, trainy, test
X, testy = data<'arr_0'>, data<'arr_1'>, data<'arr_2'>, data<'arr_3'>print('Dataset: train=%d, test=%d' % (train
X.shape<0>, test
X.shape<0>)) # normalize input đầu vào vectors in_encoder = Normalizer(norm='l2') train
X = in_encoder.transform(train
X) test
X = in_encoder.transform(test
X) # label encode targets out_encoder = Label
Encoder() out_encoder.fit(trainy) trainy = out_encoder.transform(trainy) testy = out_encoder.transform(testy) # fit model model = SVC(kernel='linear', probability=True) model.fit(train
X, trainy) # predict yhat_train = model.predict(train
X) yhat_test = model.predict(test
X) # score score_train = accuracy_score(trainy, yhat_train) score_test = accuracy_score(testy, yhat_test) # summarize print('Accuracy: train=%.3f, test=%.3f' % (score_train*100, score_test*100)) # test mã sản phẩm on a random example from the thử nghiệm dataset selection = choice(X.shape<0>)>) random_face_pixels = test
X_faces
X
Net và bộ phân loại SVM. Ráng thể:
Net.Cách sẵn sàng dữ liệu để đào tạo và giảng dạy hệ thống.Cách huấn luyện mô hình và sử dụng quy mô đã huấn luyện và đào tạo để chế tạo dự đoán.
Net hay Center
Net-Resnet 50 gì đấy cho xịn. Lí do là do khi mình tra xem có cái thư viện làm sao pretrain để cách tân và phát triển nhanh khối hệ thống thì repo MTCNN được viết bằng torch đập ngay vào mặt cùng tiện ở trong phần ngươi ta còn khiến cho pip install đến nó rồi. Center
Net mà bỏ vô docker thì lằng nhằng, Face
Net thì lại dùng MXNet.Paper gốc: https://arxiv.org/pdf/1604.02878v1.pdf.
R-Net
O-Net
Đầu vào hình hình ảnh được resize thành nhiều size tạo thành một Image Pyramid. Kế tiếp pyramid sẽ tiến hành đưa vào P-Net:
Các mạng R-Net với O-Net có kết cấu tương từ nhau chỉ không giống nhau về độ sâu với đầu ra. Với đầu vào R-Net là những bounding box từ P-Net và nguồn vào O-Net là các bounding box trường đoản cú R-Net. Nhiệm vụ của chúng là thanh lọc ra những bounding boxes chính xác hơn nhờ vào việc tặn độ sâu của tế bào hình.



Bạn có thể tự git clone repo này để sử dụng hoặc áp dụng pip. Nếu không có ý định chỉnh sửa behaviour của các phần bên trong repo thì cần sử dụng pip cho tiện nghi khi config mặt đường dẫn, ...Đầu tiên, tạo thư mục backend trong folder project. Và hãy tạo các file sau đây:
face_detector.pyface_searcher.pyPhần trích xuất đặc trưng
Ta sẽ tạo nên một class đảm nhiệm cho việc định vị khuôn mặt và trích xuất đặc trưng sang một mạng tích chập trong file face_detector.py
from facenet_pytorch import MTCNN, Inception
Resnet
V1import torchimport PILfrom PIL import Imageimport cv2import numpy as npimport osimport sysimport timeclass Face
Detector(object): def __init__(self, image_size=160, keep_all=False): """ mtcnn: face detector extractor: face feature extractor Args: image_size: face image kích thước keep_all: detect all faces or single face """ self.keep_all = keep_all # self.device = torch.device( # "cuda" if torch.cuda.is_available() else "cpu") self.device = "cpu" print("Using ", self.device) t = time.time() self.mtcnn = MTCNN( image_size=image_size, min_face_size=20, thresholds=<0.6, 0.7, 0.7>, factor=0.709, post_process=True, keep_all=False, device=self.device ) self.extractor = Inception
Resnet
V1( pretrained="vggface2").eval().to(self.device) print("Fininsh load mã sản phẩm in sec".format(time.time()-t))Giải say đắm về một vài ba param:
Inception
Resnet
V1:pretrain: chọn quy mô pretrain để sử dụngclassify: trường hợp ta thực hiện True thì mạng sẽ đi qua cả lớp Logits và là vấn đề phân loại. Ở phía trên ta sẽ set False để lấy đặc trưng ảnh.
Xem thêm: Hướng Dẫn Sử Dụng Geometers Sketchpad 5.0 (Tiếng Việt), Tải Phần Mềm Vẽ Hình Hình Học Động Gsp 5
Giờ ta sẽ liên tục code dấn diện khuôn mặt:
def detect(self, image, save_path=None): # boxes, _ = self.mtcnn.detect(image) faces = self.mtcnn(image, save_path=save_path) return faces
Hàm trên trả về ảnh ở dạng torch tensor
def extract_feature(self, tensor): if not self.keep_all: tensor = tensor.unsqueeze(0) embeddings = self.extractor(tensor.to(self.device)) embeddings = embeddings.detach().cpu().numpy() return embeddings if self.keep_all else np.squeeze(embeddings)Hàm trên vẫn trả về vector đặc trưng có shape (512, ) trong vấn đề của ta. Tiếp theo sau ta sẽ viết những hàm để đưa vector từ ảnh trực tiếp và từ một folder (trường thích hợp khởi đụng lợi vps ta cần đưa hết các ảnh đã có lại vào hệ thống).
def extract_face(self, image, save_path=None): try: faces = self.detect(image, save_path) embeddings = self.extract_feature(faces) return embeddings except Exception as err: # TODO: Logging here print(err) return Nonedef extract_face_from_folder(self, folder, save_prefix=None): # Use for single face per image. Modify save_path for multi face if not self.keep_all: all_embeddings = <> for image_name in sorted(os.listdir(folder)): image_path = os.path.join(folder, image_name) print(image_path) image = pil_loader(image_path) save_path = os.path.join( save_prefix, image_name) if save_prefix is not None else None all_embeddings.append(self.extract_face(image, save_path)) return np.array(all_embeddings)
Phần gửi vào vật dụng thị tìm kiếm kiếm
Phần này mình thực hiện Hnswlib vì chưng 2 lí vày sau đây:Thư viện trên mang đến phép add thêm các giá trị mới sau khi xây dựng đồ gia dụng thị. Các thư viện như Annoy không chất nhận được làm như vậy.Theo benchmark, Hnswlib tốt hơn nhiều thư viện khác ở cả vận tốc lẫn độ đúng đắn Recall
Ta đã viết một class phụ trách việc đào bới tìm kiếm kiếm trong face_searcher.py:
class Face
Searcher(object): def __init__(self, dim=512, space="l2", threshold=0.5): """ Args: dim: face embedding feature length space: distance algorithm (L2, Inner product, cosine) threshold: similarity threshold """ self.p = hnswlib.Index(space=space, dim=dim) self.p.init_index(max_elements=1000, ef_construction=200, M=48) self.p.set_ef(20) self.k = 1 self.threshold = threshold def add_faces(self, data, index): try: if index.shape<0> != data.shape<0>: # TODO: Logging here print("Try khổng lồ assign index with length to lớn data with length ".format( index.shape<0>, data.shape<0>)) else: self.p.add_items(data, index) except Exception as err: # TODO: Logging here print(err) def query_faces(self, data): try: index, distance = self.p.knn_query(data, k=self.k) # Filter result index = np.squeeze(index) distance = np.squeeze(distance) print("Index: ", index, "
Distance: ", distance) return index if distance các tham số của hnswlib.Index bao gồm:
Cách thông số như ef, M, ... Hãy xem sống đây