How to use Matplotlib color map in an image

327 views
Skip to first unread message

Gene Beidl

unread,
Sep 11, 2019, 11:09:59 AM9/11/19
to pyqtgraph
I am creating a spectrogram to be displayed as an image and I want to use the magma colormap from Matplotlib.

It's shown here:

And some 'magma' mapped spectrograms are here:

Is there a way to use Matplotlib colormaps with an image in pyqtgraph?

Thanks!


Patrick

unread,
Sep 11, 2019, 10:17:30 PM9/11/19
to pyqtgraph
Hi,

You can set your own custom tick colors and positions on a colormap bar with something like this:

cbar = pg.HistogramLUTItem(image=some_image)
cbar
.gradient.restoreState({"mode": "rgb", "ticks":
   
[(0.0, (0.374272, 0.119296, 3.549696)),
   
(0.125, (28.952064, 16.765952, 70.856704)),
   
(0.25, (81.063424, 18.35264, 124.25728)),
   
(0.375, (131.284736, 37.933824, 129.957888)),
   
(0.5, (183.395072, 55.035392, 121.67424)),
   
(0.625, (231.495936, 81.82016, 99.363072)),
   
(0.75, (252.5952, 137.108992, 97.84576)),
   
(0.875, (255.205888, 197.015296, 136.932352))]})

Those tick positions should be a decent copy of magma, which I created with

from matplotlib import cm
ticks
= [(i/256, tuple([256*j for j in cm.magma.colors[i]])) for i in range(0, cm.magma.N, 32)]

Patrick
Message has been deleted

Gene Beidl

unread,
Sep 12, 2019, 1:15:37 PM9/12/19
to pyqtgraph
 Great, thank you Patrick!

Erik J

unread,
Sep 26, 2019, 8:09:26 PM9/26/19
to pyqtgraph
Hi Gene,

Here is a simple function I use to convert mpl colormaps to pyqtgraph form:

import numpy as np
from matplotlib import cm

def colormap(name):
    colormap = cm.get_cmap(name)
    colormap._init()
    # Convert matplotlib colormap from 0-1 to 0-255 for PyQtGraph
    lut = (colormap._lut * 255).view(np.ndarray)[:colormap.N] 
    return lut

You can easily use it to set your colormap in pyqtgraph as follows:

         img.setLookupTable(lut)

where img is a PyQtGraph ImageItem. The truncation of the colormap ("[:colormap.N]") keeps only the portion with the colors. mpl has a few extra entries at the top of the colormap that don't work with pyqtgraph.  I got the function originally from somewhere in these group postings but I can no longer find it. I added the truncation part. This works well for me as I display both mpl and pyqtgraph images in a single Qt window.

Hope this helps,
Erik
Message has been deleted

Gene Beidl

unread,
Sep 29, 2019, 9:31:07 AM9/29/19
to pyqtgraph
Great, thank you Eric!
Reply all
Reply to author
Forward
0 new messages