「摸魚」神器來了,Python 實(shí)現(xiàn)人臉監(jiān)測制作神器

最近都在討論工作摸魚,網(wǎng)易云音樂也出了合理摸魚時(shí)間表,今天給大家推薦如何用python實(shí)現(xiàn)摸魚~碼住呦!







facial_features = ['chin','left_eyebrow','right_eyebrow','nose_bridge','nose_tip','left_eye','right_eye','top_lip','bottom_lip']video_capture = cv2.VideoCapture(0)label="flase"num=0try:os.mkdir("img/"+label)except:passwhile True:ret,frame=video_capture.read()face_locations = face_recognition.face_locations(frame)face_landmarks_list = face_recognition.face_landmarks(frame)for face_location in face_locations:top, right, bottom, left = face_locationif len(face_landmarks_list)==1:num+=1face_image = frame[top:bottom, left:right]cv2.imwrite("img/"+label+"/"+str(num)+".jpg",face_image)print("保存第"+str(num)+"張人臉")cv2.imshow("test",face_image)cv2.waitKey(1)else:print("未能檢測到人臉,或人臉數(shù)目不止一個(gè),請(qǐng)保證只有一個(gè)人臉")if num == 1000:breakcv2.destroyAllWindows()

3.2 KNN人臉分類
def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):X = []y = []for class_dir in os.listdir(train_dir):if not os.path.isdir(os.path.join(train_dir, class_dir)):continuefor img_path in image_files_in_folder(os.path.join(train_dir, class_dir)):image = face_recognition.load_image_file(img_path)face_bounding_boxes = face_recognition.face_locations(image)if len(face_bounding_boxes) != 1:if verbose:print("Image {} not suitable for training: {}".format(img_path,"Didn't find a face" if len(face_bounding_boxes) < 1 else "Found more than one face"))else:X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0])y.append(class_dir)if n_neighbors is None:n_neighbors = int(round(math.sqrt(len(X))))if verbose:print("Chose n_neighbors automatically:", n_neighbors)knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')knn_clf.fit(X, y)if model_save_path is not None:with open(model_save_path, 'wb') as f:pickle.dump(knn_clf, f)return knn_clfdef predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.5):if knn_clf is None and model_path is None:raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")if knn_clf is None:with open(model_path, 'rb') as f:knn_clf = pickle.load(f)X_img = X_img_pathX_face_locations = face_recognition.face_locations(X_img)if len(X_face_locations) == 0:return []faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]return [(pred, loc) if rec else ("unknown", loc) for pred, loc, rec inzip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]

def get_window_positon(width, height):window_x_position = (window.winfo_screenwidth() - width) // 2window_y_position = (window.winfo_screenheight() - height) // 2return window_x_position, window_y_positionpos = get_window_positon(tk_width, tk_height)window.geometry(f'+{pos[0]}+{pos[1]}')def closewindow():messagebox.showinfo(title="警告",message="請(qǐng)點(diǎn)擊確定")returndef t():try:os.remove("ok.txt")except:passwindow.destroy()window.protocol("WM_DELETE_WINDOW",closewindow)bnt=Button(window,text="確定",width=15,height=2,command=t)bnt.pack()window.mainloop()if temp>num:if os.path.exists("ok.txt"):passelse:t2 = threading.Thread(target=test2)t2.start()os.system("1.jpg")f = open("ok.txt", "w")f.close()t1 = threading.Thread(target=test1)t1.start()for name, (top, right, bottom, left) in predictions:draw.rectangle(((left, top), (right, bottom)), outline=(0, 0, 255))text_width, text_height = draw.textsize(name)draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=(0, 0, 255), outline=(0, 0, 255))draw.text((int((left + right)/2), bottom - text_height - 10), name,font=myfont, fill=(0,0,0))del drawpil_image = np.array(pil_image)temp = numelse:pil_image=img_pathdef test2():os.system('1.caj')def test1():os.system('test.exe')

完整代碼:
https://codechina.csdn.net/qq_42279468/face-monitor/-/tree/master
李秋鍵,CSDN博客專家,CSDN達(dá)人課作者。碩士在讀于中國礦業(yè)大學(xué),開發(fā)有taptap競賽獲獎(jiǎng)等。
2、為什么阿里巴巴/騰訊不去開發(fā)被卡脖子的工業(yè)軟件?
3、谷歌翻譯陷入「辱華」風(fēng)波:夾帶私貨還是訓(xùn)練語料背鍋?
4、欠債3000億,宣布破產(chǎn)!昔日民族品牌,為何總淪為反面教材?
5、華為首次自曝“天才少年”成果:入職不到一年就干成這件大事,網(wǎng)友:值200萬年薪!

評(píng)論
圖片
表情
