ImageTk.PhotoImage not displaying image correctly - python

I want to show a .tif file in a tkinter gui, but I have been having trouble getting the images to load properly. I was able to view the image correctly using Image.open with mode='r', but then when I call ImageTk.PhotoImage it displays a blank white canvas. Here is the code:
def func(image_paths):
root = Tk()
im = Image.open(image_paths[0], mode='r')
im.show() # shows image correctly
im = ImageTk.PhotoImage(im)
im_label = Label(image=im)
# im_label = Label(image=ImageTk.PhotoImage(Image.open(image_paths[0], mode='r'))) # This doesn't work either
im_label.grid(row=0, column=0, columnspan=3)
root.mainloop()
Any help is much appreciated!

So, what ended up working was the solution in this video: https://www.youtube.com/watch?v=6l6HDQyWdH0
The lines of code that got it to work was:
curr = Image.open(image_paths[0], mode='r')
curr = Image.fromarray(np.uint8(cm.jet(NormalizeData(np.array(curr).astype(np.float64)))*255))
curr = ImageTk.PhotoImage(curr)

Related

How to display an image in Python used by Google face detection Vision API

I am using a Google API (called Vision API) to detect the faces and the emotions in a given image just like documented in cloud.google.com. Everything works well and I get the desired results, but only in the terminal (no GUI displayed) :
I want to display the image using a GUI in Python. I am still a beginner in Python and the only way I know to display anything in a canvas is using grid(). I have tried it but it doesn't work because I don't know what variable should be used with grid().
import tkinter as tk
from PIL import Image, ImageTk
from tkinter.filedialog import askopenfile
import io
import os
from google.cloud import vision
root = tk.Tk()
canvas = tk.Canvas(root, width=600, height=300)
canvas.grid(columnspan=3, rowspan=3)
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'crack-producer-313920-5e16fbab8c24.json'
client = vision.ImageAnnotatorClient()
file_name = os.path.abspath('picture.jpg')
with io.open(file_name, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.face_detection(image=image)
faces = response.face_annotations
# Names of likelihood from google.cloud.vision.enums
likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE',
'LIKELY', 'VERY_LIKELY')
print('Faces:')
for face in faces:
print('anger: {}'.format(likelihood_name[face.anger_likelihood]))
print('joy: {}'.format(likelihood_name[face.joy_likelihood]))
print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))
vertices = (['({},{})'.format(vertex.x, vertex.y)
for vertex in face.bounding_poly.vertices])
print('face bounds: {}'.format(','.join(vertices)))
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
root.mainloop()
I hope my explanation is clear. Any helped is highly appreciated.

Image not displayed on python

i am a beginner of python programming.i will place the images on the frame. but image not not diaplayed error shown below.
Traceback (most recent call last):
File "C:/Users/kobinath/PycharmProjects/pythonProject4/jj.py", line 5, in <module>
img = PhotoImage(file="pic.jpg")
File "C:\Users\kobinath\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 4061, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Users\kobinath\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 4006, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "pic.jpg"
what i tried so far i attached below.
from tkinter import *
root = Tk()
canvas = Canvas(root, width = 600, height = 600)
canvas.pack()
img = PhotoImage(file="pic.jpg")
canvas.create_image(20,20, anchor=NW, image=img)
root.mainloop()
I actually think its not possible to use jpg with PhotoImage directly, instead you might want to use PIL and heres how,
pip install PIL
After this, just say
from tkinter import *
from PIL import Image,ImageTk
root = Tk()
canvas = Canvas(root, width = 600, height = 600)
canvas.pack()
img_file = Image.open("sad songs.jpg")
img_file = img_file.resize((150,150)) #(width,height)
img = ImageTk.PhotoImage(img_file)
canvas.create_image(20,20, anchor=NW, image=img)
root.mainloop()
Here is a site to convert jpg to gif
Do let me know, if any errors or doubts
Cheers
It may be a result of a new bug thats been going on with tkinter images where we have to keep a reference of the image to make sure it will work I hope this will fix it.
canvas.img = img
Also as #Cool Cloud has also pointed out it can also be the problem where it does not work with jpg files sometimes but for me sometimes it does too, so if its not working with you, you can just convert it into a png or gif(I would prefer png based on what has worked with me when I ran into these problems).
Also instead of the conversion you can try the PIL library it can be installed using
pip install PIL
And then you can use a class called PhotoImage(yup it has the same name as the tkinter class) to do the image loading and stuff, which is under the module ImageTk which can be used to deal with tkinter images.
Also you can pass the image object into this class as a parameter, you can create an Image object like so-:
img_obj = Image.open('annoying_image.jpg') # uses the Image module from PIL use import PIL.Image
Like so
img = PIL.ImageTk.PhotoImage(img_obj) # uses the Image module from PIL use import PIL.ImageTk
Also If you want to know more about PIL, its just basically a Image Processing Library of python often called as pillow also.
IMPORT STATEMENTS(JUST IN CASE ITS NOT CLEAR)
from PIL import Image, ImageTk

Error while converting PIL image to Tkinter image

