首页 > 解决方案 > 重新加载和缩放图像

问题描述

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

目前,我只是在 Eye of 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()

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

标签: pythonpython-imaging-library

解决方案


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

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)

推荐阅读