1

I'm trying to convert an array to an image using the Image.fromarray in PIL but i can't seem to get the shape I'm looking for. Here's my code:

def affichage(c, disp):
    for i in range(len(c)):
        for j in range(len(c)):
            if c[i][j]==0:
                disp[i][j]=[255,255,255]
            elif c[i][j]==1:
                disp[i][j]=[255,0,0]
            elif c[i][j]==2:
                disp[i][j]=[0,255,0]
            elif c[i][j]==3:
                disp[i][j]=[0,0,255]
    return disp

disp = affichage(c,disp)
img = Image.fromarray(disp, 'RGB')
img.save('affichage.png', 'png')
img.show()

I'm converting my array with value ranging from 0 to 3 int RGB colors but it display weird rows of color that don't output the same if i plot the array Here is the output image:

Using Image.fromarray

Using Image.fromarray

Using matplotlib to plot the array

Using matplotlib to plot the array

How can I get the same output as matplotlib ?

pippo1980
  • 2,181
  • 3
  • 14
  • 30
Abisel
  • 11
  • 2
  • Matplotlib is probably using a colormap. please show us the Matplotlib code you're using, too. – AKX Nov 05 '20 at 20:22
  • Please put back the `import` statements you have removed. Please show how you create `disp` and give some representative initialisation for `c`. – Mark Setchell Nov 05 '20 at 20:24
  • My matlotlib code for the colormap is: `foret = matplotlib.colors.ListedColormap(["#8B4513", "blue","red","darkgreen"]) matplotlib.pyplot.imshow(c,cmap=foret)` – Abisel Nov 05 '20 at 21:14
  • I'm trying to display a forest with each cell representing a tree, c is the 'map' of this forest: No tree is 0 and the different stage of growth of a tree ranges from 1 (just planted) to 3 (harvestable). it is initialised randomly using `random.choices` It is supposed to change each pass but with matplotlib i only managged to show the last state. I'm trying to convert it to an image but i can't pull it off. disp is supposed to be an array giving each value a color in RGB mode. – Abisel Nov 05 '20 at 21:23
  • If you only have a few colours (less than 256) you would be miles better off and miles faster with a palette image. Example here... https://stackoverflow.com/a/64682849/2836621 and explanation here... https://stackoverflow.com/a/52307690/2836621 – Mark Setchell Nov 06 '20 at 07:56
  • can we have 'c' = and 'disp' = ? just to try out your code ? and the way you used matplotlib to show c ? – pippo1980 Feb 07 '21 at 16:50

0 Answers0