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

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

我目前正在尝试在 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/

相关文章:

iphone - cv::matchShapes方法实现产生错误

android - 获得的位图是透明的,但是当设置为 ImageView 时变得不透明

python - 为什么我的(增量)值呈指数级增长?

python - 增加物体移动的速度(Tkinter)

python - 在我的本地盒子上运行我的 django webapp 时,为什么我使用 firefox 7.0.1 时出现黑屏

python - 多字表达式的字符串拆分问题

python - python zipfile 是线程安全的吗?

python - 如何在python中获取一个城市(geonameid)的附近城市?

image - 检测图像上的硬币(并拟合椭圆)

python - 如何制作 tkinter 条目小部件?