Reading an image in python - python

I am trying to import an image in python to later use it in a plot. I am using the following code:
import matplotlib.image as image
im = image.imread('image.png')
And I am having the following error:
SystemError: built-in method fileno of _io.FileIO object at 0x00000295A8277750 returned a result with an error set
The image exist in the current folder. I tried also the following with the same result:
from matplotlib._png import read_png
png_file = open('image.png')
Image = read_png(png_file)
Error output:
SystemError: built-in method fileno of _io.FileIO object at 0x00000295A8277828 returned a result with an error set
Why is this happening?

maybe your directory is wrong.
I tried this code and worked.
import matplotlib.image as image
imgg = image.imread('/home/ss/Desktop/1.jpg')
plt.imshow(imgg)
plt.show()

Related

AttributeError: 'dict' object has no attribute 'mode' when using Tsseract OCR in Python

I intended to import an image file from my computer and then use Tesseract OCR to recignize the characters in the image.I used Google Colab to run the code.
The code I wrote
!apt install tesseract-ocr libtesseract-dev tesseract-ocr-jpn
!pip install pyocr
from PIL import Image
import pyocr
import cv2
from google.colab.patches import cv2_imshow
from google.colab import files
uploaded=files.upload()
tools=pyocr.get_available_tools()
print(tools)
tool=tools[0]
print(tool.get_name())
txt1 = tool.image_to_string(
uploaded,
lang='jpn+eng',
builder=pyocr.builders.TextBuilder(tesseract_layout=6)
)
After running the code above, the error messageAttributeError: 'dict' object has no attribute 'mode' appeared.
Below is all of the error message shown by colab
AttributeError Traceback (most recent call last)
<ipython-input-38-2ad0a8585335> in <module>
2 uploaded,
3 lang='jpn+eng',
----> 4 builder=pyocr.builders.TextBuilder(tesseract_layout=6)
5 )
6 help(dict.items)
/usr/local/lib/python3.7/dist-packages/pyocr/tesseract.py in image_to_string(image, lang, builder)
362 builder = builders.TextBuilder()
363 with tempfile.TemporaryDirectory() as tmpdir:
--> 364 if image.mode != "RGB":
365 image = image.convert("RGB")
366 image.save(os.path.join(tmpdir, "input.bmp"))
AttributeError: 'dict' object has no attribute 'mode'
I have searched for this and although there are same cases on the Internet with similar error messages'dict' object has no attribute '~', I couldn't find any case that was regarding the attribute "mode."
Could you please tell me why this error happened?
I appreciate it if you could leave any comments or answers.
files.upload() returns a dict in the format of {filename : raw_data}, so you will want to pass only the values of the dict in the image parameter of image_to_string, instead of the entire dict.
If you know you will only ever be uploading one image file, then you could do something like:
img = list(uploaded.values())[0] # This is a bit of a hack
txt1 = tool.image_to_string(
img,
lang='jpn+eng',
builder=pyocr.builders.TextBuilder(tesseract_layout=6)
)
A better solution would be to loop over all of your uploaded files, even if there is only one:
!apt install tesseract-ocr libtesseract-dev tesseract-ocr-jpn
!pip install pyocr
from PIL import Image
import pyocr
import cv2
from google.colab.patches import cv2_imshow
from google.colab import files
uploaded=files.upload()
tools=pyocr.get_available_tools()
print(tools)
tool=tools[0]
print(tool.get_name())
for fn, filedata in uploaded.items():
print(f"Processing file {fn}...")
process_image(filedata)
def process_image(image):
txt1 = tool.image_to_string(
image,
lang='jpn+eng',
builder=pyocr.builders.TextBuilder(tesseract_layout=6)
)
# Do whatever you want to do with txt1 here. or return it and handle in the loop above

How do I resolve 'Contract' object has no attribute 'filter', in PIL ImageEnhance module?

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

When using a PIL image object with reportlab drawImage gives

I am trying to insert a PIL image object into a pdf using reportlab drawImage method.
im=Image.open('back_ground.png')
side_im=im.crop((2,2,277,819))
c=canvas.Canvas('report.pdf')
c.drawImage(side_im,200,700)
And I get this error
AttributeError: 'Image' object has no attribute 'rfind'
Just for an update since StringIO has been deprecated in Python3. import io instead of StringIO and use io.BytesIO()
import io
from reportlab.lib.utils import ImageReader
im=Image.open('back_ground.png')
side_im=im.crop((2,2,277,819))
c=canvas.Canvas('report.pdf')
#c.drawImage(side_im,200,700)
side_im_data = io.BytesIO()
side_im.save(side_im_data, format='png')
side_im_data.seek(0)
side_out = ImageReader(side_im_data)
c.drawImage(side_out,200,700)
This worked for me:
import StringIO
from reportlab.lib.utils import ImageReader
im=Image.open('back_ground.png')
side_im=im.crop((2,2,277,819))
c=canvas.Canvas('report.pdf')
#c.drawImage(side_im,200,700)
side_im_data = StringIO.StringIO()
side_im.save(side_im_data, format='png')
side_im_data.seek(0)
side_out = ImageReader(side_im_data)
c.drawImage(side_out,200,700)
I had this problem for around 3 months. After upgrading python to 3.8, reportlab to 3.5.42, Pillow to 7.0.0, it started working again on amazon ec2 instance. previously it was crashing the Django gunicorn server causing a 502 error.

Using Python 3.4 and Pillow and the method transform: AttributeError: Image

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

how to display HSV image - tkinter, python 2.7

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.

Categories