Skip to content

Instantly share code, notes, and snippets.

@hcl14
Last active October 16, 2018 10:20
Show Gist options
  • Save hcl14/45ff39d8091756913e41f2d3e3e4e513 to your computer and use it in GitHub Desktop.
Save hcl14/45ff39d8091756913e41f2d3e3e4e513 to your computer and use it in GitHub Desktop.
Running tkinter (packange pythin3-tk in Linux) as a separate process to display images, generated in main program
# My answer here: https://stackoverflow.com/questions/52793096/reload-and-zoom-image/52818151#52818151
from PIL import ImageTk, Image
from scipy.ndimage import rotate
from scipy.misc import imresize
import numpy as np
import time
# do not import *, as there is another Image
from tkinter import NW, Tk, Canvas, Label
from multiprocessing import Process, Queue
# initial image
image = Image.open("2_img.png")
# convert to numpy
image = np.array(image)
# process which will show updated images
def display_process(q):
# initialize window and label which will show images
master = Tk()
label = Label(master)
label.pack()
# take numpy image from Queue, draw in on canvas
def change_img():
# get one image from queue.
# if there is no one, None will be received
image = q.get()
# if not image received yet, skip
if image is not None:
print(image.shape)
# image array should be uint8 type with 3 channels (x, x, 3)
photo = ImageTk.PhotoImage(image = Image.fromarray(image))
label.configure(image=photo)
label.image = photo
# schedule next update
master.update_idletasks()
# check for new image each 50ms
master.after(50, change_img)
change_img()
master.mainloop() # draw canves, locks process
# Queue, through which exchange will be made
q = Queue()
q.put(image)
p = Process(target=display_process, args=(q,))
p.daemon = True # exit process on program exit
p.start() # start process
# main program (your loop code here) ----------
# Example:
for i in range(10):
# take numpy image, rotate it
image = rotate(image, 90)
# you can use fixed zoom factor for your images
# interp='nearest' uses nearest neghbor interpolation without smoothing
# (so you can see pixels)
image2 = imresize(image, 5.0, interp='nearest')
# send it to process
q.put(image2)
time.sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment