IOError: codec configuration error when reading image file - python

I am trying to get a thumbnail of a gif image using Pillow 4.3.0, Python 2.7.13, Debian 9.1
from PIL import Image
im = Image.open("Pictures/image.gif")
im.thumbnail((240,160))
im.save("Thumbnails/thumbnail.gif")
But I cannot do it. This is the log:
Traceback (most recent call last):
File "testpy.py", line 4, in <module>
im.thumbnail((240,180))
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1843, in
thumbnail
im = self.resize(size, resample)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1541, in
resize
self.load()
File "/usr/lib/python2.7/dist-packages/PIL/ImageFile.py", line 244, in
load
raise_ioerror(err_code)
File "/usr/lib/python2.7/dist-packages/PIL/ImageFile.py", line 59, in
raise_ioerror
raise IOError(message + " when reading image file")
IOError: codec configuration error when reading image file
This issue doesn't occur with other formats (jpg, png, bmp).
Any help is very appreciated.
Edit:
This happens specifically on pictures made with raspistill camera with gif encoding mode selected. If don't select encoding mode at all, it works well. But if not selecting encoding, then all the images are treated as jpg, which is not what I want.

The raspistill camera gif images contain a bit depth of 11,
>>> im.tile
[('gif', (0, 0, 100, 100), 792, (11, False))]
while Pillow supports gif images only up to a bit depth of 8.
I posted this question on Pillow github page and they are supposed to fix it soon.
https://github.com/python-pillow/Pillow/issues/2811

Related

How to Display .raw Dataset?

I'm trying to write a script to display the images in the file burned_wood_with_tape_1664x512x256_12bit.raw from this website: https://figshare.com/articles/SSOCT_test_dataset_for_OCTproZ/12356705
for a research project. However, I can't find a way to display the images in this .raw dataset.
This is the software I have, using other questions on StackOverflow:
import rawpy
import imageio
path = "Datasets/burned_wood_with_tape_1664x512x256_12bit.raw"
for item in path:
item_path = path + item
raw = rawpy.imread(item_path)
rgb = raw.postprocess()
rawpy.imshow(rgb)
But I get this error:
Traceback (most recent call last):
File "[ENTER PATH]", line 7, in <module>
raw = rawpy.imread(item_path)
File "[ENTER PATH]\lib\site-packages\rawpy\__init__.py", line 20, in imread
d.open_file(pathOrFile)
File "rawpy\_rawpy.pyx", line 404, in rawpy._rawpy.RawPy.open_file
File "rawpy\_rawpy.pyx", line 914, in rawpy._rawpy.RawPy.handle_error
rawpy._rawpy.LibRawIOError: b'Input/output error'
The data that you have is not a ".raw" file. It is a dataset that can be used with the "Virtual OCT System" of OCTproZ (https://github.com/spectralcode/OCTproZ/). The "rawpy" library is not useful in this case. That library works for ".raw" photos.

Python: Can't display images in Zelle graphics.py, tkinter can't read image data

I am trying to display the image "picture.gif" in this code:
from graphics import *
import tkinter
win = GraphWin("Self Portrait", "1000", "500")
image = Image(Point(5,5), "picture.gif")
image.draw(win)
window.mainloop()
However, I keep getting this error:
Traceback (most recent call last):
File "/Users/jstorrke/Desktop/Python/graphicsProject.py", line 6, in <module>
image = Image(Point(5,5), "picture.gif")
File "/Users/jstorrke/Desktop/Python/graphics.py", line 827, in __init__
self.img = tk.PhotoImage(file=pixmap[0], master=_root)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 3394, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 3350, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "picture.gif"
The graphics module provides very minimal support for displaying images. Try putting the image on the same folder as where graphics library is and see if it helps.
Please look at this document for more information on graphics module. http://mcsp.wartburg.edu/zelle/python/graphics/graphics.pdf
_tkinter.TclError: couldn't recognize data in image file "picture.gif"
I looked at dozens of examples this error message and the cause seems to fall into two categories:
1) The file wasn't a supported type (e.g. *.jpg, *.png, *.tif) which was obvious from the extension.
2) The file used was mislabeld as a *.gif when it wasn't. (More common than I would expect.) On Unix systems you may be able to use the file command to verify your GIF:
> file p7Q6O.gif
p7Q6O.gif: GIF image data, version 89a, 520 x 416
>
An actual failure of a valid GIF file occurs if it's an animated GIF which are not supported. However, this can be a silent failure -- no error message and no image displayed.

Error Message When Converting to Grayscale in Python Using PIL?

