import cv2 from skimage.feature import hog from sklearn.neighbors import KNeighborsClassifier import joblib import numpy as np # 加载已经训练好的分类器 model_location = "C:/Users/27745/数字图像处理/knn.pkl" knn = joblib.load(model_location) def predict_digit(image): #获取一幅手写数字图像的输入,返回预测结果 # 将图像转换为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 应用高斯模糊和大津二值化来预处理图像 blur = cv2.GaussianBlur(gray, (5, 5), 0) _, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) # Find the contours and sort them largest-to-smallest contours, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0]) # 提取每个字符的 ROI 并使用 HOG 特征提取方法进行特征提取 features = [] for cnt in contours: (x, y, w, h) = cv2.boundingRect(cnt) # 添加一定的边框,避免过小的ROI被压缩过多而失去特征 border_size = 20 roi = thresh[max(y - border_size, 0):min(y + h + border_size, image.shape[0]), max(x - border_size, 0):min(x + w + border_size, image.shape[1])] # 将ROI调整为28x28大小,并根据特征提取器生成的HOG描述符提取特征 resized_roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA) fd = hog(resized_roi, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2), block_norm='L2-Hys') features.append(fd.reshape(-1, 1)) # 将提取的特征向量输入KNN模型进行预测 results = knn.predict(np.hstack(features)) # 返回数字串预测结果 return ''.join(str(result) for result in results) # 载入测试图片并进行预测 image_name = "C:/Users/27745/Desktop/test1.png" image = cv2.imread(image_name) # 将目标图像统一调整为相同的大小 image = cv2.resize(image, (300, 300)) # 利用封装的函数进行预测 result = predict_digit(image) print("The number is:", result)以上代码出现了X has 216 features, but KNeighborsClassifier is expecting 784 features as input.的问题,请帮我更正
时间: 2023-11-22 21:53:59 浏览: 42
这个错误是因为在特征提取时,使用的HOG特征提取方法生成的特征向量维度不正确。
在代码中,我们将每个字符的ROI调整为28x28大小,并使用HOG特征提取方法生成的特征向量进行特征提取,但是在生成特征向量时,我们使用了`reshape(-1,1)`将特征向量转换为列向量,这导致特征向量的维度不正确。
要解决这个问题,我们需要使用`reshape(1,-1)`将特征向量转换为行向量,这样就可以将特征向量的维度调整为784,与KNN模型期望的输入维度相匹配。
修改代码如下:
```python
# 将ROI调整为28x28大小,并根据特征提取器生成的HOG描述符提取特征
resized_roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
fd = hog(resized_roi, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(2, 2), block_norm='L2-Hys')
features.append(fd.reshape(1, -1)) # 将特征向量转换为行向量
```
这样就可以解决这个问题了。
相关问题
from skimage.feature import hog
As an AI language model, I cannot import any libraries or packages. However, I can tell you that 'hog' stands for Histogram of Oriented Gradients, which is a feature descriptor used in computer vision and image processing. It is used to extract features from an image by calculating the gradients of the image and creating a histogram of gradient orientations. The resulting feature vector can then be used in machine learning algorithms for tasks such as object detection and recognition.
import os import numpy as np import cv2 import matplotlib.pyplot as plt from sklearn.svm import SVC from tqdm import tqdm from sklearn.preprocessing import StandardScaler from PIL import Image from skimage import feature, color, data from sklearn.preprocessing import LabelEncoder import random as rn from random import shuffle from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold, StratifiedKFold from sklearn.metrics import confusion_matrix, accuracy_score, classification_report from sklearn import metrics from sklearn.svm import LinearSVC
这段代码是用 Python 语言编写的,它使用了一些常见的机器学习库和图像处理库,如sklearn、numpy、cv2等。它的主要功能是实现对图像数据的特征提取和分类,具体来说,是通过提取图像的HOG特征并使用SVM分类器对图像进行分类。其中,使用了一些常见的机器学习算法和技术,如交叉验证、标签编码、混淆矩阵、分类报告等。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)