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) # 训练模型 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/Desktop/dc9cd0a3a572635fb27973627f514dfb.jpeg') 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(hist) label = clf.predict(features)[0] print('识别结果:', label) 帮我优化代码,可以打印概率
时间: 2024-03-27 16:39:47 浏览: 129
vim-autoimport:Vim插件,用于在不使用LSP的情况下添加导入语句(适用于python等)
好的,我们可以使用`predict_proba`方法来获取预测结果的概率。以下是优化后的代码示例:
```python
import cv2
import os
import numpy as np
from sklearn import svm
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from skimage.io import imread
from skimage.transform import resize
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)
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3)
# 创建SVM分类器
clf = svm.SVC(kernel='linear', probability=True)
# 训练分类器
clf.fit(X_train, y_train)
# 保存模型到文件
joblib.dump(clf, 'model.pkl')
# 加载模型
clf = joblib.load('model.pkl')
# 预测新图像
img = cv2.imread('C:/Users/Administrator/Desktop/dc9cd0a3a572635fb27973627f514dfb.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
features = np.array(hist.flatten()).reshape(1, -1)
# 预测分类和概率
label = clf.predict(features)[0]
prob = clf.predict_proba(features)[0]
print('识别结果:', label)
print('概率分布:', prob)
```
在这个示例中,我们首先将数据集分为训练集和测试集,然后创建SVM分类器并训练它。我们设置`probability=True`来启用预测结果的概率估计。在预测新图像时,我们使用`predict`方法获取预测分类,使用`predict_proba`方法获取预测结果的概率分布。最后,我们打印预测结果和概率分布。
阅读全文