重新加载并缩放图像

时间:2018-10-13 12:47:51

标签: python python-imaging-library

我正在播放100x100像素的图像,并一直创建和更新。我的代码工作正常,但是我希望在程序运行时显示并更新图像,将其放大到可以看到单独像素的程度。

当前,我只是在Gnome眼中打开生成的图像,该图像会自动重新加载。这里的问题是,每次重新加载时,缩放级别都跳回到100%(应该在600%左右)。

while self.running:
    img.save("image.tmp.png")
    time.sleep(1)
    os.rename("image.tmp.png", "image.png")

尝试使用PIL的show方法有效,但是会为每个视图创建一个新窗口。

while self.running:
     img.show()

如何在保持缩放级别的同时一直重新加载图像?

1 个答案:

答案 0 :(得分:0)

您可以尝试将tkinter(在Linux中安装软件包python3-tk,不了解其他操作系统)作为单独的进程来启动:

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("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


        # needed to schedule next update: 
        master.update_idletasks()
        # check for new image after 50ms
        master.after(50, change_img)


    change_img()
    master.mainloop() # 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)