簡體   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