使用 OpenCV 读取图像并使用 Tkinter 显示它

Read an image with OpenCV and display it with Tkinter

我在 Ubuntu 14.04 LTS 上有一个非常简单的程序来使用 OpenCV 读取和显示图像:

import cv2 #import OpenCV

img = cv2.imread('picture.jpg') #read a picture using OpenCV
cv2.imshow('image',img) # Display the picture
cv2.waitKey(0) # wait for closing
cv2.destroyAllWindows() # Ok, destroy the window

我的问题:

如何在 OpenCV 中继续读取图片,但使用 Tkinter 显示它?

我问这个是因为我想为我的程序制作一个界面,但 OpenCV 无法做到,所以我需要 Tkinter。但是,我必须使用 OpenCV 在后台进行所有图像处理。仅显示结果必须使用 Tkinter 完成。

编辑:

根据上面的回答,我改行:

im = Image.open('slice001.hrs').convert2byte()

收件人:

im=cv2.imread() # (I imported cv2) 

但是我得到一个错误。

如有任何提示,我将不胜感激。

您可能想看看 this one。这是适合我的东西:

import numpy as np
import cv2
import Tkinter 
import Image, ImageTk

# Load an color image
img = cv2.imread('img.png')

#Rearrang the color channel
b,g,r = cv2.split(img)
img = cv2.merge((r,g,b))

# A root window for displaying objects
root = Tkinter.Tk()  

# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im) 

# Put it in the display window
Tkinter.Label(root, image=imgtk).pack() 

root.mainloop() # Start the GUI

为了Python3我不得不修改@Ha Dang的回答:

from tkinter import *
from PIL import Image, ImageTk
import cv2
import numpy as np

image_name = 'bla.jpg'

image = cv2.imread(image_name)

#Rearrang the color channel
b,g,r = cv2.split(image)
img = cv2.merge((r,g,b))

# A root window for displaying objects
root = Tk()  

# Convert the Image object into a TkPhoto object
im = Image.fromarray(img)
imgtk = ImageTk.PhotoImage(image=im) 

# Put it in the display window
Label(root, image=imgtk).pack() 

root.mainloop() # Start the GUI

要求是:

pip3

numpy==1.13.1
opencv-python==3.3.0.9
Pillow==4.2.1

酿造

python3
tcl-tk

对我来说,上面的两个答案都不起作用,但很接近。以下代码对我有用(我也想使用 place 而不是 pack):

    image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)
    image = ImageTk.PhotoImage(image=Image.fromarray(image))
    label_image = Label(self.detection, image=image)
    label_image.image = image
    label_image.place(x=0, y=0, anchor="w")