人工智慧之Python人臉識別技術--face_recognition模組
阿新 • • 發佈:2019-01-06
Create arrays of known face encodings and their names
# 臉部特徵資料的集合
known_face_encodings = [
chenduling_face_encoding,
sunyizheng_face_encoding,
zhangzetian_face_encoding
]
# 人物名稱的集合
known_face_names = [
"michong",
"sunyizheng",
"chenduling"
]
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
# 讀取攝像頭畫面
ret, frame = video_capture.read()
# 改變攝像頭影象的大小,影象小,所做的計算就少
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# opencv的影象是BGR格式的,而我們需要是的RGB格式的,因此需要進行一個轉換。
rgb_small_frame = small_frame[:, :, ::-1]
# Only process every other frame of video to save time
if process_this_frame:
# 根據encoding來判斷是不是同一個人,是就輸出true,不是為flase
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# 預設為unknown
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# if match[0]:
# name = "michong"
# If a match was found in known_face_encodings, just use the first one.
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
face_names.append(name)
process_this_frame = not process_this_frame
# 將捕捉到的人臉顯示出來
for (top, right, bottom, left), name in zip(face_locations, face_names):
# Scale back up face locations since the frame we detected in was scaled to 1/4 size
top *= 4
right *= 4
bottom *= 4
left *= 4
# 矩形框
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
#加上標籤
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
# Display
cv2.imshow('monitor', frame)
# 按Q退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()