「摸鱼」神器来了,Python 实现人脸监测制作神器
Python客栈
共 6030字,需浏览 13分钟
·
2021-12-11 07:50
最近都在讨论工作摸鱼,网易云音乐也出了合理摸鱼时间表,今天给大家推荐如何用python实现摸鱼~码住呦!
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=0
try:
os.mkdir("img/"+label)
except:
pass
while 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_location
if len(face_landmarks_list)==1:
num+=1
face_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("未能检测到人脸,或人脸数目不止一个,请保证只有一个人脸")
if num == 1000:
break
cv2.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)):
continue
for 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_clf
def 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_path
X_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 in
zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]
def get_window_positon(width, height):
window_x_position = (window.winfo_screenwidth() - width) // 2
window_y_position = (window.winfo_screenheight() - height) // 2
return window_x_position, window_y_position
pos = get_window_positon(tk_width, tk_height)
window.geometry(f'+{pos[0]}+{pos[1]}')
def closewindow():
messagebox.showinfo(title="警告",message="请点击确定")
return
def t():
try:
os.remove("ok.txt")
except:
pass
window.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"):
pass
else:
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 draw
pil_image = np.array(pil_image)
temp = num
else:
pil_image=img_path
def test2():
os.system('1.caj')
def test1():
os.system('test.exe')
完整代码:
https://codechina.csdn.net/qq_42279468/face-monitor/-/tree/master
李秋键,CSDN博客专家,CSDN达人课作者。硕士在读于中国矿业大学,开发有taptap 竞赛获奖等。
4、欠债3000亿,宣布破产!昔日民族品牌,为何总沦为反面教材?
5、华为首次自曝“天才少年”成果:入职不到一年就干成这件大事,网友:值200万年薪!
评论