[英]How can I preprocess my image so it can be processed by a SVM in the same way it processes the MNIST dataset
I want to analyze my own images using an SVM trained on the MNIST dataset.我想使用在 MNIST 数据集上训练的 SVM 分析我自己的图像。 How can I preprocessed my image so it can be accepted by the model?
如何预处理我的图像,使其可以被 model 接受?
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 images have the following shape: 28x28x1, width 28 pixels, height 28 pixels and one color channel ie grayscale. MNIST 图像具有以下形状:28x28x1,宽 28 像素,高 28 像素和一个颜色通道,即灰度。
Assuming your model takes the same input shape, you can use the following:假设您的 model 采用相同的输入形状,您可以使用以下内容:
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.
Depending on how large your image is, you may want to select an 28x28 patch manually.根据您的图像有多大,您可能需要手动 select 一个 28x28 补丁。 Otherwise you risk of losing image quality and thus information.
否则,您将面临丢失图像质量和信息的风险。
If you model takes a vector as input, you can use the following to flatten your image before feeding it to the model:如果您 model 将向量作为输入,您可以使用以下方法在将图像输入 model 之前将其展平:
userImage = np.reshape(userImage,(784,))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.