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.
Related
I have some .bsq files with corresponding header files (.hdr). I want to open and edit them in Python, using the spectral (SPy) module.
Since I need to edit the files from within a Python Toolbox in ArcMap (that is, a single Python script which uses the Python installation that comes with ArcMap), I decided to copy the GitHub repository of the SPy module and import it as
import sys
sys.path.append("/path/to/module")
import spatial as spy
in order to be able to run the toolbox on any computer without having to install pip or other software. (I intend to just copy the Toolbox and the module folder, or, in a later step, create a single Python script comprising the Toolbox as well as the SPy-module code.)
I opened some .bsq-file and tried to subsequently edit it as memmap, following this example.
First, I opened the image as spectral.io.bsqfile.BsqFile:
path = "/path/to/image_header.hdr"
img = spy.open_image(path)
I am able to apply various methods to img (such as: view metadata, read bands as array, etc), hence, I assume there were no issues with the path or the image file. I can also read single bands with memmap = True:
mem_band = img.read_band(0, use_memmap = True)
Reading a single band results in an array of shape (lines, samples) with dtype: float64 and where lines and sample correspond to the respective values in the .hdr file.
However, trying to apply the .open_memmap() method to the BsqFile instance as follows:
mem = img.open_memmap(writable = True)
results in the following error:
Runtime error
Traceback (most recent call last):
File "<string>", line 1, in <module>
File
"/path/to/module/spectral/io/spyfile.py", line 809, in open_memmap dst_inter))
File "/path/to/lib/site-packages/numpy/core/fromnumeric.py", line 536, in transpose
return _wrapit(a, 'transpose', axes)
File "/path/to/lib/site-packages/numpy/core/fromnumeric.py", line 45, in _wrapit
result = getattr(asattr(obj), method)(*args, **kwds)
ValueError: axes don't match array
Is this due to some incompatibilities between the numpy version that comes with the ArcMap-Python-Installation which I am required to use (numpy version 1.9.2)? Or are there other issues with the code or set-up?
Python version: 2.7.10
numpy version: 1.9.2
spectral version: 0.23.1
Edit
With the given Python version, spectral.envi.create_image() cannot create images of the given size due to an OverflowError. Potentially, this older Python version does not handle large numbers "correctly"?
Using another Python installation, the .open_memmap() method worked without issues.
i have a .mat file containing annotations for some images, I need to read and manipulate specified values from this file using python and am stuck I tried to use h5py it doesn't work for me. with scipy I can read the file and print the whole file but I can't get a specified value.
I captured the structure of my mat file using octave can anyone help me to get the BBox values for each ImgName and save them into a variable.
screen shot of the annotation.mat file
Problem solved using this ( it may help some beginners like me) :
import scipy.io as spio
anno=spio.loadmat('annotation_1.mat')
#BBox. X y
#print(anno['annot'][0][1][0])
listX=anno['annot'][0][1][0]
print(listX[1][1])
#ImgName
#print(anno['annot'][0][1][1])
img=anno['annot'][0][1][1]
print(img)
I would like to read a tif file with basically the following code:
import matplotlib.pyplot as plt
filename = 'test.tif'
plt.imread(filename)
This results in the following error message (just the last lines):
File ".../miniconda2/lib/python2.7/site-packages/PIL/Image.py", line 692, in tobytes
self.load()
File ".../miniconda2/lib/python2.7/site-packages/PIL/TiffImagePlugin.py", line 1013, in load
return super(TiffImageFile, self).load()
File ".../miniconda2/lib/python2.7/site-packages/PIL/ImageFile.py", line 204, in load
decoder.setimage(self.im, extents)
ValueError: tile cannot extend outside image
When I open the tif image with imagemagick's display and save it without making changes, everything works normally.
Nevertheless, I think it could a problem with my python environment/version, as my colleague who's working with the same code and the same files did not have this problem.
I tried many files and it ends in the same for all of them. I am aware that, for this mini example, I could make a workaround or use e.g. gdal (which works fine). But as these lines are just a part of a larger code and are supposed to work for new files immediately, I would like to have a real solution.
I am working with openSUSE 11.4, conda 4.3.23, Python 2.7.13, matplotlib 2.0.2 .
This could be a duplicate of Value Error in reading tif image with pil in python?. Due to the lack of specific information there, I open a new question. Sorry if that's the wrong way - my first post here...
Remark: I see that my tif file gets uploaded as png here. Is there a way to change that?
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
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.