gpt4 book ai didi

python - 使用 PIL/Tkinter 分析图像序列

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:30 25 4
gpt4 key购买 nike

我目前正在尝试在 Tkinter 中设置一个 GUI,以便可以显示一系列图像(名为 file01.jpg、file02.jpg 等)。目前,我正在通过创建一个 Sequence 对象来管理我关心的图像列表来做到这一点:

class Sequence:
def __init__(self,filename,extension):
self.fileList = []
#takes the current directory
listing = os.listdir(os.getcwd())
#and makes a list of all items in that directory that contains the filename and extension
for item in listing:
if filename and extension in item:
self.fileList.append(item)
#and then sorts them into order
self.fileList.sort()
print self.fileList

def nextImage(self):
#returns a string with the name of the next image
return self.fileList.pop(0)

然后我使用我在网上找到的一个相当简单的 Tkinter 脚本来生成窗口并在其中放置图像:

window = Tkinter.Tk()
window.title('Image Analysis!')
sequence = Sequence('test','jpg')

image = Image.open("test01.jpg")
image = image.convert('L')
imPix = image.load()
canvas = Tkinter.Canvas(window, width=image.size[0], height=image.size[1])
canvas.pack()
image_tk = ImageTk.PhotoImage(image)
canvas.create_image(image.size[0]//2, image.size[1]//2, image=image_tk)
window.bind("<space>", lambda e: nextFrame(sequence_object=sequence,event=e))
Tkinter.mainloop()

其中 nextFrame 定义为:

def nextFrame(sequence_object,event=None):
nextImage = sequence_object.nextImage()
print 'Next Image is: ',nextImage
image = Image.open(nextImage)
image = image.convert('L')
imPix = image.load()
image_tk = ImageTk.PhotoImage(image)
canvas.create_image(image.size[0]//2, image.size[1]//2, image=image_tk)
canvas.update()

在我的 python 缓冲区中,我看到弹出正确的图像序列(“下一个图像是:test02,jpg”等),但新图像永远不会弹出!

有谁能解释一下为什么图片不弹出吗?

谢谢!

内森·拉亨梅尔

最佳答案

可能发生的情况是图像被垃圾收集器销毁,因为对图像的唯一引用是局部变量。

尝试保留对图像的永久引用,例如:

...
self.image_tk = ImageTk.PhotoImage(image)
...

关于python - 使用 PIL/Tkinter 分析图像序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9880984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com