【问题标题】:Convert own image to MNIST's image将自己的图像转换为 MNIST 的图像
【发布时间】:2016-03-07 11:15:10
【问题描述】:

我是张量流的新手。 我使用 MNIST 的训练数据训练了数字预测模型。 然后我使用自己的图像测试模型。 它无法预测实际结果。

问题是:

  1. MNIST 的图片需要黑白的
  2. 图像尺寸已标准化以适合 20x20 像素框,并使用质心在 28x28 图像中居中。
  3. 我不想用OpenCV

问题是如何将我自己的手写数字图像移动到 28x28 图像的中心。自己的图像可以是任何颜色,并且该图像可以改变黑白MNIST的图像

【问题讨论】:

    标签: python-3.x tensorflow


    【解决方案1】:
    from PIL import Image, ImageFilter
    
    
    def imageprepare(argv):
        """
        This function returns the pixel values.
        The imput is a png file location.
        """
        im = Image.open(argv).convert('L')
        width = float(im.size[0])
        height = float(im.size[1])
        newImage = Image.new('L', (28, 28), (255))  # creates white canvas of 28x28 pixels
    
        if width > height:  # check which dimension is bigger
            # Width is bigger. Width becomes 20 pixels.
            nheight = int(round((20.0 / width * height), 0))  # resize height according to ratio width
            if (nheight == 0):  # rare case but minimum is 1 pixel
                nheight = 1
                # resize and sharpen
            img = im.resize((20, nheight), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
            wtop = int(round(((28 - nheight) / 2), 0))  # calculate horizontal position
            newImage.paste(img, (4, wtop))  # paste resized image on white canvas
        else:
            # Height is bigger. Heigth becomes 20 pixels.
            nwidth = int(round((20.0 / height * width), 0))  # resize width according to ratio height
            if (nwidth == 0):  # rare case but minimum is 1 pixel
                nwidth = 1
                # resize and sharpen
            img = im.resize((nwidth, 20), Image.ANTIALIAS).filter(ImageFilter.SHARPEN)
            wleft = int(round(((28 - nwidth) / 2), 0))  # caculate vertical pozition
            newImage.paste(img, (wleft, 4))  # paste resized image on white canvas
    
        # newImage.save("sample.png
    
        tv = list(newImage.getdata())  # get pixel values
    
        # normalize pixels to 0 and 1. 0 is pure white, 1 is pure black.
        tva = [(255 - x) * 1.0 / 255.0 for x in tv]
        print(tva)
        return tva
    
    x=imageprepare('./image.png')#file path here
    print(len(x))# mnist IMAGES are 28x28=784 pixels
    

    【讨论】:

      【解决方案2】:

      我会使用像这样的 numpy 配方—— https://www.kaggle.com/c/digit-recognizer/forums/t/6366/normalization-and-centering-of-images-in-mnist

      您可能可以将其重新映射到纯 TensorFlow 管道,但我不确定是否有必要,因为它是小图像。

      另外,如果您采用另一种方式,您将获得更高的准确性 - 不是对输入数据进行标准化,而是通过在更大的随机移位/重新缩放的 MNIST 数字数据集上进行训练,使您的网络在缺乏标准化的情况下具有鲁棒性。

      【讨论】:

        猜你喜欢
        • 2021-06-17
        • 1970-01-01
        • 1970-01-01
        • 2016-12-01
        • 1970-01-01
        • 2018-08-06
        • 2019-09-29
        • 2019-06-28
        • 1970-01-01
        相关资源
        最近更新 更多