Plot 12-bit tiff image with log scale colorbar using python & matplotlib.pyplot


The result is:

Show 12-bit tiff image with log scale colorbar using python & matplotlib.pyplot

Some of the output data from measuring equipment have 12-bit unsigned int data. In some case, tiff format is used to ensure the convenience of the users. Reading the 12-bit tiff file and plotting the 12-bit tiff file is very easy. In addition, you can increase the visibility of the output figure by using log scale colormap when you plotting the tiff file. This page shows how to plot 12-bit tiff file in log scale using python and matplotlib.pyplot. 2D gaussian distribution is used as an example data.

See also:

Python Matplotlib Tips: Plot contour figure from data which has large scale and plus-minus difference using Python and matplotlib.pyplot

This page shows my suggestion to generate contour figure from data which has large scale and plus-minus difference using python and matplotlib.pyplot.

Python Matplotlib Tips: Plot contour figure from data which has large scale and plus-minus difference with minimum limit using Python and matplotlib.pyplot

This page shows my suggestion to generate contour figure from data which has large scale and plus-minus difference using python and matplotlib.pyplot. The minimum value and maximum value can be specified in this code.


In [1]:
import platform
print('python: '+platform.python_version())
import matplotlib.pyplot as plt
from matplotlib import __version__ as matplotlibversion
print('matplotlib: '+matplotlibversion)
import numpy as np
print('numpy: '+np.__version__)
%matplotlib inline
python: 3.6.3
matplotlib: 3.0.1
numpy: 1.15.4
In [2]:
# In this page, I use gaussian like 2D distribution as an example of 2D data.
# The following function is obtained from following GitHub page:
# https://gist.github.com/andrewgiessel/4635563

def makeGaussian(size, fwhm=3, center=None):
    x = np.arange(0, size, 1, float)
    y = x[:, np.newaxis]
    if center is None:
        x0 = y0 = size //2
    else:
        x = center[0]
        y = center[1]
    
    return np.exp(-((x-x0)**2 + (y-y0)**2) / fwhm**2)
In [3]:
# Generate test 2D data
testdata = makeGaussian(20)
# Convert the maximum value to 4095, which is the maximum value of 12-bit uint tiff file
testdata = 4095 * testdata / testdata.max()
# Convert the type of the array to unsigned int
testdata_uint12 = testdata.astype("uint")

# plot the test data
plt.imshow(testdata_uint12)
plt.colorbar()
Out[3]:
<matplotlib.colorbar.Colorbar at 0x11c8ea828>
In [4]:
# save the image using tifffile module
from tifffile import TiffWriter
with TiffWriter("test.tiff") as f:
    f.save(testdata_uint12)

The main part of this page is following plotting section.
At first, we have to load the saved 12-bit tiff file as an array.
Then check the type, dtype, shape of the loaded array.

In [5]:
from tifffile import TiffFile
with TiffFile("test.tiff") as f:
    arr = f.asarray()
type(arr), arr.dtype, arr.shape
Out[5]:
(numpy.ndarray, dtype('uint64'), (20, 20))

Plot data in normal linear scale.

In [6]:
plt.imshow(arr, cmap="gray")
plt.colorbar()
plt.savefig("tiff_uint_12bit_linear.png", bbox_inches="tight", pad_inches=0.02)

Plot data using in logscale

In [7]:
from matplotlib.ticker import MaxNLocator
from matplotlib.colors import BoundaryNorm

# max value to use for plotting (in the log-scale colorbar)
cmin, cmax = 5, 12
# configure the values to use colorbar and define colormap, normalization
# this is based on the following reference:
# https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/pcolormesh_levels.html
lvls = MaxNLocator(nbins=257).tick_values(cmin, cmax)
cmap = plt.get_cmap("gray")
norm = BoundaryNorm(lvls, ncolors=cmap.N, clip=True)

cmesh = plt.imshow(np.log2(arr+1e-10), cmap=cmap, norm=norm)
cbar = plt.colorbar(cmesh)                      # draw colorbar
c1tks = np.arange(cmin, cmax+1e-10).astype(int) # positions of each tick
c1tkls = 2**c1tks                               # ticklabels
cbar.set_ticks(c1tks)                           # set tick positions
cbar.set_ticklabels(c1tkls)                     # set tick labels
cbar.set_label("Raw brightness")                # set colorbar title
plt.savefig("tiff_uint_12bit_logscale.png", bbox_inches="tight", pad_inches=0.02)