69

I am running Python 2.7 in Visual Studio 2013. The code previously worked ok when in Spyder, but when I run:

import numpy as np
import scipy as sp
import math as mt
import matplotlib.pyplot as plt
import Image
import random

# (0, 1) is N
SCALE = 2.2666 # the scale is chosen to be 1 m = 2.266666666 pixels
MIN_LENGTH = 150 # pixels

PROJECT_PATH = 'C:\\cimtrack_v1'
im = Image.open(PROJECT_PATH + '\\ST.jpg')

I end up with the following errors:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\cimtrack_v1\PythonApplication1\dr\trajgen.py", line 19, in <module>
    im = Image.open(PROJECT_PATH + '\\ST.jpg')
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2020, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file

Why is it so and how may I fix it?


As suggested, I have used the Pillow installer to my Python 2.7. But weirdly, I end up with this:

>>> from PIL import Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL


>>> from pil import Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pil

>>> import PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL.Image

>>> import PIL
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL

All fail!

Junuxx
  • 14,011
  • 5
  • 41
  • 71
Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174
  • Does the file exist and is of correct format? – Maciej Gol Oct 07 '13 at 17:26
  • @kroolik Yes, it does exist. I tested its existence by moving it somewhere else, and the error message becomes "No such file". The format is .jpg. Before I have imported it in successfully. – Sibbs Gambling Oct 07 '13 at 17:30
  • 1
    Maybe try with a different image file? Your image could be corrupt. – Tyler Oct 07 '13 at 17:34
  • 2
    Have you got `libjpeg-dev` installed? Or, in other words, did `PIL` print `--- JPEG support available` when installed? – Maciej Gol Oct 07 '13 at 17:35
  • @TylerAndFriends Ive tried, but the same :/ – Sibbs Gambling Oct 07 '13 at 17:38
  • @kroolik do I need to install any extra things?? I thought it comes naturally as in Spyder? – Sibbs Gambling Oct 07 '13 at 17:40
  • 3
    You need to have libraries to handle specific image extensions. If you do `pip install -U PIL`, at the end of the output it should tell you which extensions are available. Also, I suggest uninstalling `PIL` and installing `pillow` instead - it automatically handles linking libraries to specific directories. Other than that, it's a wrapper over regular `PIL`. – Maciej Gol Oct 07 '13 at 17:49
  • @kroolik Thanks for the adive I just installed Pillow. But why: >>> from PIL import Image Traceback (most recent call last): File "", line 1, in ImportError: No module named PIL >>> ? – Sibbs Gambling Oct 07 '13 at 17:59
  • Have you uninstalled `PIL` and installed `pillow`? Also, make sure you have installed it in correct virtualenv. Installing it with `sudo` will _not_ install it in your virtualenv. – Maciej Gol Oct 07 '13 at 18:07
  • @kroolik Yes, unistalled PIL and installed pillow. I am in Windows btw – Sibbs Gambling Oct 08 '13 at 01:32
  • did you try download the images again from scratch? – Charlie Parker Jul 01 '20 at 16:23

20 Answers20

73

I had a same issue.

from PIL import Image

instead of

import Image

fixed the issue

naoko
  • 5,064
  • 4
  • 35
  • 28
  • 2
    Not sure why this was downvoted, but this worked for me too. I almost didn't try it because it was -1. – Leah Sapan Jan 29 '14 at 18:57
  • 28
    Didn't work for me... though my issue is intermittent, so not sure that qualifies... – Deep-B Mar 07 '14 at 19:53
  • 4
    This worked for me when `img2pdf.py` was suddenly unable to open JPEGs any more. **Can anyone explain the reason why this import statement change changes behaviour?** I checked, and the only `Image.py` under `site-packages` is the one in `PIL`. I thought that `from ... import ...` should work identically with `import ...`, other than how it places the resulting object in the global namespace -- in this case, it should be completely identical, no? – Evgeni Sergeev Aug 06 '14 at 06:28
  • 2
    This worked for me too. But like what Evgeni said, can anyone explain why this works? – irenemeanspeace Nov 13 '15 at 10:01
  • 4
    On `PIL/ImageTk` `from PIL import Image` is used. Using `import Image` creates two instances of Image module, and collected plugins for treat images `Image.ID` is duplicated too. One filled with plugins, other empty. Your code uses empty one. More here https://github.com/python-pillow/Pillow/pull/1898 – albfan May 07 '16 at 13:55
  • 1
    This didn't work for me. I was already doing `import PIL.Image as PILI` and I still get the same error. File exists when I did `Path(path).exists()` as that prints true. – Charlie Parker Jul 01 '20 at 16:02
  • This may appear to work, but it is not the correct fix. The file is still being written to or in use by another operation. See the response by me below for correct solution. – panofish Jul 02 '20 at 18:47
