I have waveform images stored in a database that need to be displayed and analysed in python.
Apparently, these images are stored as hex strings which are compressed with wctZLib method as shown in this extract of the database.
{
"start_dt": "2021-02-01 07:28:35",
"end_dt": "2021-02-01 07:30:49",
"compress_method": "wctZLib",
"waveform_data": "0x789CB57D07BC56D595BD22E8772E88D84BECBD6001E9B ...
}
A sample of the db can be found at github on :
https://github.com/Ddest/wctZlib/blob/main/wave.json
I tried googling this compression method in order to decompress and display these images but to no avail.
Even after decompressing it and trying to display it with the PIL library...
with open(filepath,'r') as f:
data=json.load(f)
bytesData=bytearray.fromhex(data['waveform_data'][2:])
image = Image.open(io.BytesIO(zlib.decompress(bytesData)))
image.show()
...It didn't work :
Traceback (most recent call last):
File "/home/usx/Desktop/decompress.py", line 24, in <module> main()
File "/home/usx/Desktop/decompress.py", line 12, in main
image = Image.open(io.BytesIO(zlib.decompress(bytesData)))
File "/usr/lib/python3/dist-packages/PIL/Image.py", line 3186, in open
raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f5773d6e020>
even trying to handly it as zip file didn't work.
Can someone give me some insight on how to solve this problem?
Related
The below error is thrown when trying to read the image URL referenced below. (Note, I can't even upload the image to SO because it throws an error when I try to upload it.)
https://s3.amazonaws.com/comicgeeks/comics/covers/large-7441962.jpg
image = imread('https://s3.amazonaws.com/comicgeeks/comics/covers/large-7441962.jpg', as_gray=True)
This is the stack trace.
Traceback (most recent call last):
....
return imread(image_or_path, as_gray=True)
File "skimage/io/_io.py", line 48, in imread
img = call_plugin('imread', fname, plugin=plugin, **plugin_args)
File "skimage/io/manage_plugins.py", line 209, in call_plugin
return func(*args, **kwargs)
File "skimage/io/_plugins/imageio_plugin.py", line 10, in imread
return np.asarray(imageio_imread(*args, **kwargs))
File "imageio/__init__.py", line 86, in imread
return imread_v2(uri, format=format, **kwargs)
File "imageio/v2.py", line 159, in imread
with imopen(uri, "ri", plugin=format) as file:
File "imageio/core/imopen.py", line 333, in imopen
raise err_type(err_msg)
ValueError: Could not find a backend to open `/var/folders/82/rky4yjcx75n1zskhy5570v0m0000gn/T/tmpy9xg7dvb.jpg`` with iomode `ri`.
After looking into this further I believe the image was originally a TIFF file that was just renamed to a .jpg file manually, but I'm not sure. If I download the file and try to open it with Photoshop I get the following message.
Could not open “large-7441962.jpeg” because an unknown or invalid JPEG marker type is found.
If I simply change the extension to a .tiff file it will not open as it states it is an invalid tiff file.
The only way I can open it with photoshop is if I open it with the preview.app and then save a copy of the image as a .tiff file. Then I can open it in photoshop.
This is an issue with a potentially large number of images so re-saving them one-by-one is not an option.
Are there any possible ways to re-save this file when this error is thrown? Or somehow figure out how to handle it even though imread() is failing?
I was able to work around this by using the following.
from PIL import Image
from skimage.io import imread
try:
image = imread(url, as_gray=True)
return image
except:
image = Image.open(requests.get(url, stream=True).raw)
return image
However it is worth noting that when having to make this request using PIL it is significantly slower.
I am setting up a computer vision project to detect and process GFP proteins. I keep getting errors about my file not being a Tiff Image and a Byte Error. I don't quite understand what they mean and haven't found anything about it online.
I have already made sure that the file path is correct and have tried changing the file into Tiff Format. Now on Finder, it says that it is a TIFF Image but still gives an error.
import tifffile
from colicoords import Data, Cell, CellPlot
import matplotlib.pyplot as plt
binary_img = tifffile.imread('organoid_images/gfp/cells1.tif')
data = Data()
data.add_data(binary_img, 'binary')
cell = Cell(data)
cell.optimize()
cp = CellPlot(cell)
plt.figure()
cp.imshow('flu_514', cmap='viridis', interpolation='nearest')
cp.plot_outline()
cp.plot_midline()
plt.show()
Error Message:
Traceback (most recent call last):
File "/Users/CosmoCrash/opencvblobs/lib/python3.7/site-packages/tifffile/tifffile.py", line 2236, in __init__
byteorder = {b'II': '<', b'MM': '>'}[header[:2]]
KeyError: b'\x89P'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "gfp.py", line 6, in <module>
binary_img = tifffile.imread('organoid_images/gfp/cells1.tif')
File "/Users/CosmoCrash/opencvblobs/lib/python3.7/site-packages/tifffile/tifffile.py", line 715, in imread
with TiffFile(files, **kwargs_file) as tif:
File "/Users/CosmoCrash/opencvblobs/lib/python3.7/site-packages/tifffile/tifffile.py", line 2238, in __init__
raise TiffFileError('not a TIFF file')
tifffile.tifffile.TiffFileError: not a TIFF file
Your file starting \x89P is a PNG file, not TIFF, as that is a PNG signature, whereas TIFF files start II if in Intel order, or MM if in Motorola order.
If on Linux/macOS, try running:
file cells1.tif
See Wikipedia for description of PNG signature, as suggested by Warren.
See Wikipedia for description of TIFF header.
I am trying to get some code working that has broken but was working before. I have a PNG file on my desktop and I simply want to open it using the Image module from PIL.
from PIL import Image
img_dir = r'C:\Users\DylanDB\Desktop\square.png'
img = Image.open(img_dir)
This is a remake of my more advanced code that it happens in as well. The error is:
Traceback (most recent call last):
File "C:/Users/DylanDB/Desktop/img_test.py", line 5, in <module>
img = Image.open(img_dir)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2317, in open
% (filename if filename else fp))
OSError: cannot identify image file 'C:\\Users\\DylanDB\\Desktop\\square.png'
I had the same error and it was due to the file was recently created and not closed properly before opening with the Image.open(). After closing the file f.close() it werked as expect
I found that the file was a corrupted image.
I'm looking for a way to open and crop several tiff images and then save the new croped images created in the same folder (related to my script folder).
My current code looks like this:
from PIL import Image
import os,platform
filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")
for file in os.listdir(filespath):
if file.endswith(".tif"):
im = Image.open(file)
im.crop((3000, 6600, 3700, 6750)).save(file+"_crop.tif")
This script is returning me the error:
Traceback (most recent call last):
File "C:\Users...\Desktop\Python\script.py", line 22, in
im = Image.open(file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 2219, in open
fp = builtins.open(fp, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Image1Name.tif'
'Image1Name.tif' is the first tif image I'm trying to process in the folder. I don't get how the script can give the file's name without being able to find it. Any Help?
PS: I have 2 days experience in python and codes generaly speaking. Sorry if the answer is obvious
[EDIT/Update]
After modifying my initial code thanks to vttran and ChrisGuest answers, turning then into this:
from PIL import Image
import os,platform
filespath = os.path.join(os.environ['USERPROFILE'],"Desktop\Python\originalImagesfolder")
for file in os.listdir(filespath):
if file.endswith(".tif"):
filepath = os.path.join(filespath, file)
im = Image.open(filepath)
im.crop((3000, 6600, 3700, 6750)).save("crop"+file)
the script is returning me a new error message:
Traceback (most recent call last):
File "C:/Users/.../Desktop/Python/script.py", line 11, in
im.crop((3000, 6600, 3700, 6750)).save("crop"+file)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 986, in crop
self.load()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 166, in load
self.load_prepare()
File "C:\Python34\lib\site-packages\PIL\ImageFile.py", line 250, in
load_prepare
self.im = Image.core.new(self.mode, self.size) ValueError: unrecognized mode
A maybe-useful information, it's a Landsat8 image in GeoTiff format. The TIFF file therefore include geoposition, projection... informations. The script works perfectly fine if I first open and re-save them with a software like Photoshop (16int tiff format).
When you are search for the file names you use filespath to specify the directory.
But then when you open the file, you are only using the base filename.
So you could replace
im = Image.open(file)
with
filepath = os.path.join(filespath, file)
im = Image.open(filepath)
Also consider using the glob module, as you can do glob.glob(r'path\*.tif) .
It is also good practice to avoid using builtin functions like file as variable names.
TLDR; I'm trying to take a TIFF, resize it, then save it. However it returns an error. This works fine if I change the saved filetype to png or jpg.
System: Windows 7
Tried using both Python 3.4 and 2.7.
Code:
from PIL import Image
try: #test file exists
im = Image.open(r"c:\temp\file.tif")
except:
print("Error opening image")
multiply = 5 #how much bigger
processing = tuple([multiply*x for x in im.size]) #maths
saved = (r"c:\temp\biggerfile.tif") #save location
imB = im.resize((processing)) #resizing
imB.save(saved) #saving
I need to resize a TIFF because I'm using tesseract-ocr, and resizing the image to get a better output. The program seems to work best with a TIFF.
The error I receive is:
_TIFFVSetField: c:\temp\biggerfile.tif: Bad value 2 for "ExtraSamples" tag.
Traceback (most recent call last):
File "step1.py", line 15, in <module>
imB.save(saved)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 1684, in save
save_handler(self, fp, filename)
File "C:\Python34\lib\site-packages\PIL\TiffImagePlugin.py", line 1185, in _save
e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)
File "C:\Python34\lib\site-packages\PIL\Image.py", line 430, in _getencoder
return encoder(mode, *args + extra)
RuntimeError: Error setting from dictionary
Thanks!
Try to install libtiff
http://gnuwin32.sourceforge.net/packages/tiff.htm
File "C:\Python34\lib\site-packages\PIL\TiffImagePlugin.py", line 1185, in _save
e = Image._getencoder(im.mode, 'libtiff', a, im.encoderconfig)
Looks like that's the error that is holding you up. It's trying to access libtiff and you don't have it installed so it's failing.
Had the same issue, when using PIL to combine multiple images to one and adding a label.
I could fix this easily by converting the .tif file to a .png file in MS Paint (pls don't hate me for using MS :D). Quality of the final merged image was not reduced.