我正在从相机捕捉图像并在Tkinter的画布上显示图像。 但是,看起来很奇怪的现象是画布将使用下面的代码闪烁
def get_image_cam() :
global cam,cam_flag,cam_image, cam_imageTk, canvas_img
print '[THREAD CREATE]get image camera'
print cam_flag
while cam_flag :
image = cam.get_image()
pygame.image.save(image,'capture.bmp')
cam_image = Image.open('capture.bmp')
cam_imageTk = ImageTk.PhotoImage(cam_image)
canvas_img.create_image(0, 0, anchor = NW ,image = cam_imageTk)
print '[THREAD EXIT] get image camera'
thread.exit_thread()
我已经搜索了很多来解决这个问题。下面是一些代码 http://codingmess.blogspot.com/2008/07/showing-webcam-image-in-desktop-window_08.html, 它确实有帮助
def showimage(image):
'''Loads given image and puts it into the window'''
img = Image.open(image)
photo = ImageTk.PhotoImage(img)
container.canvas.create_image(container.width/2+2, container.height/2, image=photo)
container.obr = photo # why is this line necessary?
作为帖子的作者说,他不知道为什么这个'container.obr = photo'有帮助。 我对我的代码做了同样的事情。它改变如下:
def get_image_cam() :
global cam,cam_flag,cam_image, cam_imageTk, canvas_img
print '[THREAD CREATE]get image camera'
print cam_flag
while cam_flag :
image = cam.get_image()
pygame.image.save(image,'capture.bmp')
cam_image = Image.open('capture.bmp')
cam_imageTk = ImageTk.PhotoImage(cam_image)
canvas_img.create_image(0, 0, anchor = NW ,image = cam_imageTk)
obr = cam_imageTk # variable 'obr' is not neccessary, you can change it to anything you want
print '[THREAD EXIT] get image camera'
thread.exit_thread()
有没有人可以帮我解释一下?提前谢谢。
答案 0 :(得分:1)
PhotoImage
创建本地对象(在函数中)当您离开函数时被垃圾收集器删除(并且您丢失了图像以便闪烁)。
您必须将此分配给现有的全局变量或现有对象。