14

So after struggling with this issue for quite some time, this is what could help you:

from PIL import Image

instead of

import Image

Also, if your Image file is not loading and you're getting an error "No file or directory" then you should do this:

path=r'C:\ABC\Users\Pictures\image.jpg'

and then open the file

image=Image.open(path)
musicakc
  • 488
  • 1
  • 4
  • 15
  • 2
    I am already doing `import PIL.Image as PILI` and I still get the same error. File exists when I did `Path(path).exists()` as that prints true. I am struggling to understand what you are suggesting us to do. Can you clarify? – Charlie Parker Jul 01 '20 at 16:04
14

In my case.. I already had "from PIL import Image" in my code.

The error occurred for me because the image file was still in use (locked) by a previous operation in my code. I had to add a small delay or attempt to open the file in append mode in a loop, until that did not fail. Once that did not fail, it meant the file was no longer in use and I could continue and let PIL open the file. Here are the functions I used to check if the file is in use and wait for it to be available.

def is_locked(filepath):
    locked = None
    file_object = None
    if os.path.exists(filepath):
        try:
            buffer_size = 8
            # Opening file in append mode and read the first 8 characters.
            file_object = open(filepath, 'a', buffer_size)
            if file_object:
                locked = False
        except IOError as message:
            locked = True
        finally:
            if file_object:
                file_object.close()
    return locked

def wait_for_file(filepath):
    wait_time = 1
    while is_locked(filepath):
        time.sleep(wait_time)
panofish
  • 7,578
  • 13
  • 55
  • 96
  • How did you `open the file in append mode in a loop`? I believe I might be having the same issue you are referring to. – Charlie Parker Jul 01 '20 at 16:08
  • I am skeptical that you managed to fix it the way you say. The code for `.open` has a specific check that throws error if `mode != r`. The doc says: ` :param mode: The mode. If given, this argument must be "r".` – Charlie Parker Jul 01 '20 at 16:11
  • 1
    a similar approach worked for me too, in my case multiple processes tried to access the same image file – yazan sayed Jan 19 '21 at 21:34
  • @CharlieParker Did you try my code? It does work perfectly in my case. – panofish Sep 20 '22 at 18:34
8

first, check your pillow version

python -c 'import PIL; print PIL.PILLOW_VERSION'

I use pip install --upgrade pillow upgrade the version from 2.7 to 2.9(or 3.0) fixed this.

Syscall
  • 19,327
  • 10
  • 37
  • 52
iamsk
  • 346
  • 5
  • 7
5

In my case, the image was corrupted during download (using wget with github url)

  • Try with multiple images from different sources. python

    from PIL import Image Image.open()

rahul4data
  • 261
  • 2
  • 5
4

Often it is because the image file is not closed by last program.

It should be better to use

with Image.open(file_path) as img:
    #do something
True
  • 419
  • 3
  • 7
  • Yes, this was my case. I downloaded and resized list of images in a For loop, however I did not close each image after parsing it. In the end I did it like: image = Image.open(my_file) ...do stuff... Image.close() – VA13 Jun 26 '22 at 19:24
2

In my case, it was because the images I used were stored on a Mac, which generates many hidden files like .image_file.png, so they turned out to not even be the actual images I needed and I could safely ignore the warning or delete the hidden files. It was just an oversight in my case.

pinkie pAI
  • 21
  • 6
2

Just a note for people having the same problem as me. I've been using OpenCV/cv2 to export numpy arrays into Tiffs but I had problems with opening these Tiffs with PIL Open Image and had the same error as in the title. The problem turned out to be that PIL Open Image could not open Tiffs which was created by exporting numpy float64 arrays. When I changed it to float32, PIL could open the Tiff again.

