Display a 32 bit unsigned int image with Tkinter and Python 3 Display a 32 bit unsigned int image with Tkinter and Python 3 tkinter tkinter

Display a 32 bit unsigned int image with Tkinter and Python 3


Step 1: make a function that can do the pixel conversion:

def convert(pixel):    '''convert 32-bit integer to 4 8-bit integers'''    return list(int(pixel).to_bytes(4, 'big'))

Step 2: convert your 2D array into a 3D array (I'll assume you named the array you have "data").

import numpy as npnew = np.empty((data.size, 4))old_shape = data.shapedata.shape = -1, # reshape into a 1D arrayfor i in range(data.size):    new[i] = convert(data[i])new.shape = old_shape + (-1,) # reshape into 3D

Step 3: Load the numpy array into an image.

from PIL import Imageimg = Image.fromarray(new, mode='RGBA')

Step 4a: If all you want to do is see or save the image then you can use PIL to do that; no tkinter needed.

img.show() # display in your default image viewerimg.save('data.png') # save to disk

Step 4b: If you do need to load it into tkinter then you can use ImageTk.PhotoImage to load it into a Label widget:

from PIL import ImageTkimport tkinter as tklbl = tk.Label()lbl.pimg = ImageTk.PhotoImage(img)lbl.config(image=lbl.pimg)lbl.pack()