So, I've got PIL installed (at least I think properly) to convert color images to grayscale, and when I use this code
from PIL import Image
image_file = Image.open("James.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('Gray.png')
IDLE shows me this...
Traceback (most recent call last):
File "C:/Users/Kane/Desktop/huh.py", line 2, in <module>
image_file = Image.open("James.png")
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1952, in open
fp = __builtin__.open(fp, "rb")
IOError: [Errno 2] No such file or directory: 'James.png'
What do I need to do to fix this? I have Python 2.7, does this make a difference?
Your problem could be that the image file "James.png" is not in the same directory as your script, in your example on your Desktop. Is that the case?
Cheers

Python mac matplotlib imread error

I'm trying to read a jpg image using matplotlib's pyplot.
This is the error I get when using the imread command:
Traceback (most recent call last):
File "/Users/rugheid/Dropbox/Documents/Rugen Dropbox/School/Universiteit/3e jaar/P&O/Git Repository/backend/image_processing/image_processor.py", line 27, in <module>
img = pyplot.imread(io.BytesIO(jpg_bytes), format='jpg')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/pyplot.py", line 2177, in imread
return _imread(*args, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/image.py", line 1242, in imread
im = pilread(fname)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/image.py", line 1226, in pilread
return pil_to_array(image)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/image.py", line 1328, in pil_to_array
x = toarray(im)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/image.py", line 1313, in toarray
x_str = im.tostring('raw', im.mode)
File "/Library/Python/2.7/site-packages/PIL/Image.py", line 695, in tostring
"Please call tobytes() instead.")
Exception: tostring() has been removed. Please call tobytes() instead.
It seems it's calling something from PIL that has been removed... Can I change matplotlib to use Pillow instead of PIL? Or can I do something else? I have the most recent version of matplotlib installed.
Thanks in advance!
You should probably just use pillow directly, since matplotlib just falls back to PIL anyway for anything other than PNG files. From the documentation:
matplotlib can only read PNGs natively, but if PIL is installed, it will use it to load the image and return an array (if possible)
To load a JPG with pillow:
from PIL import Image
im = Image.open('myimage.jpg')
This way you cut out the middle man and control the image loading directly.

Why am I getting "I/O operation on closed file" with PILLOW 3.1.0?

I am attempting to convert a tiff file into a PDF using Pillow and PyPDF. I was able to get this to work using an earlier version of Pillow, although I cannot which version.
I recently upgraded to Pillow 3.1.0, and now I ran into issues. This is the previously working code.
import os
import traceback
from PIL import Image
from PyPDF2 import PdfFileReader, PdfFileMerger
to_merge = []
with Image.open('my_tif.tif') as img:
seeker = 0
while True:
try:
# temp file name for PDF
img_pdf = 'temp_{}.pdf'.format(seeker)
#seeks to next image with TIFF
img.seek(seeker)
# saves the image as a PDF
img.save(img_pdf)
seeker += 1
to_merge.append(img_pdf)
except Exception as err:
traceback.print_exc()
break
merger = PdfFileMerger()
for f in to_merge:
merger.append(PdfFileReader(f))
os.remove(f)
merger.write('merged.pdf')
Beforehand, it generated a PDF for each image within the tiff and then merged the PDFs together with no problem.
After I upgraded to Pillow 3.1.0 it loops through all of the images, but then throws a ValueError on the final image.
Traceback (most recent call last):
File "C:/Code/Python/tiff_to_pdf.py", line 16, in <module>
img.save(img_pdf)
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1675, in save
save_handler(self, fp, filename)
File "C:\Python27\lib\site-packages\PIL\PdfImagePlugin.py", line 155, in _save
im.seek(pageNumber)
File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 930, in seek
self._seek(max(frame, 0)) # Questionable backwards compatibility.
File "C:\Python27\lib\site-packages\PIL\TiffImagePlugin.py", line 956, in _seek
self.fp.seek(self._frame_pos[frame])
ValueError: I/O operation on closed file
What would be the cause of the ValueError?
I had the same problem a while ago. The only solution I found was to open the file as a file object and pass that to Image.Open on each iteration:
with open('my_tif.tif', 'rb') as f:
seeker = 0
while True:
try:
img = Image.open(f)
# temp file name for PDF
img_pdf = 'temp_{}.pdf'.format(seeker)
#seeks to next image with TIFF
img.seek(seeker)
# saves the image as a PDF
img.save(img_pdf)
seeker += 1
to_merge.append(img_pdf)
except Exception as err:
traceback.print_exc()
break
I also occur this issue in Pillow 5.4.1, downgraded to 5.0.0 was resolved.
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/web.py", line 1592, in _execute
result = yield result
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1133, in run
value = future.result()
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1141, in run
yielded = self.gen.throw(*exc_info)
File "/home1/irteam/deploy/oneapp-clover/doc_base/clover/profilehandler.py", line 73, in get
image, tmp_error_code = yield loadUserImage(user_no, hash_id, headers)
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1133, in run
value = future.result()
File "/home1/irteam/miniconda3/lib/python3.6/site-packages/tornado/gen.py", line 1147, in run
yielded = self.gen.send(value)
File "/home1/irteam/deploy/oneapp-clover/doc_base/clover/merge_profile.py", line 273, in loadUserImage
setCache(user_cache_key, image_file.getvalue())
ValueError: I/O operation on closed file.
Problem
There can be two problems.
Image.Image.seek()
If the image is a single-frame image, the file will be closed in this
method after the frame is read. If the image is a multi-frame image, (e.g.
multipage TIFF and animated GIF) the image file is left open so that
Image.Image.seek() can load the appropriate frame.
Image.Image.close()
Closes the file and destroys the core image object.
The Pillow context manager will also close the file, but will not destroy
the core image object.
Solution
If you are using Image.Image.seek() function to read the image and want to
re-use the image again without opening it.
What you can do, is copy the loaded image into another variable and perform
operation.
loaded_image = Image.open("test.jpg")
temp = loaded_image.copy()
Now you can use temp.sheek() to read the image and your loaded image
will be safe
If you are not using Image.Image.seek() and facing the same issue then
you are using Image.Image.close() function that is destroying the
image.
So, do not use Image.Image.close() if you want to re use the image.
Solution Source
File Handling in Pillow Read the Image Lifecycle section

Categories