繁体   English   中英

用 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) 

但我有一个错误。

我将不胜感激任何提示。

你可能想看看这个 这是对我有用的东西:

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM