Reputation: 141
I have an MxN ndarray that contains True and False values inside those arrays and want to draw those as an image. The goal is to convert the array to a pillow image with each True value as a constant color. I was able to get it working by looping through each pixel and changing them individually by a comparison and drawing the pixel on a blank image, but that method is way too slow.
# img is a PIL image result
# image is the MxN ndarray
pix = img.load()
for x in range(image.shape[0]):
for y in range(image.shape[1]):
if image[x, y]:
pix[y, x] = (255, 0, 0)
Is there a way to change the ndarray to a MxNx3 by replacing the tuples directly to the True values?
Upvotes: 3
Views: 194
Reputation: 207445
I think you can do this quite simply and fast like this:
# Make a 2 row by 3 column image of True/False values
im = np.random.choice((True,False),(2,3))
Mine looks like this:
array([[False, False, True],
[ True, True, True]])
Now add a new axis it make it 3 channel and multiply the truth values by your new "colour":
result = im[..., np.newaxis]*[255,255,255]
which gives you this:
array([[[ 0, 0, 0],
[ 0, 0, 0],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]])
Upvotes: 0
Reputation: 141
Did find another solution, converted to an image first, then converted to RGB, then converted back to separate to 3 channels. When I was trying to combine multiple boolean arrays together, this way was a lot faster.
img = Image.fromarray(image * 1, 'L').convert('RGB')
data = np.array(img)
red, green, blue = data.T
area = (red == 1)
data[...][area.T] = (255, 255, 255)
img = Image.fromarray(data)
Upvotes: 1
Reputation: 825
If you have your True/False 2D array and the label for the color, for example [255,255,255]
, the following will work:
colored = np.expand_dims(bool_array_2d,axis=-1)*np.array([255,255,255])
To illustrate it with a dummy example: in the following code I have created a random matrix of 0s and 1s and then have turned the 1s to white ([255,255,255]).
import numpy as np
import matplotlib.pyplot as plt
array = np.random.randint(0,2, (100,100))
colors = np.array([255,255,255])
colored = np.expand_dims(array, axis=-1)*colors
plt.imshow(colored)
Hope this has helped
Upvotes: 1