python - 重新加载和缩放图像
问题描述
我正在玩一点 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()
如何在保持缩放级别的同时始终重新加载图像?
解决方案
您可以尝试将 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)
推荐阅读
- javascript - 可在网页中实时预览的可嵌入乳胶编辑器
- sorting - 表键未正确排序
- autohotkey - 如何使用 AutoHotkey 获取 Microsoft Teams 活动会议窗口?
- python - 如何使用按钮将值输入到不同的输入框中?
- compiler-errors - Cython 教程编译失败 [OSX]
- node.js - node.js 的 MongoDB 驱动程序,事务 API,错误“client.startSession() 不是函数”
- javascript - 我想为提交我的页面创建一个类似 onbeforeunload 的函数
- reactjs - 如何在子组件中使用路由?反应路线
- python - 将 C++ 中的代码转换为 python 的数组和列表错误
- wifi - 尝试与 CYW4343W cypress wifi 芯片通信