如何在 python 中使用 Image.fromaray() 生成随机彩色图像?
How do I generate a random colored image using Image.fromaray() in python?
我正在尝试使用 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)
它们的形状相同,我不明白我哪里弄错了。
当我创建一个 2D 数组然后将其转换回来时,它给我一个那个大小的黑色 canvas(即使像素不应该是黑色)。
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)
我能够使用详细的解决方案 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)
我正在尝试使用 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)
它们的形状相同,我不明白我哪里弄错了。
当我创建一个 2D 数组然后将其转换回来时,它给我一个那个大小的黑色 canvas(即使像素不应该是黑色)。
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)
我能够使用详细的解决方案 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)