OSError when reading image files using matplotlib - python

When trying to follow the example posted here. The code segment is the same as given in the example
import matplotlib.image as mpimg
filename = "/home/MarshOrchid.jpg"
image = mpimg.imread(filename)
# Print out its shape
print(image.shape)
Running the code gives the following error message. What could be the underlying cause?
Traceback (most recent call last):
File "test2.py", line 5, in <module>
image = mpimg.imread(filename)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux- x86_64.egg/matplotlib/image.py", line 1304, in imread
im = pilread(fname)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1283, in pilread
return pil_to_array(image)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1400, in pil_to_array
x = toarray(im)
File "/tfw/lib/python3.4/site-packages/matplotlib-1.5.1-py3.4-linux-x86_64.egg/matplotlib/image.py", line 1383, in toarray
x_str = im.tobytes('raw', im.mode)
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/Image.py", line 678, in tobytes
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/ImageFile.py", line 235, in load
File "/tfw/lib/python3.4/site-packages/Pillow-3.2.0-py3.4-linux-x86_64.egg/PIL/ImageFile.py", line 59, in raise_ioerror
OSError: broken data stream when reading image file

Related

read_mrz error : Could not find a format to read the specified file in mode 'i'

The below code is what i am using to read mrz data from a passport, and it works absolutely fine when i run it on my local computer, but when i try to execute it on my server (Windows AWS server) it throws an error.
Can you please help what's this error and how to resolve it.
from PIL import Image
import sys
from passporteye import read_mrz
import pytesseract
mrz = read_mrz("C:/docs/IMG/PASSPORT/abc.png")
Error :
Traceback (most recent call last):
File "C:/qfc_apps/edocs/PY/PASSPORT/passport.py", line 64, in <module>
passport()
File "C:/qfc_apps/edocs/PY/PASSPORT/passport.py", line 19, in passport
mrz = read_mrz("C:/docs/IMG/PASSPORT/abc.png")
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 337, in read_mrz
mrz = p.result
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 325, in result
return self['mrz_final']
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 102, in __getitem__
self._compute(key)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
self._compute(d)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
self._compute(d)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 109, in _compute
self._compute(d)
[Previous line repeated 1 more times]
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\util\pipeline.py", line 111, in _compute
results = self.components[cname](*inputs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 52, in __call__
return self._imread(self.file)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\passporteye\mrz\image.py", line 37, in _imread
img = skimage_io.imread(file, as_gray=self.as_gray, plugin='imageio')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\_io.py", line 61, in imread
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\skimage\io\manage_plugins.py", line 210, in call_plugin
return func(*args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\imageio\core\functions.py", line 221, in imread
reader = read(uri, format, "i", **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\imageio\core\functions.py", line 139, in get_reader
"Could not find a format to read the specified file " "in mode %r" % mode
ValueError: Could not find a format to read the specified file in mode 'i'
Figured out the solution after hours of research so posting my solution for others who might face a similar solution.
I still couldnt figure out what was the problem with the above code but i managed a way out.
Documentation of passporteye mentions that either we pass the path of the image or a byte stream containing image data. As path was not working for me so i opted for the second method.
Using the below code solves our problem :-
image = cv2.imread("path of image")
import PIL.Image as Image
import io
pil_im = Image.fromarray(image)
b = io.BytesIO()
pil_im.save(b, 'jpeg')
im_bytes = b.getvalue()
mrz = read_mrz(im_bytes)

IOError: cannot identify image file in Python

I am trying to run this start up code where I am trying to get python to read photos as I am trying to get it to copy all the photos in 1200 folders and paste them to a single photo for my deep learning project. But I keep getting this error or problem.
from PIL import Image
im = Image.open("1.jpg")
im.show()
This is what I get when I try to run the code.
anthony#anthony-G53JW:~/design4$ python copy2.py
Traceback (most recent call last):
File "copy2.py", line 2, in <module>
im = Image.open("1.jpg")
File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2289, in open
preinit()
File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 365, in preinit
from PIL import JpegImagePlugin
File "/usr/local/lib/python2.7/dist-packages/PIL/JpegImagePlugin.py", line 40, in <module>
from PIL import Image, ImageFile, TiffImagePlugin, _binary
File "/usr/local/lib/python2.7/dist-packages/PIL/TiffImagePlugin.py", line 50, in <module>
from fractions import Fraction
File "/usr/lib/python2.7/fractions.py", line 7, in <module>
from decimal import Decimal
File "/usr/lib/python2.7/decimal.py", line 139, in <module>
import copy as _copy
File "/home/anthony/design4/copy.py", line 25, in <module>
dataset = Image.open("1.jpg")
File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2317, in open
% (filename if filename else fp))
IOError: cannot identify image file '1.jpg'

Python 3.5: Open an image with underscore in file name?

I have a script (seen below) that opens a collection of images. It took me a while to figure this out, but I realized that the script can't seem to open any of the image files with an underscore in the name. An example of my image directory is as follows:
Images\img1.jpg
Images\img2.jpg
Images\img3_c.jpg
The script will behave as expected when dealing with "normal" image file names. The moment the script has to open a file with an underscore in the name, it returns an error as follows:
OSError: cannot identify image file <_io.BufferedReader name='TrainingSets\\CottonWoolSpots\\0006_c.jpg'>
I would like to avoid changing my file names if possible. Any help is appreciated.
Script:
import numpy as np
from skimage import io
import glob
import os
def importAllImgs():
imagePath = glob.glob("TrainingSets\CottonWoolSpots\*.jpg")
im_coll = io.ImageCollection(imagePath)
im_array = []
for i in range(len(im_coll)):
image = im_coll[i]
im_array.append(image)
return im_array
if __name__ == "__main__":
testArray = importAllImgs()
EDIT FULL STACKTRACE + ERROR:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 734, in debugfile
debugger.run("runfile(%r, args=%r, wdir=%r)" % (filename, args, wdir))
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\bdb.py", line 431, in run
exec(cmd, globals, locals)
File "<string>", line 1, in <module>
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "//mspm1bnas50s/home58/biegad1/python scripts/batchimportimgs_0_1.py", line 54, in <module>
testArray = importAllImgs()
File "//mspm1bnas50s/home58/biegad1/python scripts/batchimportimgs_0_1.py", line 36, in importAllImgs
image = im_coll[i]
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\skimage\io\collection.py", line 264, in __getitem__
self.data[idx] = self.load_func(self.files[n], **kwargs)
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\skimage\io\_io.py", line 61, in imread
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\skimage\io\manage_plugins.py", line 211, in call_plugin
return func(*args, **kwargs)
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\skimage\io\_plugins\pil_plugin.py", line 36, in imread
im = Image.open(f)
File "C:\Users\biegad1\AppData\Local\Continuum\Anaconda3\lib\site-packages\PIL\Image.py", line 2309, in open
% (filename if filename else fp))
OSError: cannot identify image file <_io.BufferedReader name='TrainingSets\\CottonWoolSpots\\0006_c.jpg'>
OKAY! So. It appears that I've been working with corrupted image files the entire time, hence the errors.

Python Scipy library: saving images

I am learning image processing with scipy. I experience some diffuculties with rather basic opeartions as saving an image. Here is my code:
import scipy
from scipy import misc
img=misc.imread("C:\\..\\name.jpg")
misc.imsave("image.jpg",img)
I obtain error message:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
misc.imsave("image.jpg",img)
File "C:\Python27\lib\site-packages\scipy\misc\pilutil.py", line 158, in imsave
im.save(name)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1461, in save
fp = builtins.open(fp, "wb")
IOError: [Errno 13] Permission denied: 'image.jpg'
Try to use the full path when saving:
misc.imsave(r'C:\path\image.jpg', img)
your error is a permission error, so probably you do not have access to write in the current directory. You can also change the current directory using os.chdir( newpath ).
The code above creates a file in a given directory but it is empty (0 bytes) and produces error in the IDLE:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
misc.imsave(r"D:\Darek\back3.jpg", img)
File "C:\Python27\lib\site-packages\scipy\misc\pilutil.py", line 158, in imsave
im.save(name)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1467, in save
save_handler(self, fp, filename)
File "C:\Python27\lib\site-packages\PIL\JpegImagePlugin.py", line 557, in _save
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 466, in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 395, in _getencoder
return encoder(mode, *args + extra)
TypeError: function takes at most 11 arguments (13 given)
Hmm, your code works fine for me in the dreampie shell
import scipy
from scipy import misc
img = misc.imread("C:/folder/name.jpg")
misc.imsave("C:/folder2/image.jpg",img)
I don't know PIL well enough, but there seems to be an encoder issue involved. Have you tried your code with different image files?

scipy.io typeerror:buffer too small for requested array

I have a problem in python. I'm using scipy, where i use scipy.io to load a .mat file. The .mat file was created using MATLAB.
listOfFiles = os.listdir(loadpathTrain)
for f in listOfFiles:
fullPath = loadpathTrain + '/' + f
mat_contents = sio.loadmat(fullPath)
print fullPath
Here's the error:
Traceback (most recent call last):
File "tryRankNet.py", line 1112, in <module>
demo()
File "tryRankNet.py", line 645, in demo
mat_contents = sio.loadmat(fullPath)
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/mio.py", line 111, in loadmat
matfile_dict = MR.get_variables()
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/miobase.py", line 356, in get_variables
getter = self.matrix_getter_factory()
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/mio5.py", line 602, in matrix_getter_factory
return self._array_reader.matrix_getter_factory()
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/mio5.py", line 274, in matrix_getter_factory
tag = self.read_dtype(self.dtypes['tag_full'])
File "/usr/lib/python2.6/dist-packages/scipy/io/matlab/miobase.py", line 171, in read_dtype
order='F')
TypeError: buffer is too small for requested array
The whole thing is in a loop, and I checked the size of the file where it gives the error by loading it interactively in IDLE.
The size is (9,521), which is not at all huge. I tried to find if I'm supposed to clear the buffer after each iteration of the loop, but I could not find anything.
Any help would be appreciated.
Thanks.

Categories