【问题标题】:How do I generate a random colored image using Image.fromaray() in python?如何在 python 中使用 Image.from array() 生成随机彩色图像?
【发布时间】:2021-09-26 02:34:01
【问题描述】:

我正在尝试使用 NUMPY 创建一个随机图像。首先,我正在创建一个随机 3D 数组,因为它应该是在图像的情况下,例如(177,284,3)。

random_im = np.random.rand(177,284,3)

data = np.array(random_im)
print(data.shape)
Image.fromarray(data)

但是当我使用 Image.fromarray(random_array) 时,会抛出以下错误。

只是为了检查数组的形状是否有任何问题,我将图像转换回数组并在将其复制到另一个变量后将其转换回来。我得到了我正在寻找的输出。

img = np.array(Image.open('Sample_imgs/dog4.jpg'))
git = img.copy()
git.shape
Image.fromarray(git)

它们的形状相同,我不明白我在哪里做错了。

当我创建一个二维数组然后将其转换回来时,它给了我一个该大小的黑色画布(即使像素不应该是黑色的)。

random_im = np.random.randint(0,256,size=(231,177))

print(random_im)
# data = np.array(random_im)
print(data.shape)
Image.fromarray(random_im)

【问题讨论】:

    标签: python arrays python-3.x numpy python-imaging-library


    【解决方案1】:

    我能够使用详细的解决方案 here

    import numpy as np
    from PIL import Image
    random_array = np.random.rand(177,284,3)
    random_array = np.random.random_sample(random_array.shape) * 255
    random_array = random_array.astype(np.uint8)
    random_im = Image.fromarray(random_array)
    random_im.show()
    

    ----编辑 无需转换即可获得正确类型的随机数组的更优雅的方法如下:

    import numpy as np
    from PIL import Image
    random_array = np.random.randint(low=0, high=255,size=(250,250),dtype=np.uint8)
    random_im = Image.fromarray(random_array)
    random_im.show()
    

    这几乎是您在解决方案中所做的,但您必须将 dtype 指定为 np.uint8:

    random_im = np.random.randint(0,256,size=(231,177),dtype=np.uint8)
    

    【讨论】:

    • 是的,一开始我也在使用 randint。毕竟主要问题是 dtype 。谢谢哥们。你能解释一下我们需要这个 dtype 的原因吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2020-03-22
    • 2017-03-28
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    相关资源
    最近更新 更多