def arrayconv(a):
black = [0, 0, 0, 1] #RGBA value for black
white = [255, 255, 255, 1] #RGBA value for white
red = [255, 0, 0, 1] #RGBA value for red
b = np.zeros(shape=(10, 10), dtype=object) #creates an array of zeroes
for i in range(10):
for j in range(10):
if a[i][j] == 0: #Copies the values of a into b except in rgba.
b[i][j] = black
if a[i][j] == 1:
b[i][j] = white
if a[i][j] == 2:
b[i][j] = red
print(b)
return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().
I am writing a program that solves a ten by ten pixel maze. This code is from the back end of the program, and it is supposed to convert an array of 0s, 1s, and 2s into a new array with a corresponding rgba value. That part works fine.
But when I use fromarray()
to print this picture, it is different colors than intended. The image prints out with the correct amount of colors (three) and the right arrangement but in shades of blue or in shades of green. The same incorrect color scheme does not print every time as well.
You have to create a 3 dimensional array with dtype='uint8'
for b
.
This code works for me:
def arrayconv(a):
b = np.zeros(shape=(a.shape[0], a.shape[1], 4), dtype="uint8") #creates an array of zeroes
colormap = {
0: (0, 0, 0, 1),
1: (255, 255, 255, 1),
2: (255, 0, 0, 1),
}
for index_x, row in enumerate(a):
for index_y, pixel in enumerate(row):
b[index_x, index_y] = colormap[pixel]
return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().
#create test data
data = [random.randint(0, 2) for i in range(100 * 100)]
data = np.reshape(data, (100, 100))
img = arrayconv(data)
img.show()
If you only change
b = np.zeros(shape=(10, 10), dtype=object)
to
b = np.zeroes(shape=(10, 10, 4), dtype="uint8")
your code should work as well.