[英]Read an image with OpenCV and display it with Tkinter
I have a very simple program on Ubuntu 14.04 LTS to read and display an image using OpenCV:我在 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
My problem:我的问题:
How can I keep reading the picture in OpenCV but display it using Tkinter ?如何继续在 OpenCV 中阅读图片但使用 Tkinter 显示它?
I ask this because I want to make an interface for my program but OpenCV is not able to do it so I need Tkinter for this.我问这个是因为我想为我的程序制作一个接口,但 OpenCV 无法做到这一点,所以我需要 Tkinter。 However, all the image processing I must do it on the background using OpenCV.但是,我必须使用 OpenCV 在后台进行所有图像处理。 Only displaying the results must be done using Tkinter.必须使用 Tkinter 仅显示结果。
EDIT:编辑:
From the answer above, I change the line:从上面的答案,我改变了这一行:
im = Image.open('slice001.hrs').convert2byte()
To:到:
im=cv2.imread() # (I imported cv2)
But I got an error.但我有一个错误。
I would appreciate any hints.我将不胜感激任何提示。
You might want to take a look at this one .你可能想看看这个。 Here is something works for me:这是对我有用的东西:
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
For Python3 I had to modify @Ha Dang answer:对于 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
Requirements were:要求是:
pip3 pip3
numpy==1.13.1
opencv-python==3.3.0.9
Pillow==4.2.1
brew酿造
python3
tcl-tk
For me both answers above did not work but where close.对我来说,上面的两个答案都不起作用,但很接近。 The following code did the trick for me (I also want to use place instead of pack):以下代码对我有用(我也想使用 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.