1. face_generate.py
Before playing with the code, let us see the libraries that need to be installed on your Ubuntu machine.
在玩代碼之前,讓我們看一下需要在Ubuntu計算機上安裝的庫。
Requirements
要求
python 3.7
python 3.7
OpenCV 4.1.0
OpenCV 4.1.0
NumPy
NumPy
face-recognition
人臉識別
sudo apt-get install gnome-screensaver
sudo apt-get安裝gnome-screensaver
sudo apt-get install xdotool
sudo apt-get安裝xdotool
Below are the three python files that are just enough to achieve this!!!
以下是三個足以滿足此要求的python文件!!!
1. face_generate.py
1. face_generate.py
2. face_train.py
2. face_train.py
3. face_unlock.py
3. face_unlock.py
Demo video示范影片1. face_generate.py (1. face_generate.py)
Generate face產生臉As a first step, we have to generate training images to train the models. I have created a python file to generate our face image. When you execute this file, it will ask your name in the command line then the system will create a folder with the given name.
第一步,我們必須生成訓練圖像來訓練模型。 我創建了一個python文件來生成我們的面部圖像。 當您執行此文件時,它將在命令行中詢問您的名稱,然后系統將使用給定名稱創建一個文件夾。
number=0;frame_count=0
detector = dlib.get_frontal_face_detector()
print("enter the person name")
name = input()
folder_name="dataset/"+nameif os.path.exists(folder_name):
print ("Folder exist")
else:
os.mkdir(folder_name)
After that, we need to use the OpenCV library to read our face via webcam and store it in the respective folder, before saving to that folder we should resize our image.
之后,我們需要使用OpenCV庫通過網絡攝像頭讀取面部并將其存儲在相應的文件夾中,然后再保存到該文件夾??中,我們應該調整圖像大小。
image = imutils.resize(image, width=500)gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# detect faces in the grayscale image
rects = detector(gray, 1)
# loop over the face detections
for (i, rect) in enumerate(rects):
# determine the facial landmarks for the face region, then
(x, y, w, h) = face_utils.rect_to_bb(rect)
#print rect.dtype
cro=image[y: y + h, x: x + w]out_image = cv2.resize(cro,(108,108))
fram= os.path.join(folder_name+"/",str(number)+ "." + "jpg")
number+=1
cv2.imwrite(fram,out_image)
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
frame_count+=1
This will take 50 face images to train the model, you can change the number of image counts as per your requirements.
這將需要50張面部圖像來訓練模型,您可以根據需要更改圖像計數的數量。
2. face_train.py (2. face_train.py)
This file will read every face image that is generated by face_genrate.py file. Upon completion, we need to pass them into the load_image_file method to get the face location of the images.
該文件將讀取face_genrate.py文件生成的每個面部圖像。 完成后,我們需要將它們傳遞到load_image_file方法中,以獲取圖像的面部位置。
face = face_recognition.load_image_file("dataset/" + person + "/" + person_img)# location is in css order - top, right, bottom, left
height, width, _ = face.shape
face_location = (0, width, height, 0)
Before training our face model, we should encode our images, so I used the face_encoding method. Also, we should store our names in one array to train with the k-nearest neighbor algorithm.
在訓練我們的面部模型之前,我們應該對圖像進行編碼,因此我使用了face_encoding方法。 同樣,我們應該將我們的名稱存儲在一個數組中,以使用k最近鄰算法進行訓練。
face_enc = face_recognition.face_encodings(face, known_face_locations=[face_location])face_enc = np.array(face_enc)face_enc = face_enc.flatten()
# Add face encoding for current image with corresponding label (name) to the training data
encodings.append(face_enc)
names.append(person)
Sci-kit learn library is popular for the machine learning algorithm. We have used the KNeighborsClassifier algorithm which is provided by sci-kit learn library.
Sci-kit學習庫在機器學習算法中很受歡迎。 我們使用了sci-kit學習庫提供的KNeighborsClassifier算法。
knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')knn_clf.fit(encodings,names)
Finally, We should save our model file using the pickle library.
最后,我們應該使用pickle庫保存模型文件。
# Save the trained KNN classifierif model_save_path is not None:
with open(model_save_path, 'wb') as f:
pickle.dump(knn_clf, f)return knn_clf
3. face_unlock.py (3. face_unlock.py)
This python file will lock & unlock the ubuntu system based on the trained image. Let’s first capture our face via webcam using the OpenCV library. After using the read method, we can read face images as frames.
這個python文件將根據訓練后的圖像鎖定和解鎖ubuntu系統。 首先,我們使用OpenCV庫通過網絡攝像頭捕捉面部表情。 使用read方法后,我們可以將面部圖像讀取為幀。
camera = cv2.VideoCapture(0)(grabbed, image1) = camera.read()
We must detect the face location from the image, hence I’ve used the face_location method. After getting the face location we should pass into the face_encodings method to encode face image to process the next step.
我們必須從圖像中檢測面部位置,因此我使用了face_location方法。 獲得面部位置后,我們應該傳遞給face_encodings方法對面部圖像進行編碼,以進行下一步。
image = image1[:, :, ::-1]X_face_locations = face_recognition.face_locations(image)# If no faces are found in the image, return an empty result.if len(X_face_locations) != 0:
# Find encodings for faces in the test iamge
faces_encodings = face_recognition.face_encodings(image, known_face_locations=X_face_locations)
Before predicting, knn model should be used to find the best matches for the given face. Below is the prediction method to verify the face. It will return the name and top, left, right & bottom variable.
在進行預測之前,應使用knn模型為給定的面Kong找到最佳匹配。 以下是驗證人臉的預測方法。 它將返回名稱和頂部,左側,右側和底部變量。
closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)are_matches = [closest_distances[0][i][0] <= 0.4 for i in range(len(X_face_locations))]predictions = [(pred, loc) if rec else ("unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]Use gnome shell command to Lock and Unlock the ubuntu system.
使用gnome shell命令鎖定和解鎖ubuntu系統。
if name not in "unknown":os.popen('gnome-screensaver-command -d && xdotool key Return')
else
os.popen('gnome-screensaver-command -a')
If the user’s face is unknown or not detected, the system will remain in a locked state.
如果未知或未檢測到用戶的臉部,則系統將保持鎖定狀態。
結論 (Conclusion)
That’s it, we have successfully tested the auto-lock & unlock technique of ubuntu using a human face with the help of three python files listed above. You can get the complete source code here
就是這樣,我們已經在上面列出的三個python文件的幫助下使用人臉成功地測試了ubuntu的自動鎖定和解鎖技術。 您可以在此處獲取完整的源代碼
if you need any help or assistance please connect with me LinkedIn and Twitter.
如果您需要任何幫助或幫助,請與我聯系LinkedIn和Twitter 。
翻譯自: https://towardsdatascience.com/automatically-locking-unlocking-ubuntu-with-computer-vision-using-a-human-face-db35cbe312f7
總結
以上是生活随笔為你收集整理的1. face_generate.py的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 传奇城镇建设模拟游戏重制版《法老王:新纪
- 下一篇: 三星新款旗舰笔记本 Galaxy Boo