[英]Converting image into MNIST format
我已經訓練了一個 KNN model 來預測 MNIST 數據集中的手寫圖像。 我現在想用我自己的筆跡來測試它。 我想將其轉換為 MNIST 格式(圖像中 784 像素的值作為數組)。 我嘗試將圖像轉換為 28*28 像素並將像素強度存儲在下面的代碼中:
img = cv2.imread(image,cv.IMREAD_GRAYSCALE)
resized = cv2.resize(img, (28,28))
features = resized.reshape(1,-1)
但由於某種原因,它不起作用,預測總是“0”。 我想我需要將自己的圖像轉移到 28x28 圖像的中心並對其進行灰度化。 我也認為我的圖像沒有正確轉換為數組。 有人可以告訴我如何正確格式化圖像以使預測更准確嗎?
我建議可視化您處理過的圖像以檢查它是否居中並具有正確的對比度。 請參閱: 使用 OpenCV 或 Matplotlib/Pyplot 可視化 MNIST 數據集
以下代碼應該可以正常工作,或者您可能需要稍微調整一下。 Function 名稱是不言自明的。
import numpy as np
import cv2
def resize_to_28x28(img):
img_h, img_w = img.shape
dim_size_max = max(img.shape)
if dim_size_max == img_w:
im_h = (26 * img_h) // img_w
if im_h <= 0 or img_w <= 0:
print("Invalid Image Dimention: ", im_h, img_w, img_h)
tmp_img = cv2.resize(img, (26,im_h),0,0,cv2.INTER_NEAREST)
else:
im_w = (26 * img_w) // img_h
if im_w <= 0 or img_h <= 0:
print("Invalid Image Dimention: ", im_w, img_w, img_h)
tmp_img = cv2.resize(img, (im_w, 26),0,0,cv2.INTER_NEAREST)
out_img = np.zeros((28, 28), dtype=np.ubyte)
nb_h, nb_w = out_img.shape
na_h, na_w = tmp_img.shape
y_min = (nb_w) // 2 - (na_w // 2)
y_max = y_min + na_w
x_min = (nb_h) // 2 - (na_h // 2)
x_max = x_min + na_h
out_img[x_min:x_max, y_min:y_max] = tmp_img
return out_img
def run_inference(img):
tsr_img = resize_to_28x28(img)
input_data = np.copy(tsr_img).reshape(1,28,28,1)
if floating_model:
input_data = (np.float32(input_data) - input_mean) / input_std
# Instantiate tensorflow interpreter and run inference on input_data
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.