SVM分类算法实现人脸识别,python代码
时间: 2023-07-05 22:11:40 浏览: 135
SVM人脸识别的Python代码
以下是使用SVM算法实现人脸识别的Python代码:
```python
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
# 加载人脸数据集
face_data = np.load('face_data.npy')
labels = np.load('face_labels.npy')
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(face_data, labels, test_size=0.2, random_state=42)
# 训练SVM分类器
svm = SVC(kernel='linear')
svm.fit(X_train, y_train)
# 测试分类器准确率
accuracy = svm.score(X_test, y_test)
print('Accuracy:', accuracy)
# 实时人脸识别
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)
for (x, y, w, h) in faces:
face_roi = gray[y:y+h, x:x+w]
face_roi = cv2.resize(face_roi, (100, 100))
label, confidence = svm.predict(face_roi.reshape(1, -1))
if confidence < 200:
cv2.putText(frame, str(label), (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)
else:
cv2.putText(frame, 'Unknown', (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255), 2)
cv2.imshow('Face Recognition', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
这段代码中,我们首先加载了人脸数据集和对应的标签,然后使用`train_test_split`函数将其划分为训练集和测试集。接着,我们使用SVM分类器进行训练,并计算其在测试集上的准确率。最后,我们使用OpenCV库实现实时人脸识别,将摄像头捕捉到的人脸图像进行预处理(灰度化、缩放)后,使用训练好的SVM分类器进行识别。如果置信度(即预测结果与真实标签的距离)小于200,就认为识别成功,否则识别失败。
阅读全文