【问题标题】:Converting image into MNIST format将图像转换为 MNIST 格式
【发布时间】:2021-06-17 01:37:23
【问题描述】:

我已经训练了一个 KNN 模型来预测 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 图像的中心并对其进行灰度化。我也认为我的图像没有正确转换为数组。有人能告诉我如何正确格式化图像以使预测更准确吗?

【问题讨论】:

    标签: python image opencv mnist image-preprocessing


    【解决方案1】:

    以下代码应该可以正常工作,或者您可能需要稍微调整一下。函数名称是不言自明的。

    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
    

    【讨论】:

    • 只是想澄清一下 run_inference 函数采用您想要运行推理的后者/数字的二值化图像(基本上是轮廓图像)。因此,在调用运行推理之前,您还有很多工作要做。
    【解决方案2】:

    我建议将处理后的图像可视化,以检查它是否居中并具有正确的对比度。见:Visualize MNIST dataset using OpenCV or Matplotlib/Pyplot

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-29
      • 1970-01-01
      • 2017-08-31
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      相关资源
      最近更新 更多