Navakanth
Navakanth

Reputation: 864

Image.open() cannot identify image file in python script file

I am trying to execute this script

from PIL import Image
im = Image.open("image.jpg")
nx, ny = im.size

It is working fine when I run it in python shell

pytesser_v0.0.1]#env python
>>> from PIL import Image
>>> im = Image.open("image.jpg")
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=46x24 at 0x7FA4688F16D0>

but when I put it in a some test.py file and run it like python test.py I am getting this error

File "test1.py", line 17, in <module>
    im = Image.open("image.jpg")
  File "/usr/local/python.2.7.11/lib/python2.7/site-packages/PIL/Image.py", line 2309, in open
    % (filename if filename else fp))
IOError: cannot identify image file 'image.jpg'

please help me with this issue, Thanks

PS: Earlier I installed PIL from Imaging-1.1.7 setup.py, later I installed Pillow, I think the problem was in the mutual presence of the PIL and Pillow library on the machine.

Upvotes: 3

Views: 8097

Answers (3)

Orkhan Mammadov
Orkhan Mammadov

Reputation: 353

Seems like PIL library haven't fixed this bug yet.

Here is my solution: Open image using OpenCV library, then convert it to PIL image

from PIL import Image
import cv2

image_path = 'Folder/My_picture.jpg'

# read image using cv2 as numpy array
cv_img = cv2.imread(image_path) 

# convert the color (necessary)
cv_img = cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB) 

# read as PIL image in RGB
pil_img = Image.fromarray(cv_img).convert('RGBA') 

Then you can operate with it as with a regular PIL image object.

Upvotes: 1

darren
darren

Reputation: 5694

I have the same issue.

This is because the test.py does not have the same pathname. If you are working in the same folder it will work.

However, the solution i found was to put in the full path + file name so that it is unambiguous.

"c:\...fullpath...\image.jpg"

You can do it like this:

from PIL import Image
import os

curDir = os.getcwd()
fileName = "image.jpg"
fn = curDir + "\\" + fileName

print(fn)

image = Image.open(fn)
image.show()

This works. Please let me know if you find better.

Upvotes: 0

Charlton Lane
Charlton Lane

Reputation: 438

Make sure that "image.jpg" is in the same directory as "test1.py".

If it isn't then you could either move it, or put the correct directory inside of Image.open().

Upvotes: 0

Related Questions