gpt4 book ai didi

python-3.x - 将自己的图像转换为 MNIST 的图像

转载 作者:行者123 更新时间:2023-12-03 09:30:14 37 4
gpt4 key购买 nike

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

问题是:

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

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

    最佳答案

    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

    关于python-3.x - 将自己的图像转换为 MNIST 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35842274/

    37 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com