I have a very simple program on Ubuntu 14.04 LTS to read and display an image using 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 ?
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. However, all the image processing I must do it on the background using OpenCV. Only displaying the results must be done using 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
from PIL 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:
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
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 were close. The following code did the trick for me (I also want to use place instead of pack):
from PIL import ImageTk, Image
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")
Related
The url to image decoding process that I got from the internet seems to be manipulating images very weirdly and discoloring them, and as I have no idea how the process works I'm not able to figure out what the problem is. if you take this url: https://cdn.w600.comps.canstockphoto.com/human-freedom-happiness-in-nature-stock-photo_csp5610464.jpg and try to open it, it will show you the original image. But if you take the code below and try to convert that into a tkinter compatible image, it produces the same thing except the everything got tinted with blue and her skirt became yellow. Can someone figure out what the issue is or provide a better method of converting images into a format readable by tkinter? Thank you!
import cv2
import urllib.request as req
import numpy as np
from tkinter import *
from PIL import Image, ImageTk
imgUrl='https://cdn.w600.comps.canstockphoto.com/human-freedom-happiness-in-nature-stock-photo_csp5610464.jpg'
image1=''
def url_to_image(url):
# download the image, convert it to a NumPy array, and then read
# it into OpenCV format
resp = req.urlopen(url)
image = np.asarray(bytearray(resp.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
# return the image
return image
class ImageFrame:
def __init__(self, master):
self.master = master
master.title("Image")
#root.geometry("1920x1080")
master.config(bg="black")
master.resizable(False,False)
self.image=Label(master, image=imgma1)
self.image.pack()
root = Tk()
imgmal = Image.fromarray(url_to_image(imgUrl))
imgmal.thumbnail((600, 650))
imgma1 = ImageTk.PhotoImage(imgmal)
mainWindow = ImageFrame(root)
root.mainloop()
The image color mode of OpenCV is in BGR, so you need to convert to RGB using cv2.cvtColor():
...
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert BGR to RGB
...
With the following code I want to display images from a relative path .\Datasets\image_datasets\problem_datasets within my project, I am unable to do so with tkinter, Instead it displays all the images in same UI window, I want these images to be displayed like a stream of frames as a video, can you help me understand why I don't get the expected ouput.
code :
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib import image
from numpy import imag
import matplotlib.pyplot as plt
import glob
root = tk.Tk()
root.title("Test app")
images = [file for file in glob.glob('.\\Datasets\\image_datasets\\problem_datasets\\*.jpg')]
for path in images:
img = ImageTk.PhotoImage(Image.open(path))
lab = tk.Label(root,image=img)
lab.photo = img
lab.pack()
root.mainloop()
A couple of points:
you dont need lab.photo = img
you need to define and pack the label outside of your loop and just overwrite the image property inside, otherwise you create new labels each iteration
i recommend using os.sep instead of hardcoded folder separators \\ to be OS-independent
to actually see the transition, you need time.sleep or similar
my example will freeze the GUI, if you want it to be reactive after launching your image-transitions/"video", you will have to implement Threads
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib import image
from numpy import imag
import matplotlib.pyplot as plt
import glob
import os
import time
root = tk.Tk()
root.title("Test app")
images = [file for file in glob.glob('.' + os.sep + 'Datasets' + os.sep + 'image_datasets' + os.sep + 'problem_datasets' + os.sep + '*.jpg')]
lab = tk.Label(root)
lab.pack()
for path in images:
_img = ImageTk.PhotoImage(Image.open(path))
lab.config(image=_img)
root.update() # to update the GUI
time.sleep(0.25) # to see the transition
root.mainloop()
You created new label in each iteration of the for loop. Instead you should create the label once before the for loop and update its image inside it.
However using loop and time.sleep() is not recommended in a tkinter application, suggest to use .after() instead:
import tkinter as tk
from PIL import ImageTk, Image
import glob
root = tk.Tk()
root.title("Test app")
images = glob.glob('./Datasets/image_datasets/problem_datasets/*.jpg')
# create the label for showing the images
lab = tk.Label(root)
lab.pack()
def show_image(i=0):
if i < len(images):
img = ImageTk.PhotoImage(file=images[i])
# update image
lab.config(image=img)
lab.photo = img # save reference of image to avoid garbage collection
# can change 10(ms) to other value to suit your case
root.after(10, show_image, i+1)
show_image() # start showing the images
root.mainloop()
So i am using python 3 and got confused why the image doesnt show up in text widget after excuted the following code:
from tkinter import *
import fitz
root=Tk()
filenew=fitz.open(r'C:\Users\azoka\Desktop\Python\b.pdf')
text_1=Text(root,width=100,height=100,bg='gray').pack(side=LEFT,expand=FALSE)
def Show():
pix =filenew.getPagePixmap(0) # 0 is page number
pix1=fitz.Pixmap(pix,0)
img =pix1.getImageData("ppm")
timg=PhotoImage(data=img)
frame=[]
frame.append(timg)
text_1.image_create(END,image=timg)
Shower=Button(win1,text='show',bg='navy',fg='light cyan',width=5,height=1,command=Show)
Shower.place(x=1000,y=360)
root.mainloop()
The image just dont show up after clicked the button but it doesnt show any code error,I am new to python
and cant figure out. I want my img be shown without altering the Show()function.
-Appreciate for helpful answers!-
I tried to use the from previous code but not works
I made some fix with last version today, see fix bellow with simplifications
from tkinter import *
from PIL import Image, ImageTk
import fitz
root = Tk()
file = "yourfile.pdf"
doc = fitz.open(file)
page = doc.load_page(0) # loads page number 'pno' of the document (0-based)
pix = page.get_pixmap()
mode = "RGBA" if pix.alpha else "RGB"
img = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
frame_image = ImageTk.PhotoImage(img)
label = Label(root, bg='gray')
label.pack(side=LEFT)
label.config(image=frame_image)
label.image = frame_image
root.mainloop()
requirements to use "PyMuPDF-1.21.1"
pip install --upgrade pymupdf
see more: https://pymupdf.readthedocs.io/
Good morning, everyone,
I tried to import image logo.gif but got an error message saying the image does not exit.
Appreciate your help.
Dennis
from PIL import Image, ImageChops
from PIL.GifImagePlugin import getheader, getdata
img = Image.open("logo.gif")
img.show()
from tkinter import *
window = Tk()
imgLbl = Label( window, image = img )
TclError: image "<PIL.GifImagePlugin.GifImageFile image mode=P size=92x95 at 0x8C92B38>" doesn't exist
Please refer to this post Play Animations in GIF with Tkinter
This question seems to be a duplicate.
You'll have to first convert the image to tK compatible image by the function PhotoImage present in ImageTk class.
I'm new in python, I want to load random images from a folder. i wrote this code for loading a specific image.
from Tkinter import *
from PIL import ImageTk, Image
import os
root = Tk()
img = ImageTk.PhotoImage(Image.open("9.jpg"))
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()
Pycharm IDE gives me these error
"cannot import name _imagingtk"
2) errors which IDE pycharm is giving
can anyone help me.