修改下面代码,有几个要求:1注册人脸单独拿出来。2识别出来人脸使用红框框出并且周围放上名字,需要中文显示。
CONFIG = {
“feature_file”: “employee_features.json”,
“attendance_file”: “attendance_records.json”,
“yolo_model”: “yolov11s-face.pt”,
“recog_model”: “arcfaceresnet100-8.onnx”,
“detect_thresh”: 0.7,
“match_thresh”: 0.65,
“camera_id”: 0,
“frame_size”: (640, 480)
}
class FaceProcessor:
def init(self):
self.face_model = YOLO(CONFIG[“yolo_model”])
self.recog_model = cv2.dnn.readNetFromONNX(CONFIG[“recog_model”])
self.frame_queue = Queue(maxsize=3)
self.detect_queue = Queue(maxsize=2)
self.feature_mgr = FeatureManager()
self.attendance_log = []
threading.Thread(target=self._capture_thread, daemon=True).start()
threading.Thread(target=self._detect_thread, daemon=True).start()
def _capture_thread(self):
cap = cv2.VideoCapture(CONFIG["camera_id"])
cap.set(3, CONFIG["frame_size"][0])
cap.set(4, CONFIG["frame_size"][1])
while True:
ret, frame = cap.read()
if not ret: continue
if self.frame_queue.qsize() < 3:
self.frame_queue.put(frame)
def _detect_thread(self):
while True:
if self.frame_queue.empty():
time.sleep(0.01)
continue
frame = self.frame_queue.get()
results = self.face_model(frame, imgsz=640, conf=CONFIG["detect_thresh"])
boxes = results[0].boxes.xyxy.cpu().numpy()
self.detect_queue.put((frame, boxes))
def process_frame(self):
if self.detect_queue.empty():
return None
frame, boxes = self.detect_queue.get()
for box in boxes:
x1, y1, x2, y2 = map(int, box)
face_img = frame[y1:y2, x1:x2]
aligned_face = cv2.resize(face_img, (112, 112))
blob = cv2.dnn.blobFromImage(aligned_face, 1 / 128.0, (112, 112),
(127.5, 127.5, 127.5), swapRB=True)
self.recog_model.setInput(blob)
feature = self.recog_model.forward().flatten()
max_sim = 0
matched_id = -1
for emp_id, name, db_feat in self.feature_mgr.get_all_features():
similarity = np.dot(db_feat, feature)
if similarity > max_sim and similarity > CONFIG["match_thresh"]:
max_sim = similarity
matched_id = emp_id
# 考勤记录
if matched_id != -1:
self._record_attendance(matched_id)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(frame, f"ID:{matched_id}", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
return frame
def _record_attendance(self, user_id):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
new_record = {"user_id": user_id, "timestamp": timestamp}
with threading.Lock():
try:
with open(CONFIG["attendance_file"], "r+") as f:
records = json.load(f)
records.append(new_record)
f.seek(0)
json.dump(records, f, indent=2)
except FileNotFoundError:
with open(CONFIG["attendance_file"], "w") as f:
json.dump([new_record], f, indent=2)
if name == “main”:
processor = FaceProcessor()
fm = FeatureManager()
sample_feature = np.random.randn(512).astype(np.float32) # 示例特征
fm.add_feature(1001, "张三", sample_feature)
while True:
processed_frame = processor.process_frame()
if processed_frame is not None:
cv2.imshow("Attendance System", processed_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()