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 12:37:15 浏览: 58
可以添加以下代码来计算并打印出识别率:
```python
# 读取测试图像和标签
test_images, test_labels = read_images('C:/Users/Administrator/Downloads/test')
# 提取测试图像的特征向量
test_features = extract_features(test_images)
# 预测测试图像的标签
pred_labels = clf.predict(test_features)
# 计算识别率
accuracy = sum(1 for i in range(len(test_labels)) if test_labels[i] == pred_labels[i]) / len(test_labels)
# 打印识别率
print('识别率:{:.2f}%'.format(accuracy * 100))
```
其中,`test` 文件夹包含了测试图像,每张图像的文件名为其真实标签,例如 `cat.jpg` 表示这张图像真实标签为 `cat`。
相关问题
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) 我想知道怎么获取返回结果的概率值
在这个例子中,你可以使用`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`变量是一个一维数组,包含了新图像属于各个类别的概率值。
import cv2 import numpy as np import os # 提取图像的HOG特征 def get_hog_features(image): hog = cv2.HOGDescriptor() hog_features = hog.compute(image) return hog_features # 加载训练数据集 train_data = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128"] train_labels = [r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128\labels.txt"] num_samples = 681 for i in range(num_samples): img = cv2.imread(str(i).zfill(3)+'.jpg') hog_features = get_hog_features(image) hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) color_hist = cv2.calcHist([hsv_image], [0, 1], None, [180, 256], [0, 180, 0, 256]) color_features = cv2.normalize(color_hist, color_hist).flatten() train_data.append(hog_features) train_labels.append(labels[i]) # 训练SVM模型 svm = cv2.ml.SVM_create() svm.setType(cv2.ml.SVM_C_SVC) svm.setKernel(cv2.ml.SVM_LINEAR) svm.train(np.array(train_data), cv2.ml.ROW_SAMPLE, np.array(train_labels)) # 对测试图像进行分类 test_image = cv2.imread('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\maskslic2_roi.png', 0) test_features = get_hog_features(test_image) result = svm.predict(test_features.reshape(1,-1)) # 显示分割结果 result_image = np.zeros(test_image.shape, np.uint8) for i in range(test_image.shape[0]): for j in range(test_image.shape[1]): if result[i,j] == 1: result_image[i,j] = 255 cv2.imshow('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\Result.png', result_image) cv2.waitKey(0) cv2.destroyAllWindows()
这段代码似乎存在一些问题。以下是一些可能需要修改的地方:
1. 在加载训练数据时,`train_data`和`train_labels`应该是列表类型,而不是字符串类型。您可以使用`os.listdir()`函数来获取文件夹中的所有图像文件名,并使用`cv2.imread()`函数读取图像文件。
2. 在获取HOG特征时,您应该使用`img`而不是`image`变量。
3. 在提取颜色直方图特征时,您应该使用`test_image`而不是`image`变量。
4. 在将特征添加到`train_data`列表中时,您应该将`hog_features`和`color_features`链接在一起。
5. 在使用`svm.predict()`函数对测试图像进行分类时,您应该使用`svm.predict(test_features)`而不是`svm.predict(test_features.reshape(1,-1))`。
6. 在显示分割结果时,您应该使用`cv2.imshow()`函数的第一个参数是窗口的名称,而不是图像文件的路径。
以下是修改后的示例代码:
```python
import cv2
import numpy as np
import os
# 提取图像的HOG特征
def get_hog_features(img):
hog = cv2.HOGDescriptor()
hog_features = hog.compute(img)
return hog_features.flatten()
# 加载训练数据集
train_folder = r"I:\18Breakageratecalculation\SVM run\detection_cut\whole\train128"
train_data = []
train_labels = []
for filename in os.listdir(train_folder):
if filename.endswith('.jpg'):
img = cv2.imread(os.path.join(train_folder, filename), 0)
hog_features = get_hog_features(img)
hsv_image = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
color_hist = cv2.calcHist([hsv_image], [0, 1], None, [180, 256], [0, 180, 0, 256])
color_features = cv2.normalize(color_hist, color_hist).flatten()
features = np.concatenate((hog_features, color_features))
train_data.append(features)
with open(os.path.join(train_folder, 'labels.txt'), 'r') as f:
label = int(f.readline().strip())
train_labels.append(label)
# 训练SVM模型
svm = cv2.ml.SVM_create()
svm.setType(cv2.ml.SVM_C_SVC)
svm.setKernel(cv2.ml.SVM_LINEAR)
svm.train(np.array(train_data), cv2.ml.ROW_SAMPLE, np.array(train_labels))
# 对测试图像进行分类
test_image = cv2.imread('I:\18Breakageratecalculation\mask-slic use\maskSLIC-master\result\split\result2\maskslic2_roi.png', 0)
test_features = get_hog_features(test_image)
hsv_test_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2HSV)
color_hist = cv2.calcHist([hsv_test_image], [0, 1], None, [180, 256], [0, 180, 0, 256])
color_features = cv2.normalize(color_hist, color_hist).flatten()
test_features = np.concatenate((test_features, color_features))
result = svm.predict(test_features)
# 显示分割结果
result_image = np.zeros(test_image.shape, np.uint8)
for i in range(test_image.shape[0]):
for j in range(test_image.shape[1]):
if result[i,j] == 1:
result_image[i,j] = 255
cv2.imshow('Result', result_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请注意,以上代码仅作为参考。您可能需要根据自己的情况进行微调。
阅读全文