如何对图像进行预处理,以便支持向量机以处理MNIST数据的相同方式对其进行处理

2024-06-30 15:53:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用MNIST数据集上训练的支持向量机来分析我自己的图像。如何对图像进行预处理,使其被模型接受

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))

Tags: totest图像imageaddmodeltypetrainy
1条回答
网友
1楼 · 发布于 2024-06-30 15:53:54

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,))

相关问题 更多 >