import cv2 import os import numpy as np from sklearn import svm import joblib def read_images(folder): images = [] labels = [] for filename in os.listdir(folder): label = filename.split('.')[0] img = cv2.imread(os.path.join(folder,filename)) if img is not None: images.append(img) labels.append(label) return images, labels # 提取特征向量 def extract_features(images): features = [] for img in images: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) hist = cv2.calcHist([gray],[0],None,[256],[0,256]) features.append(hist.flatten()) return features # 读取图像和标签 images, labels = read_images('C:/Users/Administrator/Desktop/111') # 提取特征向量 features = extract_features(images) print(features) # 训练模型 clf = svm.SVC() clf.fit(features, labels) # 保存模型到文件 joblib.dump(clf, 'model.pkl') clf = joblib.load('E:/xiangmu/measure/model.pkl') print(clf) # 预测新图像 img = cv2.imread('C:/Users/Administrator/Downloads/092b08c53b49d92254db7874c0a7b073.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) hist = cv2.calcHist([gray],[0],None,[256],[0,256]) features = np.array(hist.flatten()).reshape(1, -1) print(clf.predict(features)) label = clf.predict(features)[0] print('识别结果:', label) 帮我把这写代码,打印识别率
时间: 2024-03-27 17:37:07 浏览: 110
这段代码中没有计算识别率的部分,需要添加一些代码来实现。以下是修改过的代码:
```python
import cv2
import os
import numpy as np
from sklearn import svm
from sklearn.metrics import accuracy_score
import joblib
def read_images(folder):
images = []
labels = []
for filename in os.listdir(folder):
label = filename.split('.')[0]
img = cv2.imread(os.path.join(folder,filename))
if img is not None:
images.append(img)
labels.append(label)
return images, labels
def extract_features(images):
features = []
for img in images:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
features.append(hist.flatten())
return features
images, labels = read_images('C:/Users/Administrator/Desktop/111')
features = extract_features(images)
clf = svm.SVC()
clf.fit(features, labels)
joblib.dump(clf, 'model.pkl')
clf = joblib.load('model.pkl')
test_images, test_labels = read_images('C:/Users/Administrator/Desktop/222')
test_features = extract_features(test_images)
pred_labels = clf.predict(test_features)
accuracy = accuracy_score(test_labels, pred_labels)
print('识别率:', accuracy)
```
这段代码会读取一个文件夹中的图片作为训练数据,另一个文件夹中的图片作为测试数据,然后计算识别率并打印出来。注意修改文件夹的路径和文件名的格式。
阅读全文