Working with TIFFs (import, export) in Python using numpy
First, I downloaded a test TIFF image from this page called a_image.tif
. Then I opened with PIL like this:
>>> from PIL import Image
>>> im = Image.open('a_image.tif')
>>> im.show()
This showed the rainbow image. To convert to a numpy array, it's as simple as:
>>> import numpy
>>> imarray = numpy.array(im)
We can see that the size of the image and the shape of the array match up:
>>> imarray.shape
(44, 330)
>>> im.size
(330, 44)
And the array contains uint8
values:
>>> imarray
array([[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
...,
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246],
[ 0, 1, 2, ..., 244, 245, 246]], dtype=uint8)
Once you're done modifying the array, you can turn it back into a PIL image like this:
>>> Image.fromarray(imarray)
<Image.Image image mode=L size=330x44 at 0x2786518>
Python: How do I read the data in this multipage TIFF file to produce the desired image?
"produce a numpy array representing the new image that looks as it is meant to.": The PNG image looks like a thumbnail image, a somewhat arbitrary preview of the data in the TIFF file obtained by binning and scaling:
import tifffile
im = tifffile.imread('20180309_Vn_ribosome_0001.tif', maxworkers=6)
binsize = 25
height = im.shape[1] // binsize
width = im.shape[2] // binsize
im = im[:, :height * binsize, : width * binsize]
im = im.reshape(im.shape[0], height, binsize, width, binsize)
im = im.sum((0, 2, 4), dtype='uint32')
from matplotlib import pyplot
pyplot.imshow(im, cmap='gray')
pyplot.show()
Python PIL For Loop to work with Multi-image TIFF
You can use the "seek" method of a PIL image to have access to the different pages of a tif (or frames of an animated gif).
from PIL import Image
img = Image.open('multipage.tif')
for i in range(4):
try:
img.seek(i)
print img.getpixel( (0, 0))
except EOFError:
# Not enough frames in img
break
Related Topics
Convert Timedelta64[Ns] Column to Seconds in Python Pandas Dataframe
Case-Insensitive List Sorting, Without Lowercasing the Result
How to Configure Atom to Run Python3 Scripts
Get Timezone from City in Python/Django
How to Write String Literals in Python Without Having to Escape Them
Prevent Plot from Showing in Jupyter Notebook
Python/Beautifulsoup - How to Remove All Tags from an Element
How to Invoke Pandas.Rolling.Apply with Parameters from Multiple Column
How to Rotate Xticklabels in Matplotlib So That the Spacing Between Each Xticklabel Is Equal
Image Segmentation Based on Edge Pixel Map
How to Generate a List of Consecutive Numbers
Reading/Writing Ms Word Files in Python