I'm converting an RGB image to HSV, and trying to display the same in a Label. But I'm getting error.
My code snippet is:
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
imgthresh=Image.open(imgthresh)
re_hsv=imhsv.resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(windo, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
And my error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\App\appdata\canopy-1.0.3.1262.win-x86\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "E:\python\track\guinew.py", line 215, in hsv_img
imhsv=Image.open(imgthresh)
File "C:\Users\Balu\AppData\Local\Enthought\Canopy32\System\lib\site-packages\PIL\Image.py", line 1956, in open
prefix = fp.read(16)
AttributeError: 'numpy.ndarray' object has no attribute 'read'
So how to display the HSV image, is there any other way then what i have tried? Any suggestions are welcome!
Thanks in advance!
The error is thrown when you call Image.open(imgthresh), because Image.open expects a file-like object, but imgthresh is a Numpy array.
Try removing that line altogether.
EDIT: Here's a complete version that works (on my machine):
from PIL import Image, ImageTk
from Tkinter import Tk, Label, SOLID
import cv2
import numpy as np
img = np.array(Image.open('some-file.png'))
window = Tk()
def hsv_img():
img1=cv2.medianBlur(img,3)
imghsv = cv2.cvtColor(img1,cv2.COLOR_BGR2HSV)
lw_range=np.array([160,170,50])
up_range=np.array([179,250,220])
imgthresh1=cv2.inRange(imghsv,lw_range,up_range)
re_hsv=Image.fromarray(imghsv).resize((360,360),Image.ANTIALIAS)
imhsv1=ImageTk.PhotoImage(re_hsv)
lb_hsv = Label(window, image = imhsv1,relief=SOLID)
lb_hsv.image=imhsv1
lb_hsv.pack()
lb_hsv.place(x=230,y=180)
hsv_img()
window.mainloop()
I had to rename some things, as well as add a call to Image.fromarray when you resize to 360x360.
It seems like most of the confusion stems from different numpy/PIL/OpenCV/Tkinter image formats. You might find this conversion guide useful, though it's slightly out of date.
Related
I'm trying to add an image to Customtkinter Buttom, but an error occurs
import sqlite3
from tkinter import \*
import customtkinter
from tkinter import ttk
from PIL import Image, ImageTk
customtkinter.set_appearance_mode('dark')
customtkinter.set_default_color_theme('blue')
\#Create a Ctk instance(app)
main = customtkinter.CTk()
main.geometry("400x240")
main.resizable(width=False, height=False)
\#Username Frame
username_tittle = customtkinter.CTkLabel(master=main, text='Username:').place(relx=0.2, rely= 0.3)
username_box = customtkinter.CTkEntry(master=main, width=150)
username_box.place(relx=0.43, rely=0.3)
python_image = ImageTk.PhotoImage(Image.open('user_icon.png'), Image.ANTIALIAS, )
but = customtkinter.CTkButton(master=main, image=python_image).pack()
this code generate the following error:
c:\\Users\\claud\\OneDrive\\Documentos\\meuusprojetos\\Login\\main.py:19: DeprecationWarning: ANTIALIAS is deprecated and will be removed in Pillow 10 (2023-07-01). Use LANCZOS or Resampling.LANCZOS instead.
python_image = ImageTk.PhotoImage(Image.open('user_icon.png'), Image.ANTIALIAS, )
CTkButton Warning: Given image is not CTkImage but \<class 'PIL.ImageTk.PhotoImage'\>. Image can not be scaled on HighDPI displays, use CTkImage instead.
Traceback (most recent call last):
File "c:\\Users\\claud\\OneDrive\\Documentos\\meuusprojetos\\Login\\main.py", line 20, in \<module\>
but = customtkinter.CTkButton(master=main, image=python_image).pack()
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 106, in __init__
self.\_draw()
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 243, in \_draw
self.\_update_image() # set image
File "C:\\Users\\claud\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages\\customtkinter\\windows\\widgets\\ctk_button.py", line 154, in \_update_image
self.\_image_label.configure(image=self.\_image.create_scaled_photo_image(self.\_get_widget_scaling(),
AttributeError: 'PhotoImage' object has no attribute 'create_scaled_photo_image'
Can anybody help me?
It looks like you are encountering an error when trying to add an image to a CTkButton widget in the customtkinter module.
The error message mentions that the given image is not a CTkImage, but a PIL.ImageTk.PhotoImage.
To fix this issue, you can try the following:
Use the CTkImage class to create an image object instead of the PIL.ImageTk.PhotoImage class. You can do this by using the CTkImage.open() method to open the image file, like this:
python_image = customtkinter.CTkImage.open('user_icon.png')
I hope this suggestion will help you.
Latest version of customtkinter accepts CTkImage only for image option of its widgets:
...
python_image = customtkinter.CTkImage(Image.open("user_icon.png"))
customtkinter.CTkButton(master=main, image=python_image).pack()
...
from PIL import Image
img = Image.open("demo.png")
New_img=img.thumbnail((90,90), Image.ANTIALIAS)
New_img.save("deTT.png")
Traceback (most recent call last):
File "/Users/sahejmundi/Desktop/projects/LiveProjects/XML_project/Task_4/img_re.py", line 15, in
AttributeError: 'NoneType' object has no attribute 'save'
The thumbnail() method reduces the size of the image passed to it "in situ" rather than returning a new, reduced image. So you actually need:
from PIL import Image
img = Image.open("demo.png")
# Reduce to thumbnail in place
img.thumbnail((90,90), Image.ANTIALIAS)
img.save("deTT.png")
This is very vague, but hope this helps
There seams to be an error when you defines your New_img function. If you can check the docs again and try to fix it
Most likely, you missed a parenthesis somewhere ()
Something like this should work
my_size = (90, 90)
image.thumbnail(my_size, Image.ANTIALIAS)
image.save(path_to_image, 'image/png', optimize=True)
I'm having an issue with my code in production. It works locally- I'm not sure how to troubleshoot the issue.
From what I can tell, PIL is the same version in both environments. The Image module works as expected both locally and in production- ImageEnhancement is causing issues.
Locally, the following code works as expected.
from PIL import Image
from PIL import ImageEnhancement
image = Image.open("a.jpg")
newImage = ImageEnhance.Contrast(image)
newImage.enhance(1.5)
newImage.save("newImage.jpg")
However when trying this in my production environment, I get an error:
Traceback (most recent call last):
File "analyse.py", line 95, in <module>
processedImage = ImageEnhance.Sharpness(processedImage)
File "/usr/lib/python2.7/dist-packages/PIL/ImageEnhance.py", line 97, in __init__
self.degenerate = image.filter(ImageFilter.SMOOTH)
AttributeError: 'Contrast' object has no attribute 'filter'
Class Contrast doesn't create image but object which can change image. And enhance() creates new image.
from PIL import Image
from PIL import ImageEnhance
image = Image.open("a.jpg")
enhancer = ImageEnhance.Contrast(image)
new_image = enhancer.enhance(1.5)
new_image.save("newImage.jpg")
I know that this question has already been asked several times, but I still couldn't figure out the answer to my problem. I keep getting the same error and don't know how to solve it.
This is my code:
from Tkinter import *
from PIL import Image, ImageTk
import os
window = Tk()
i = Image.open(pathToImage)
if os.path.isfile(pathToImage):
print 'image exists'
else:
print 'image does not exits'
label=Label(window, image=i)
label.pack()
window.mainloop()
It says that the image exists at the indicated path, but I keep getting this error message:
Traceback (most recent call last):
File "ImageTest.py", line 31, in <module>
label=Label(window, image=i)
File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2597, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Users\username\Anaconda2\lib\lib-tk\Tkinter.py", line 2096, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=640x480 at 0x36DF278>" doesn't exist
I could not figure out how to solve this problem. Any help would be appreciated!
You should use PhotoImage instance as image value. Also, you need to keep the reference of your image.
im = Image.open(pathToImage)
ph = ImageTk.PhotoImage(im)
label = Label(window, image=ph)
label.image=ph #need to keep the reference of your image to avoid garbage collection
A quick hacky fix is to provide the PhotoImage with the correct master:
i = ImageTk.PhotoImage(pathToImage, master=window)
It seems to be an Anaconda - Spyder - Iphyton problem.
Solution is here:
_tkinter.TclError: image "pyimage" doesn't exist
I have tried to make the following script running correctly:
def tftest():
from PIL import Image
picture = "ttamet3dim.png"
impict = Image.open(picture)
transf = impict.Image.transform((78,78), Image.QUAD, (78,41,178,27,183,91,81,91), Image.BICUBIC)
imt = Image.open(transf)
imt.show()
But I get the following error:
File "C:\Python34\tftest.py", line 5, in tftest
transf = impict.Image.transform(...)
File "C:\Python34\lib\site-packages\pillow-3.0.0-py3.4-win32.egg\PIL\Image.py", line 626, in __getattr__
AttributeError: Image
It's the first time that I use "transform". I wanted to have a look to the "transform" script to see if I could find out what's wrong but my Pillow is a .egg so I didn't find how to access to the code. Do you know why I get this error and how to fix it?
Thank you, best regards
transform is a method for Image objects, and returns a new image:
from PIL import Image
def tftest():
picture = "ttamet3dim.png"
impict = Image.open(picture)
imt = impict.transform((78,78), Image.QUAD, (78,41,178,27,183,91,81,91), Image.BICUBIC)
imt.show()
Try to change transf = impict.Image.transform to transf = impict.transform
You've assigned the Image to the impict variable here:
impict = Image.open(picture)
you should reference this variable, that's the opened image, with the transform:
impict.transform
instead of what you're currently doing (basically Image.open(picture).Image.transform).