Skip to content

Instantly share code, notes, and snippets.

@ChrisBeaumont
Created November 6, 2012 16:30
Show Gist options
  • Save ChrisBeaumont/4025831 to your computer and use it in GitHub Desktop.
Save ChrisBeaumont/4025831 to your computer and use it in GitHub Desktop.
convert matplotlib colormap to Qt4 pixmap
from matplotlib import cm
import numpy as np
from PyQt4.QtGui import QImage, QPixmap, QColor
def cmap2pixmap(cmap, steps=50):
"""Convert a maplotlib colormap into a QPixmap
:param cmap: The colormap to use
:type cmap: Matplotlib colormap instance (e.g. matplotlib.cm.gray)
:param steps: The number of color steps in the output. Default=50
:type steps: int
:rtype: QPixmap
"""
sm = cm.ScalarMappable(cmap=cmap)
sm.norm.vmin = 0.0
sm.norm.vmax = 1.0
inds = np.linspace(0, 1, steps)
rgbas = sm.to_rgba(inds)
rgbas = [QColor(int(r * 255), int(g * 255),
int(b * 255), int(a * 255)).rgba() for r, g, b, a in rgbas]
im = QImage(steps, 1, QImage.Format_Indexed8)
im.setColorTable(rgbas)
for i in range(steps):
im.setPixel(i, 0, i)
im = im.scaled(100, 100)
pm = QPixmap.fromImage(im)
return pm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment