【问题标题】:How can I preprocess my image so it can be processed by a SVM in the same way it processes the MNIST dataset如何预处理我的图像,以便 SVM 可以像处理 MNIST 数据集一样处理它
【发布时间】:2020-02-19 00:32:44
【问题描述】:

我想使用在 MNIST 数据集上训练的 SVM 分析我自己的图像。如何预处理我的图像以便模型可以接受?

dataset = datasets.fetch_openml("mnist_784", version=1)
(trainX, testX, trainY, testY) = train_test_split(
    dataset.data / 255.0, dataset.target.astype("int0"), test_size = 0.33)

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, default="3scenes",
    help="path to directory containing the '3scenes' dataset")
ap.add_argument("-m", "--model", type=str, default="knn",
    help="type of python machine learning model to use")

args = vars(ap.parse_args())

#user input image to classify

userImage = cv.imread('path_to_image/1.jpg')

#preprocess user image
#...

models = {
    "svm": SVC(kernel="linear"),
}

# train the model
print("[INFO] using '{}' model".format(args["model"]))
model = models[args["model"]]
model.fit(trainX, trainY)

print("[INFO] evaluating image...")
predictions = model.predict(userImage)
print(classification_report(userImage, predictions))

【问题讨论】:

  • 这些代码到底是关于什么的?
  • 如果没有看到这些图像就很难分辨。
  • 我只想使用在 MNIST 数据集上训练的模型对我的图像进行分类。我的问题是如何将 mi 图像转换为与 MNIST 数据集相同的格式,以便我可以将其传递给模型并获得分类。也许这不是它的工作方式,我是这个主题的初学者,请让我知道任何见解。

标签: python machine-learning image-processing svm mnist


【解决方案1】:

MNIST 图像具有以下形状:28x28x1,宽 28 像素,高 28 像素和一个颜色通道,即灰度。

假设您的模型采用相同的输入形状,您可以使用以下内容:

import cv2
userImage = cv2.imread('path_to_image/1.jpg')
# resize image to 28x28
userImage = cv2.resize(userImage,(28,28))
# convert to grayscale
userImage = cv2.cvtColor(userImage,cv2.COLOR_BGR2GRAY)
# normalize
userImage /= 255.

根据图像的大小,您可能需要手动选择 28x28 补丁。否则,您可能会丢失图像质量和信息。

如果您的模型将向量作为输入,您可以使用以下方法在将图像输入模型之前将其展平:

userImage = np.reshape(userImage,(784,))

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2016-12-09
    • 2019-07-09
    • 2020-09-21
    相关资源
    最近更新 更多