Is there a way to convert a 3-value array into an image? Is there a way to convert a 3-value array into an image? tkinter tkinter

Is there a way to convert a 3-value array into an image?


You were very close with your code, you were just missing a Look Up Table (LUT) to look up the colour corresponding to your 0,1,2 data:

#!/usr/local/bin/python3import numpy as npfrom PIL import Image# Specify image size, create and fill with random 0, 1, or 2w, h = 500, 400 data = np.random.randint(0,3,(h, w), dtype=np.uint8)# Make LUT (Look Up Table) with your 3 coloursLUT = np.zeros((3,3),dtype=np.uint8)LUT[0]=[255,0,0]LUT[1]=[0,255,0]LUT[2]=[0,0,255]# Look Up each pixel in the LUTpixels = LUT[data]# Convert Numpy array to image, save and displayimg = Image.fromarray(pixels) img.save('result.png')img.show() 

enter image description here


You could use PIL to create (and display) an image:

from PIL import Imageimport numpy as npw, h = 512, 512data = np.zeros((h, w, 3), dtype=np.uint8)data[256, 256] = [255, 0, 0]img = Image.fromarray(data, 'RGB')img.save('my.png')img.show()


So, there are two-three parts to this, and a few ways to go about it.

For simplicity, you could simply make a 2D numpy array of triples:

np.zeros((h, w, 3))

And then iterate over it, assigning each value to either (225, 0, 0), (0, 255, 0), or (0, 0, 255) depending on the value returned from a call to the random library.


More generically though, if you wanted an arbitrary number of colors and arbitrary assignment of those colors, I'd recommend something more like:

  1. Make a 2D array with random values from numpy.random.rand
  2. scale those values to however many colors you have, and convert to integers
  3. color each pixel in a new numpy array with the color corresponding to its number
  4. convert to PIL image
colorMapping = {    0: (255, 0, 0),    1: (0, 255, 0),    2: (0, 0, 255),    3: (255, 255, 0),    4: (128, 42, 7),    5: (128, 42, 7)    # whatever colors you want. Could also use a list, but may be less clear.}w = #somethingh = #somethingnumberOfColors = len(colorMapping)randArray = np.random.rand(w, h)scaledArray = randArray * numberOfColorscolorMapArray = scaledArray.astype(int)# see [here][3] for sleeker, more elegant way of doing thispixels = np.zeros((w, h, 3))for i in range(0, w):    for j in range(0, h):        colorNumber = colorMapArray[i, j]        pixels[(i, j)] = colorMapping[colorNumber]im = Image.fromarray(pixels.astype('uint8'), 'RGB')im.show()

In response to the edit:

You could do it like in that code example with minor changes, but you'd need to use one of the things in this question also linked above, for applying a function to every value in a 2D numpy array.