Can not open .tif image - python

I want to open a .tif image but I always get error for every library I tried to use.
I tried with PIL:
from PIL import Image
img = Image.open('filepath/img_name.tif')
but I get the following error:
UnidentifiedImageError: cannot identify image file 'filepath/img_name.tif'
(This error does not mean that I can not find the file so the directory should be good)
I tried with tifffile:
import tifffile
img = tifffile.imread('filepath/img_name.tif')
I got the following error:
NotImplementedError: unpacking 14-bit integers to uint16 not supported.
I am pretty sure the problem is that the picture because I tried to open a tif image on the internet and it work just by doing this: this is the picture
from PIL import Image
im = Image.open('a_image.tif')
Is there a way to convert my 14-bit picture to a 16-bit picture?
(I know that I could multiply by 4 to get to 16-bit but I do not know how)

I installed imagedecodecs and tifffile has been able to open it
import tifffile
img = tifffile.imread(tif_name)
The problem was that my image was in 14bits.

Perhaps your TIF file has more than one frame. That could be a problem. Try:
from PIL import Image
image = Image.open("animation.tif")
image.seek(1) # skip to the second frame
try:
while 1:
image.seek(image.tell()+1)
# do something to im
except EOFError:
pass # end of sequence
From the documentation.

Related

How to get jpeg image from a tiff file?

I have a large tiff file contains multiple JPEG image.When I want to get the image from tiff,it will take a lots of time because of decompression from jpeg to rgb. If i want to get the jpeg image without decompression, how should I do with the tiff. Can I parse the TIFF file to get some image data and directly generate a JPEG image?
This is the final implementation method with opentile:
from opentile import OpenTile
import os
import traceback
os.environ.setdefault('TURBOJPEG', 'C:/lib/')
try:
tiler = OpenTile.open('name.svs')
except:
traceback.print_exc()
tile_leve=tiler.levels
print("{}".format(len(tile_leve)))
s=tiler.get_level(0)
print(s.compression.split('.')[1])
print(s.photometric_interpretation)
print(s.samples_per_pixel)
print(s.pixel_spacing)
tile_size=str(s.tiled_size).split("x")
print(s.tile_size)
print(tile_size)
y={}
for i in range(int(tile_size[0])):
for j in range(int(tile_size[1])):
tile = tiler.get_tile(0,0,0, (i, j))
y[(i,j)]=tile
with open("im/im_{}_{}.jpg".format(i,j),"wb") as f:
f.write(tile)
Tifffile is also feasible.

Unable to convert imgkit image to PIL image

I am trying to convert an imgkit image into a PIL image to modify it. imgkit successfully converted the html to image when I tried to use a file. When I use BytesIO and try to convert to a PIL image, im getting an error.
Here is my code:
img = imgkit.from_string(template.render(a=elements, r=range(len(elements))), False, config=config)
bytesImg = BytesIO(img)
bytesImg.seek(0)
image = Image.open(bytesImg) #error here
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x102082680>
I already saw this and this.
Am I incorrectly converting the imgkit image to bytes or is there some other error?
Using Pillow 8.1 Python 3.9 and imgkit 1.0.2
Am I incorrectly converting the imgkit image to bytes or is there some other error?
I would start from checking if your bytes represents image understand by your Pillow. Built-in module imghdr should suffice if you are excepting one of format known by it (see table in docs). Usage in this case:
import imghdr
...
print(imghdr.what(None, h=img))
If it does identify format then check if it is supported by your Pillow, else you would need to manually check file signature (few starting bytes).
imgkit was converting the html to pdf because the config variable was messed up.
use
which wkhtmltoimage
to find path to wkhtmltoimage and set
config = imgkit.config(wkhtmltoimage="path found")

Using python to save a JPG image that was edited in the script

Referring to the answer to this question, I tried to save my own JPG image files, after some basic image processing. I've only applied a rotation and a shear. This is my code:
import numpy as np
import sys
from skimage import data, io, filter, color, exposure
import skimage.transform as tf
from skimage.transform import rotate, setup, AffineTransform
from PIL import Image
mypath = PATH_TO_FILENAME
readfile = FILENAME
img = color.rgb2gray(io.imread(mypath + readfile))
myimg = rotate(img, angle=10, order=2)
afine_tf = tf.AffineTransform(shear=0.1)
editedimg = tf.warp(myimg, afine_tf)
# IF I UNCOMMENT THE TWO LINES BELOW, I CAN SEE THE EDITED IMAGE AS EXPECTED
#io.imshow(editedimg)
#io.show()
saveimg= np.array(editedimg)
result = Image.fromarray((saveimg).astype(np.uint8))
newfile = "edited_" + readfile
result.save(path+newfile)
I know that the image processing was fine because if I display it before saving, it's just the original image with a bit of rotation and shearing, as expected. But I'm doing something wrong while saving it. I tried without the astype(np.uint8)) part but got an error. Then I removed some of the code from the link mentioned above because I guessed it was particularly for Fourier Transforms, since when I included some of their code, then I got an image that was all gray but with white lines in the direction of the shear I'd applied. But now the image that gets saved is just 2KB of nothing but blackness.
And when I tried something as simple as:
result = Image.fromarray(editedimg)
result.save(path+newfile)
then I got this error:
raise IOError("cannot write mode %s as JPEG" % im.mode)
IOError: cannot write mode F as JPEG
I don't really need to use PIL, if there's another way to simply save my image, I'm fine with that.
Look into the PIL fork, Pillow, is is not as outdated and what you should probably be using for this.
Also depending on your operating system you may need a few other libraries to compile PIL with JPEG support properly, see here
This may also help Says you need to convert your image to RGB mode before saving.
Image.open('old.jpeg').convert('RGB').save('new.jpeg')

Mspaint in commandline

I converted images (using imagemagick) from png to bmp.
Trying to analyze the bmp with Python Simplecv
img=Image('im.bmp')
returns an error from PIL:
.....IOError: Unsupported BMP header type (124)
When I convert the image with mspaint, no error is returned.
Consequently, as I have a lot of images to convert, does anybody knows how to save an image with mspaint.
I can open paint but how to save the image ?
Thanks a lot in advance for any clue
Dom
Just working on something similar, below code has worked for me but I'm not sure how to close paint now I've done:
import os
import ImageGrab
SaveDirectory=r'C:\Users\????\Desktop'
sName = "Name of File"
ImageEditorPath=r'C:\WINDOWS\system32\mspaint.exe'
img=ImageGrab.grab()
saveas=os.path.join(SaveDirectory,sName + '.bmp')
img.save(saveas)
editorstring='""%s" "%s"'% (ImageEditorPath,saveas)
os.system(editorstring)

Using Matplotlib imshow to show GIF image

I need to show a background to a matplotlib plot using ax.imshow(). The background images that I will be using are GIF-images. Despite having PIL installed, the following code results in an error complaining that the Python Image Library (PIL) is not installed (which it is):
from pylab import imread
im_file = open("test.gif")
im_obj = imread(im_file)
Reading the image using PIL directly works better:
from PIL import Image
import numpy
img = Image.open("test.gif")
img_arr = asarray(img.getdata(), dtype=numpy.uint8)
However, when reshaping the array, the following code does not work:
img_arr = img_arr.reshape(img.size[0], img.size[1], 3) #Note the number 3
The reason is that the actual color information is contained in a color table accessed through img.getcolors() or img.getpalette().
Converting all the images to PNG or another suitable format that results in RGB images when opening them with imread() or Image.open() is not an option. I could convert the images when needed using PIL but I consider that solution ugly. So the question is as follows: Is there a simple and fast (the images are 5000 x 5000 pixels) way to convert the GIF images to RGB (in RAM) so that I can display them using imshow()?
You need to convert the GIF to RGB first:
img = Image.open("test.gif").convert('RGB')
See this question: Get pixel's RGB using PIL

Categories