Python,在标签中的Tkinter中显示openCv图像

时间:2017-05-15 12:45:16

标签: python image opencv numpy tkinter

我尝试在Tkinter标签中显示openCV图像。当我从文件加载图像时:

img = ImageTk.PhotoImage("asd.png")

everythink工作得很好。但是当我改变它时,我只得到空的黑色图像,不管怎么说。这是示例代码:

import tkinter as tk
from tkinter import *

import cv2
from skimage import io
from PIL import Image, ImageTk
from skimage.color import rgb2gray


def make_label(master, x, y, w, h, img, *args, **kwargs):
   f = Frame(master, height = h, width = w)
   f.pack_propagate(0)
   f.place(x = x, y = y)
   label = Label(f, image = img, *args, **kwargs)
   label.pack(fill = BOTH, expand = 1)
   return label


if __name__ == '__main__':
   root = tk.Tk()
   frame = tk.Frame(root, width=400, height=600, background='white')
   frame.pack_propagate(0)
   frame.pack()
   image = rgb2gray(io.imread("asd.png"))

   image2 = Image.fromarray(image)
   img = ImageTk.PhotoImage(image2)
   make_label(root, 0, 0, 100, 100, img)
   root.mainloop()

请帮助

1 个答案:

答案 0 :(得分:1)

我认为问题是rgb2gray(io.imread("asd.png"))给出的灰度值介于0和1之间,而PIL期望0到255之间的值,因此Image.fromarray(image)的结果是黑色方块,因为所有值都是小于1.

因此image2 = Image.fromarray(image*255)应该提供预期的图像。