Created
November 6, 2012 16:30
-
-
Save ChrisBeaumont/4025831 to your computer and use it in GitHub Desktop.
convert matplotlib colormap to Qt4 pixmap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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