Johan R
  • 137
  • 1
  • 1
  • 7
1

If you are using Anaconda on windows then you can open Anaconda Navigator app and go to Environment section and search for pillow in installed libraries and mark it for upgrade to latest version by right clicking on the checkbox.

Screenshot for reference:enter image description here

This has fixed the following error:

PermissionError: [WinError 5] Access is denied: 'e:\\work\\anaconda\\lib\\site-packages\\pil\\_imaging.cp36-win_amd64.pyd'
ThinkFloyd
  • 4,981
  • 6
  • 36
  • 56
1

Seems like a Permissions Issue. I was facing the same error. But when I ran it from the root account, it worked. So either give the read permission to the file using chmod (in linux) or run your script after logging in as a root user.

Anoop Sharma
  • 87
  • 1
  • 13
1

In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.

David K.
  • 76
  • 6
1

This error can also occur when trying to open a multi-band image with PIL. It seems to do fine with 4 bands (probably because it assumes an alpha channel) but anything more than that and this error pops out. In my case, I fixed it by using tifffile.imread instead.

plp
  • 11
  • 1
1

I had the same issue. In my case, the image file size was 0(zero). Check the file size before opening the image.

fsize = os.path.getsize(fname_image)
if fsize > 0 :       
    img = Image.open(fname_image)
    #do something
WangSung
  • 259
  • 2
  • 5
0

In my case the image file had just been written to and needed to be flushed before opening, like so:

img_file.flush() 
img = Image.open(img_file.name))
jchmyz
  • 17
  • 2
  • Are you sure this is correct? `.open()` always opens on read mode. `:param mode: The mode. If given, this argument must be "r".` – Charlie Parker Jul 01 '20 at 16:16
0

For anyone who make it in bigger scale, you might have also check how many file descriptors you have. It will throw this error if you ran out at bad moment.

Deil
  • 106
  • 5
0

For whoever reaches here with the error colab PIL UnidentifiedImageError: cannot identify image file in Google Colab, with a new PIL versions, and none of the previous solutions works for him:

Simply restart the environment, your installed PIL version is probably outdated.

Jjang
  • 11,250
  • 11
  • 51
  • 87
0

For me it was fixed by downloading the image data set I was using again (in fact I forwarded the copy I had locally using vs-code's SFTP). Here is the jupyter notebook I used (in vscode) with it's output:

from pathlib import Path

import PIL
import PIL.Image as PILI
#from PIL import Image

print(PIL.__version__)

img_path = Path('PATH_UR_DATASET/miniImagenet/train/n03998194/n0399819400000585.jpg')
print(img_path.exists())
img = PILI.open(img_path).convert('RGB')

print(img)

output:

7.0.0
True
<PIL.Image.Image image mode=RGB size=158x160 at 0x7F4AD0A1E050>

note that open always opens in r mode and even has a check to throw an error if that mode is changed.

Charlie Parker
  • 5,884
  • 57
  • 198
  • 323
0

In my case the error was caused by alpha channels in a TIFF file.

rhy
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 28 '21 at 20:46
  • This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://stackoverflow.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://stackoverflow.com/help/whats-reputation), you can also [add a bounty](https://stackoverflow.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/30692106) – Sercan Dec 29 '21 at 10:52
0

I'll add my particular case.

I was processing images uploaded through multipart/form-data using AWS API Gateway. When I was uploading my images, that had not been giving this error locally, I was observing UnidentifiedImageError exception thrown by PIL when loading uploaded image. In order to fix this error I had to add multipart/form-data within settings of service.

Greg0ry
  • 931
  • 8
  • 25
0

Im working in Google colab, and in had same problem.

UnidentifiedImageError: cannot identify image file '/content/drive/MyDrive/Python/test.jpg'

The problem is that the default version of PIL (as today 24/11/2022) in colab is 9.3.0; but when you do !pip install pillow the version that is updated is 7.1.2.

So, what I did was open a new colab notebook and NOT pip pillow. It worked.

Azhar Khan
  • 3,829
  • 11
  • 26
  • 32