我想使用在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图像具有以下形状: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,))