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') # 预测新图像 img = cv2.imread('C:/Users/Administrator/Downloads/2fa446fe46477a2850d029fedce20ae6.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] print('识别结果:', label) 我想知道怎么获取返回结果的概率值
时间: 2024-03-27 18:39:00 浏览: 73
在这个例子中,你可以使用`predict_proba`方法来获取预测结果的概率值。具体来说,可以将新图像的特征向量作为输入,使用`predict_proba`方法来获取属于各个类别的概率值。代码如下:
```
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(probability=True) # 启用概率估计功能
clf.fit(features, labels)
# 保存模型到文件
joblib.dump(clf, 'model.pkl')
# 加载模型
clf = joblib.load('model.pkl')
# 预测新图像
img = cv2.imread('C:/Users/Administrator/Downloads/2fa446fe46477a2850d029fedce20ae6.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)
# 预测结果的概率值
proba = clf.predict_proba(features)[0]
print('概率值:', proba)
# 预测结果
label = clf.predict(features)[0]
print('识别结果:', label)
```
这里需要将SVM分类器的`probability`参数设置为True来启用概率估计功能,然后使用`predict_proba`方法来获取预测结果的概率值。在这个例子中,`proba`变量是一个一维数组,包含了新图像属于各个类别的概率值。
阅读全文