Python是一種強(qiáng)大的編程語(yǔ)言,被廣泛使用在機(jī)器人領(lǐng)域中??梢允褂肞ython編寫(xiě)各種機(jī)器人程序,例如,可以編寫(xiě)一個(gè)能夠識(shí)別人臉的機(jī)器人程序。下面是實(shí)現(xiàn)這種程序的一些Python代碼和技巧。
import face_recognition import cv2 # 加載待檢測(cè)的人臉 known_face_encodings = [] known_face_names = [] image = face_recognition.load_image_file("person.jpg") face_encoding = face_recognition.face_encodings(image)[0] known_face_encodings.append(face_encoding) known_face_names.append("Person") # 打開(kāi)視頻流并開(kāi)始捕捉幀 video_capture = cv2.VideoCapture(0) while True: # 讀取單幀圖像并找到所有人臉 ret, frame = video_capture.read() rgb_frame = frame[:, :, ::-1] face_locations = face_recognition.face_locations(rgb_frame) face_encodings = face_recognition.face_encodings(rgb_frame, face_locations) # 在幀上循環(huán)遍歷每個(gè)人臉并檢查它是否與已知人臉匹配 for face_encoding in face_encodings: matches = face_recognition.compare_faces(known_face_encodings, face_encoding) name = "Unknown" # 如果匹配,就指定人名 if True in matches: first_match_index = matches.index(True) name = known_face_names[first_match_index] # 繪制邊框 top, right, bottom, left = face_location cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) cv2.putText(frame, name, (left +6, bottom -6), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1) # 顯示結(jié)果 cv2.imshow('Video', frame) # 按q鍵退出 if cv2.waitKey(1) & 0xFF == ord('q'): break #釋放視頻流 video_capture.release() cv2.destroyAllWindows()
以上代碼使用face_recognition和opencv-python等Python庫(kù)來(lái)識(shí)別人臉并在視頻流上進(jìn)行標(biāo)記。這個(gè)機(jī)器人程序可以檢測(cè)已知人臉并將其標(biāo)記,同時(shí)也會(huì)標(biāo)記未知人臉。
上一篇encode json
下一篇python 考試填空題