I'm trying to rotate an image using Pillow:
img = Image.open("./assets/aircraftCarrier/aircraftCarrier0.gif")
img = img.rotate(270)
This rotates the image but when I try to save it Pillow doesn't seem to recognise the file type, even if I put the format type when saving it:
img.save("./tempData/img", "GIF")
It comes up with a file with a blank extension
Now this doesn't really matter as long as tkinter can recognise it with PhotoImage, but that doesn't seem to work either:
img = PhotoImage(img)
label = Label(root, image=img)
label.pack()
I get this error message:
TypeError: __str__ returned non-string (type Image)
I'm not really sure what I've done wrong or if I need to do more processing with Pillow.
Help would be greatly appreciated,
Josh
Full code:
import tkinter as tk
from tkinter import *
import tkinter
from PIL import Image
root = tk.Tk()
root.title("Test")
img = Image.open("./assets/aircraftCarrier/aircraftCarrier0.gif")
img = img.rotate(270)
img.save("./tempData/img", "GIF")
img = PhotoImage(img)
label = Label(root, image=img)
label.pack()
root.mainloop()
Full error message:
Traceback (most recent call last):
File "C:\Users\Joshlucpoll\Documents\Battleships\test.py", line 19, in <module>
label = Label(root, image=img)
File "C:\Users\Joshlucpoll\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2766, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\Joshlucpoll\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 2299, in __init__
(widgetName, self._w) + extra + self._options(cnf))
TypeError: __str__ returned non-string (type Image)
Ok, looking into the effbot documentation for PhotoImage there are these lines of code:
from PIL import Image, ImageTk
image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
and it states:
If you need to work with other file formats, the Python Imaging
Library (PIL) contains classes that lets you load images in over 30
formats, and convert them to Tkinter-compatible image objects
So it seems you need to add ImageTk before PhotoImage when converting from PIL to Tkinter.
Eg:
img = ImageTk.PhotoImage(img)
Adding this to my program does result in the rotated image to show perfectly.

How to save an image as a variable?

Now, I have a python game that has sprites, and it obtains the images from files in its directory. I want to make it such that I do not even need the files. Somehow, to pre-store the image in a variable so that i can call it from within the program, without the help of the additional .gif files
The actual way i am using the image is
image = PIL.Image.open('image.gif')
So it would be helpful if you could be precise about how to replace this code
Continuing #eatmeimadanish's thoughts, you can do it manually:
import base64
with open('image.gif', 'rb') as imagefile:
base64string = base64.b64encode(imagefile.read()).decode('ascii')
print(base64string) # print base64string to console
# Will look something like:
# iVBORw0KGgoAAAANS ... qQMAAAAASUVORK5CYII=
# or save it to a file
with open('testfile.txt', 'w') as outputfile:
outputfile.write(base64string)
# Then make a simple test program:
from tkinter import *
root = Tk()
# Paste the ascii representation into the program
photo = 'iVBORw0KGgoAAAANS ... qQMAAAAASUVORK5CYII='
img = PhotoImage(data=photo)
label = Label(root, image=img).pack()
This is with tkinter PhotoImage though, but I'm sure you can figure out how to make it work with PIL.
Here is how you can open it using PIL. You need a bytes representation of it, then PIL can open a file like object of it.
import base64
from PIL import Image
import io
with open("picture.png", "rb") as file:
img = base64.b64encode(file.read())
img = Image.open(io.BytesIO(img))
img.show()

No file or Directory exist, but it does

I am trying to use tkinter module to open a window to show a picture and was previously having trouble with: _tkinter.TclError: couldn't recognize data in image
I have since used the following this question to restructured my code to the following:
How do I insert a JPEG image into a python Tkinter window?
I have made a few changes to the code as I am using python 3.
When I have tried to execute the code: I get an error saying no file or directory exist. However i have used the following code to check:
python open() method IOError: [Errno 2] No such file or directory:
Below are the result of checking the files:
>>> os.listdir()
['comments.py', 'Conan.txt', 'conditions.py', 'dateandtime.py', 'desktop.ini', 'dictionaries.py', 'exceptions.py', 'forging_functions.py', 'formatting.py', 'graphics.py', 'Hello.py', 'leapdays.py', 'logging.py', 'loop.py', 'modules.py', 'months.py', 'numbers.py.py', 'Opening_files.py', 'Picture.jpg', 'print_hello.py.py', 'tkintercode1.py', 'tkintercode2.py', 'user_input.py', 'Writing_file.py', '__pycache__']
>>> os.getcwd()
'C:\\Users\\Draco\\OneDrive\\Documents\\Programming'
>>> os.chdir(r'C:\\Users\\Draco\\OneDrive\\Documents\\Programming')
>>> open('Picture.jpg')
<_io.TextIOWrapper name='Picture.jpg' mode='r' encoding='cp1252'>
Below is the code I am working with:
import tkinter as tk
from tkinter import *
window = tk.Tk()
window.title("Random Image")
window.geometry("300x300")
window.configure(background='grey')
path = "C:\Draco\OneDrive\Documents\Programming\Picture.jpg"
img = tkinter.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
window.mainloop()
Many thanks for any help
"C:\Draco\OneDrive\Documents\Programming\Picture.jpg" try path ="C:\\Draco\\OneDrive\\Documents\\Programming\\Picture.jpg" - double slash
EDIT
You have diff in paths. Users\Draco but in code just Draco

Categories