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!
I had a same issue.
from PIL import Image
instead of
import Image
fixed the issue
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)
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)
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.
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()
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
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.
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.
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:
This has fixed the following error:
PermissionError: [WinError 5] Access is denied: 'e:\\work\\anaconda\\lib\\site-packages\\pil\\_imaging.cp36-win_amd64.pyd'
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.
In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.
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.
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
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))
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.
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.
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.
In my case the error was caused by alpha channels in a TIFF file.
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.
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.
Related
I am trying to open an iPhone image in a Jupyter notebook. This is the location of my image on my hard drive: /Users/admin/work/img_2581.jpg; this is the location of my Jupyter notebook: /Users/admin/work/Untitled.ipynb. However, I am unable to load the image onto the Jupyter notebook.
Image Path: path = '/Users/admin/work/img_2581.jpg'
Notebook location: /Users/admin/work/Untitled.ipynb
I first tried using OpenCV to open the image on the Jupyter notebook. Here's what I did:
OpenCV image read: img = cv2.imread(path)
I tried to print the shape of the image: print(img.shape). However, I received the following error:
AttributeError: 'NoneType' object has no attribute 'shape'
To check for the correct path of the image, I used a simple Python open() statement:
f = open("../work/img_2581.jpg", "r")
print(f)
Output: <_io.TextIOWrapper name='../work/img_2581.jpg' mode='r' encoding='UTF-8'>
Seeing that OpenCV did not work, I tried using Pillow:
from PIL import Image
img = Image.open(path)
The following exception occurred when I tried Pillow:
---------------------------------------------------------------------------
UnidentifiedImageError Traceback (most recent call last)
Input In [14], in <cell line: 3>()
1 from PIL import Image
----> 3 img = Image.open(path)
File ~/opt/anaconda3/lib/python3.9/site-packages/PIL/Image.py:3283, in open(fp, mode, formats)
3281 warnings.warn(message)
3282 msg = "cannot identify image file %r" % (filename if filename else fp)
-> 3283 raise UnidentifiedImageError(msg)
UnidentifiedImageError: cannot identify image file '/Users/admin/work/img_2581.jpg'
I saw on this website that a possible problem was that the image has been corrupted. However, I am able to open it without any issues.
My questions are as follows:
(1) In OpenCV, why is img taking on the value of None when the image I am importing exists?
(2) What is causing UnidentifiedImageError in Pillow?
(3) How can I fix these issues?
There seem to be two possibilities:
either OpenCV/PIL cannot find the image, or
they can find it but cannot read it.
I'll look at each possibility in a separate section.
In case OpenCV/PIL cannot find your image...
The simplest thing to do is work out what directory your Jupyter notebook is running in, so use:
!pwd
Then you can work out the relative path to your image - that is a path that does NOT start with a slash.
So, if your notebook is running in /Users/admin, you will need to open work/img_2581.jpg without a leading slash.
If your notebook is running in /Users/admin/work, you will need to open img_2581.jpg without a leading slash.
If your notebook is running in /Users/admin/work/someMadDirectory, you will need to open ../img_2581.jpg without a leading slash because .. means "one level higher".
In case OpenCV/PIL can find your image, but cannot read it...
It is possible that your image is either not a JPEG at all, or is a JPEG with unusual characteristics (such as being 12-bit instead of 8-bit) or is say JPEG2000.
The simplest way to test if it is a JPEG on Linux/macOS without installing any special software is with:
file img_2581.jpg # or "!file img_2581.jpg" inside Jupyter
If you don't have file available, exiftool is an excellent way to examine images, so I would suggest:
exiftool img_2581.jpg # or "!exiftool img_2581.jpg" inside Jupyter
If you have neither file nor exiftool, you can upload your image to https://hexed.it and copy the first few lines and paste them into your question so we can check them.
I'm trying to use the python image library to import an image. I keep getting an error that says the file or directory doesn't exist when I run this code:
from PIL import Image
img = Image.open("Users/tylercordeiro/hello/sunrisesunsettime.jpeg")
Am I doing anything wrong?
Is there a specific way that I need to put in the name of my file/directory?
Try with an absolute path. I have added a / or slash at the beginning of the file name.
from PIL import Image
im = Image.open("/Users/tylercordeiro/hello/sunrisesunsettime.jpeg")
im
I'm experimenting a little bit working with images in Python for a project I'm working on.
This is the first time ever for me programming in Python and I haven't found a tutorial that deals with the issues I'm facing.
I'm experimenting with different image decompositions, and I want to define some variable A as a set image from a specified folder. Basically I'm looking for Python's analog of Matlab's imread.
After googling for a bit, I found many solutions but none seem to work for me for some reason.
For example even this simple code
import numpy as np
import cv2
# Load an color image in grayscale
img = cv2.imread('messi5.jpg',0)
which is supposed to work (taken from http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_image_display/py_image_display.html) yields the error "No module named cv2".
Why does this happen? How can I read an image?
Another thing I tried is
import numpy as np
import skimage.io as io
A=io.imread('C:\Users\Oria\Desktop\test.jpg')
io.imshow(A)
which yields the error "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape"
All I want to do is be able to read an image from a specified folder, shouldn't be hard...Should also be noted that the database I work with is ppm files. So I want to read and show ppm images.
Edit: My enviornment is Pyzo. If it matters for anything.
Edit2: Changing the back slashes into forward slashes changes the error to
Traceback (most recent call last):
File "<tmp 1>", line 3, in <module>
A=io.imread('C:/Users/Oria/Desktop/test.jpg')
File "F:\pyzo2015a\lib\site-packages\skimage\io\_io.py", line 97, in imread
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
File "F:\pyzo2015a\lib\site-packages\skimage\io\manage_plugins.py", line 209, in call_plugin
return func(*args, **kwargs)
File "F:\pyzo2015a\lib\site-packages\matplotlib\pyplot.py", line 2215, in imread
return _imread(*args, **kwargs)
File "F:\pyzo2015a\lib\site-packages\matplotlib\image.py", line 1258, in imread
'more images' % list(six.iterkeys(handlers.keys)))
File "F:\pyzo2015a\lib\site-packages\six.py", line 552, in iterkeys
return iter(d.keys(**kw))
AttributeError: 'builtin_function_or_method' object has no attribute 'keys'
The closest analogue to Matlab's imread is scipy.misc.imread, part of the scipy package. I would write this code as:
import scipy.misc
image_array = scipy.misc.imread('filename.jpg')
Now to your broader questions. The reason this seems hard is because you're coming from Matlab, which uses a different philosophy. Matlab is a monolithic install that comes out of the box with a huge number of functions. Python is modular. The built-in library is relatively small, and then you install packages depending on what you want to do. For instance, the packages scipy (scientific computing), cv2 (computer vision), and PIL (image processing) can all read simple images from disk, so you choose between them depending on what else from the package you might want to use.
This provides a lot more flexibility, but it does require you to become comfortable installing packages. Sadly this is much more difficult on Windows than on Linux-like systems, due to the lack of a "package manager". On Linux I can sudo apt-get install scipy and install all of scipy in one line. In Windows, you might be better off installing something like conda that smooths the package installation process.
I want to draw a rectangle on a picture and save it as a new file. what I'm doing is below:
from PIL import Image
from PIL import ImageChops
from PIL import ImageDraw
im = Image.open('the animal picture.jpg')
draw = ImageDraw.Draw(im)
draw.rectangle((69, 17, 418, 107))
im = im.convert('RGB')
im.save('new.jpg')
It gives an error message:
Traceback (most recent call last):
File "C:\Python27\draw_re.py", line 9, in <module>
im.save('new.jpg')
File "C:\Python27\lib\PIL\Image.py", line 1439, in save
save_handler(self, fp, filename)
File "C:\Python27\lib\PIL\JpegImagePlugin.py", line 471, in _save
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
File "C:\Python27\lib\PIL\ImageFile.py", line 494, in _save
for e, b, o, a in tile:
ValueError: Not a valid number of quantization tables. Should be between 1 and 4.
It looks like the problem in PIL - Not a valid numbers of quantization tables. Should be between 2 and 4, but the tip doesn't solve the problem. It makes batch processing impossible.
I worked it out. The problem caused by the Image and PIL libraries I am using.
I uninstalled and removed all previous installed PIL and Image libraries (there were confusion before and difficulties in original installations) so I have cross files and folders for the libraries.
I did the uninstallations through pip, and "Control Panel\All Control Panel Items\Programs and Features" in Windows as well. Also have manually removed the residues folders and files.
Pillow is the one shall be used. I downloaded a MS Windows installer from https://pypi.python.org/pypi/Pillow/2.6.1 and installed it. Run the script and it's working fine.
I'm not entirely sure why this is happening but I am in the process of making a program and I am having tons of issues trying to get opencv to open images using imread. I keep getting errors saying that the image is 0px wide by 0px high. This isn't making much sense to me so I searched around on here and I'm not getting any answers from SO either.
I have taken about 20 pictures and they are all using the same device. Probably 8 of them actually open and work correctly, the rest don't. They aren't corrupted either because they open in other programs. I have triple checked the paths and they are using full paths.
Is anyone else having issues like this? All of my files are .jpgs and I am not seeing any problems on my end. Is this a bug or am I doing something wrong?
Here is a snippet of the code that I am using that is reproducing the error on my end.
imgloc = "F:\Kyle\Desktop\Coinjar\Test images\ten.png"
img = cv2.imread(imgloc)
cv2.imshow('img',img)
When I change the file I just adjust the name of the file itself the entire path doesn't change it just refuses to accept some of my images which are essentially the same ones.
I am getting this error from a later part of the code where I try to use img.shape
Traceback (most recent call last):
File "F:\Kyle\Desktop\Coinjar\CoinJar Test2.py", line 14, in <module>
height, width, depth = img.shape
AttributeError: 'NoneType' object has no attribute 'shape'
and I am getting this error when I try to show a window from the code snippet above.
Traceback (most recent call last):
File "F:\Kyle\Desktop\Coinjar\CoinJar Test2.py", line 11, in <module>
cv2.imshow('img',img)
error: ..\..\..\..\opencv\modules\highgui\src\window.cpp:261: error: (-215) size.width>0 && size.height>0 in function cv::imshow
Probably you have problem with special meaning of \ in text - like \t or \n
Use \\ in place of \
imgloc = "F:\\Kyle\\Desktop\\Coinjar\\Test images\\ten.png"
or use prefix r'' (and it will treat it as raw text without special codes)
imgloc = r"F:\Kyle\Desktop\Coinjar\Test images\ten.png"
EDIT:
Some modules accept even / like in Linux path
imgloc = "F:/Kyle/Desktop/Coinjar/Test images/ten.png"
From my experience, file paths that are too long (OS dependent) can also cause cv2.imread() to fail.
Also, when it does fail, it often fails silently, so it is hard to even realize that it failed, and usually something further the the code will be what sparks the error.
Hope this helps.
Faced the same problem on Windows: cv.imread returned None when reading jpg files from a subfolder. The same code and folder structure worked on Linux.
Found out that cv.imread processes the same jpg files, if they are in the same folder as the python file.
My workaround:
copy the image file to the python file folder
use this file in cv.imread
remove redundant image file
import os
import shutil
import cv2 as cv
image_dir = os.path.join('path', 'to', 'image')
image_filename = 'image.jpg'
full_image_path = os.path.join(image_dir, image_filename)
image = cv.imread(full_image_path)
if image is None:
shutil.copy(full_image_path, image_filename)
image = cv.imread(image_filename)
os.remove(image_filename)
...
I had i lot of trouble with cv.imread() not finding my Image. I think i tryed everything involving changing the path. The os.path.exists(file_path) function also gave me back a True.
I finaly solved the problem by loading the images with imageio.
img = imageio.imread('file_path')
This also loads the img in a numpy array and you can use funktions like cv.matchTemplate() on this object. But i would recomment if u are doing stuff with multiple images that you then read all of them with imageio because i found diffrences in the arrays produced by .imread() from the two libs (opencv, imageio) on a File both of them could open.
I hope i could help someone
Take care to :
try imread() with a reliable picture,
and the correct path in your context like (see Kyle772 answer). For me either //or \.
I lost a couple of hours trying with 2 images saved from a left click in a browser. As soon as I took a personal camera image, it works fine.
Spyder screen shot
#context windows10 / anaconda / python 3.2.0
import cv2
print(cv2.__version__) # 3.2.0
imgloc = "D:/violettes/Software/Central/test.jpg" #this path works fine.
# imgloc = "D:\\violettes\\Software\\Central\\test.jpg" this path works fine also.
#imgloc = "D:\violettes\Software\Central\test.jpg" #this path fails.
img = cv2.imread(imgloc)
height, width, channels = img.shape
print (height, width, channels)
python opencv image-loading imread
I know that the question is already answered but in case anybody still is not able to load images with imread. It may be because there are letters in the string path witch imread does not accept.
For exmaple umlauts and diacritical marks.
My suggestion for everyone facing the same problem is to try this:
cv2.imshow("image", img)
The img is keyword. Never forget.
When you get error like this AttributeError: 'NoneType' object has no attribute 'shape'
Try with new_image=image.copy