跳转到主要内容

曲线的转弯半径和曲率

import cv2
import numpy as np
import os
class FaceRecognizer:
   def __init__(self):
       self.recognizer = cv2.face.LBPHFaceRecognizer_create()
       self.labels = []
       self.faces = []
   def train(self, data_path):
       # 遍历数据集文件夹
       for person_name in os.listdir(data_path):
           person_path = os.path.join(data_path, person_name)
           if not os.path.isdir(person_path):
               continue
           # 为每个人分配标签(如"张三"->0)
           label = len(self.labels)
           self.labels.append(person_name)
           # 加载该人所有照片
           for img_name in os.listdir(person_path):
               img_path = os.path.join(person_path, img_name)
               img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
               if img is not None:
                   # 检测人脸(复用之前的检测器)
                   faces = face_cascade.detectMultiScale(img, 1.1, 4)
                   if len(faces) == 1:
                       x, y, w, h = faces[0]
                       face_roi = img[y:y+h, x:x+w]
                       self.faces.append(face_roi)
       # 训练模型
       self.recognizer.train(self.faces, np.array(range(len(self.labels))))
   def predict(self, img_path):
       img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)
       faces = face_cascade.detectMultiScale(img, 1.1, 4)
       if len(faces) != 1:
           return "未检测到人脸或检测到多张人脸"
       x, y, w, h = faces[0]
       face_roi = img[y:y+h, x:x+w]
       # 预测
       label, confidence = self.recognizer.predict(face_roi)
       return f"{self.labels[label]} (置信度: {confidence:.2f})"
# 使用示例
recognizer = FaceRecognizer()
recognizer.train('dataset')  # dataset文件夹下包含按人名分类的子文件夹
print(recognizer.predict('test_face.jpg'))

分类