【问题标题】:vectorize a picture to pass into classifier将图片矢量化以传递给分类器
【发布时间】:2021-02-08 00:27:55
【问题描述】:

我按照本教程创建了一个简单的图像分类:

https://blog.hyperiondev.com/index.php/2019/02/18/machine-learning/

在训练之前,我们像这样对数据集中的图片进行矢量化处理:

train_data = scipy.io.loadmat('extra_32x32.mat')
# extract the images and labels from the dictionary object
X = train_data['X']
y = train_data['y']

# example: view an image (e.g. 25) and print its corresponding label
img_index = 25
plt.imshow(X[:,:,:,img_index])
plt.show()
print(y[img_index])

X = X.reshape(X.shape[0]*X.shape[1]*X.shape[2],X.shape[3]).T
y = y.reshape(y.shape[0],)
X, y = shuffle(X, y, random_state=42)

一旦我们完成训练,我想上传另一张图片(不在数据集中)并通过分类器检查它是否被预测(连同它的准确度分数)

但是我怎样才能传递图片呢?我试过这个:

jpgfile = Image.open("63.jpg") 
value = clf.predict(jpgfile)

并得到一个错误:

Found array with dim 3. Estimator expected <= 2.

那么,由于我没有单独的 x,y 值,我该如何相应地对其进行矢量化。

【问题讨论】:

    标签: python machine-learning scikit-learn computer-vision image-classification


    【解决方案1】:

    你需要在加载后重塑你的图像:

    jpgfile = Image.open("63.jpg") 
    jpgfile = jpgfile.resize((32, 32) # resize image to 32*32
    img_as_matrix = numpy.array(jpgfile)  # convert to numpy array
    img_as_matrix = img_as_matrix.reshape(img_as_matrix.shape[0]*img_as_matrix.shape[1]*img_as_matrix.shape[2],1).T  # Reshape and transpose image as the train images
    # Here the second dim is 1, since there is only 1 image instead of X.shape[3] images 
    
    value = clf.predict(img_as_matrix)
    

    【讨论】:

    • 我收到Expected 2D array, got 1D array instead: array=[212. 213. 217. ... 50. 50. 50.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.的错误
    • 如果我添加img_as_matrix = img_as_matrix.reshape(-1,1) ,我会在Number of features of the model must match the input. Model n_features is 3072 and input n_features is 1的最后一行得到一个错误
    • 好的,这是形状问题。你能告诉我 X 的形状(整形后)和numpy.array(jpgfile) 的形状吗?
    • X: (73257, 3072), np.array(jpgfile): (1024, 963, 3)
    • 所以你的图片需要有形状(1,3072)。我更正了我的答案:你能检查它是否有效吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2020-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多