Search code examples
pythonimagebokehrgbimshow

How do I display a TIFF image in Bokeh?


I can load a TIFF image into memory as a NumPy array where each pixel is represented by a 3-element RGB vector:

from PIL import Image
import numpy as np
arr=np.array(Image.open(imgfn))

For example the arr above might have shape (2469,2858,3).

Follow the Bokeh docs, in Bokeh, pixels are 1D numbers that are interpreted with respect to a color map.

How do I map my 3D RGB TIFF array into a 1D Bokeh colormap index array, and what colormap should I use?

This post suggest I should write something called an RGBAColorMapper. How do I do that?

There is also something call image_rgba which is a 4D pixel, how would I translate 3D pixels to 4D to use that?

Basically I'm looking for the same functionality as MatPlotLib imshow.


Solution

  • You can convert a tiff image to rgba using the PIL package. It is then straightforward to plot this with image_rgba. The tiff file was downloaded from http://www-eng-x.llnl.gov/documents/tests/tiff.html, following the SO answer posted here.

    import numpy
    
    from PIL import Image
    from bokeh.plotting import figure, show
    
    im = Image.open('a_image.tif')
    im = im.convert("RGBA")
    # uncomment to compare
    #im.show()
    imarray = numpy.array(im)
    
    p = figure(x_range=(0,10), y_range=(0,1), width=1000, height=200)
    
    p.image_rgba(image=[imarray], x=0, y=0, dw=10, dh=1)
    
    show(p)
    

    enter image description here