I'm working on a project and I have to generate a random binary image(that is, an image consisting of black and white pixels - 1 represents black and 0 represents white). Like this:
Then this is converted into a numpy array and saved to a txt file, like this (truncated result):
[[0 1 0 ... 0 0 1] [1 1 1 ... 0 0 0] [1 0 0 ... 0 1 0] ... [0 1 1 ... 1 0 1] [1 1 0 ... 0 1 1] [0 1 1 ... 0 1 0]]
Now I need to take that binary array and convert it back into an image like the example above. This is the code I have so far for this operation:
import numpy as np
from PIL import Image as im
array = np.genfromtxt('binary_array.txt', dtype=int)
print(array)
print(array.shape)
data = im.fromarray(array)
data.save('new_img.png')
(I'm using print statements just to better understand what is happening and what might be missing). Unfortunately, what I'm getting so far from this, is a black image. I'm sure there is something important I'm missing here, but I can't seem to think of anything. Thanks
CodePudding user response:
You could also use matplotlib with the bare array instead of PIL
from matplotlib import pyplot as plt
arr = np.array([[0,0,1,0], [1,0,0,0], [1,0,0,0],
[0,0,0,0]])
plt.imshow(arr, cmap='gray')
plt.savefig('img.png', cmap='gray')
CodePudding user response:
You can time this array by 255, then use method Image.fromarray
to convert it into PIL.Image
obejct.
from PIL import Image
import numpy as np
rand_array = np.random.randint(low=0, high=2, size=(100, 100), dtype=np.uint8)
im = Image.fromarray(rand_array * 255)
im.show()