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?
Related
I have an image opened with Image.open(). I make some changes, reassigning pixel RGV values,and try to save.
When I try to save, I get:
Trace back (most recent call last):
File "./shimmer", line 97, in <module>
cv2.imwrite('/home/christos/portrait-out.jpg', result)
TypeError: Expected Pre<cv::UMat> for argument 'img'
This happens when the image has been created, baseline = Image.open('/home/christos/portrait-new-mini.jpg').
In searching I have found similar reported errors but no clear articulation of "Here’s what works and how’s why."
I have also seen pages in which similar work is done without similar recorded difficulties.
I can post my code if that is requested, but I am guessing that the problem is narrowly defined by the cv2.imwrite() call and something I want to be feeding the invocation.
Seems that you open the Image in Pillow and try to save the Pillow Image with OpenCV. OpenCV expect a numpy array. You should first convert your image before write in file with opencv.
Check this post : https://stackoverflow.com/a/14140796/13103631
I think, it will solve your issue
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'm trying to open a zipped nifty file using nibabel library (as nib) and the following code:
img = nib.load (nifti_file)
img_data = img.get_data ()
where nifti_file is a variable with the path to the file in the same directory.
On the second line, there is an out-of-memory error that happens 60% of the time randomly while I try running those two lines.
I have enough memory space on my computer so I'm not sure why this happens and also as I mentioned sometimes it simply works.
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'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