Python: Building an Image grid - python

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.

Related

Unable to display images in a stream in tkinter instead it prints all images on same page

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

Tkinter:Cant place image which imported from Pixmap inside text widget using button

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/

How to import and display list of images in GUI using Tkinter?

from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
# Function to display image
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
# gta_images = []
os.chdir("gta")
for file in glob.glob("*.jpg"):
# gta_images.append(str(file))
displayImg(file)
print(file)
# print(gta_images)
root.mainloop()
I am trying to load images from a folder called "gta" and then display those game logos on my app. Program has no error but I think its a logical error. I am new to Python I don't know maybe there is some scoping logic problem in my displayImg funcion.
Note: When a PhotoImage object is garbage-collected by Python (e.g.
when you return from a function which stored an image in a local
variable), the image is cleared even if it’s being displayed by a
Tkinter widget.
For more.
from tkinter import *
from PIL import Image, ImageTk
import glob, os
root = Tk()
root.geometry("800x600")
photos = []
def displayImg(img):
image = Image.open(img)
photo = ImageTk.PhotoImage(image)
photos.append(photo)#keep references!
newPhoto_label = Label(image=photo)
newPhoto_label.pack()
for file in glob.glob("*.jpg"):
displayImg(file)
print(file)
root.mainloop()
Not sure if it will work but try using the path of the gta folder you are getting the images from, instead of its name simply - replace the name with the path.

How can open an image by asking the path of it using pillow (python)?

I am trying to pass the path of an image and then opening it but i get this error for this line image = Image.open(path):
AttributeError: type object 'Image' has no attribute 'open'
from PIL import Image
from tkinter import *
class Menu:
def __init__(self,root):
self.root = root
self.root.title("Image")
self.image_entry = Entry(root)
self.image_entry.grid(row=0,column=1)
image_label = Label(root,text = "Enter the path of the image").grid(row=0)
images = Button(root,text="Show",command=lambda:[self.show(self.image_entry)]).grid(row=1,column=1)
root.mainloop()
def show(self,image_entry):
path=image_entry.get()
image = Image.open(path)
image.show()
The variable Image imported from PIL is being overwritten by the variable Image imported from Tkinter.
Possible solutions, in descending order of best-practice-ness:
Don't import things from tkinter using import *. Try importing only the names you need, for example from tkinter import Entry, Label, Button, Tk.
Choose an alias for PIL's Image that doesn't conflict with Tkinter's Image. For example, from PIL import Image as PILImage.
Switch the order of your imports so PIL's Image overwrites Tkinter's Image, instead of the other way around.

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

Categories

Resources