【问题标题】:Analyzing a Sequence of Images using PIL/Tkinter使用 PIL/Tkinter 分析图像序列
【发布时间】:2012-04-10 11:30:26
【问题描述】:

我目前正在尝试在 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'等),但新图像永远不会弹出!

有没有人解释为什么图片没有弹出?

谢谢!

内森·拉肯迈尔

【问题讨论】:

    标签: python image-processing tkinter python-imaging-library


    【解决方案1】:

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

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

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

    【讨论】:

    • 看来你是对的! nextFrame() 中的一个简单的“全局 image_tk”修复了它。
    • @asymptoticdesign:无论您在何处创建变量来保存图像,请确保该变量不是本地变量。
    猜你喜欢
    • 2012-06-29
    • 2020-04-19
    • 2013-09-27
    • 2022-06-27
    • 2015-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    相关资源
    最近更新 更多