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

Posted

技术标签:

【中文标题】使用 OpenCV 读取图像并使用 Tkinter 显示【英文标题】:Read an image with OpenCV and display it with Tkinter 【发布时间】:2015-04-24 13:55:59 【问题描述】:

我在 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) 

但我遇到了一个错误。

我会很感激任何提示。

【问题讨论】:

【参考方案1】:

您可能想看看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

【讨论】:

谢谢。但我没有看到您在哪里使用 OpenCV 读取图像? 只需编辑答案。但是小伙伴们,你们自己试一试吧? DIY - 这是最好的学习方式。 我试过了(见我的编辑)。您的第二个解决方案几乎可以完美运行。然而,只有一个缺点:我的图像几乎是橙色的,但现在它几乎显示为蓝色:( 我添加了 RGB 模式以像这样im = Image.fromarray(img,'RGB') 读取它,但结果相同:( 这是因为颜色通道顺序是 BBGR,而不是 RGB。您可以在代码中添加以下两行: b,g,r = cv2.split(img) img = cv2.merge((b,g,r))【参考方案2】:

对于 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

【讨论】:

【参考方案3】:

对我来说,上面的两个答案都不起作用,但很接近。以下代码对我有用(我也想使用 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")

【讨论】:

以上是关于使用 OpenCV 读取图像并使用 Tkinter 显示的主要内容,如果未能解决你的问题,请参考以下文章

[实例]ROS使用OpenCV读取图像并发布图像消息在rviz中显示

OpenCV 读取图像并使用整数值管理它们的像素(如 matlab)

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

python OpenCV 读取并显示图像

详解OpenCV的函数imread()和函数imshow(),并利用它们实现对图像的读取和显示

读取图像中的像素值并保存在 OpenCv 文件中