簡體   English   中英

如何預處理我的圖像,以便 SVM 可以像處理 MNIST 數據集一樣處理它

[英]How can I preprocess my image so it can be processed by a SVM in the same way it processes the MNIST dataset

我想使用在 MNIST 數據集上訓練的 SVM 分析我自己的圖像。 如何預處理我的圖像,使其可以被 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 圖像具有以下形狀:28x28x1,寬 28 像素,高 28 像素和一個顏色通道,即灰度。

假設您的 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.

根據您的圖像有多大,您可能需要手動 select 一個 28x28 補丁。 否則,您將面臨丟失圖像質量和信息的風險。

如果您 model 將向量作為輸入,您可以使用以下方法在將圖像輸入 model 之前將其展平:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM