-
Notifications
You must be signed in to change notification settings - Fork 2
/
mpl_cmaps_in_ImageView.py
224 lines (181 loc) · 9.56 KB
/
mpl_cmaps_in_ImageView.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# MIT License
#
# Copyright (c) 2020 Sebastian Höfer
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
This is an example how to use an ImageView with Matplotlib Colormaps (cmap).
The function 'cmapToColormap' converts the Matplotlib format to the internal
format of PyQtGraph that is used in the GradientEditorItem. The function
itself has no dependencies on Matplotlib! Hence the weird if clauses with
'hasattr' instead of 'isinstance'.
The class 'MplCmapImageView' demonstrates, how to integrate converted
colormaps into a GradientEditorWidget. This is just monkey patched into the
class and should be implemented properly into the GradientEditorItem's
constructor. But this is one way to do it, if you don't want to touch your
PyQtGraph installation.
The 'main' block is just the modified 'ImageView' example from pyqtgraph.
"""
import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph
import collections
import matplotlib.cm
def cmapToColormap(cmap, nTicks=16):
"""
Converts a Matplotlib cmap to pyqtgraphs colormaps. No dependency on matplotlib.
Parameters:
*cmap*: Cmap object. Imported from matplotlib.cm.*
*nTicks*: Number of ticks to create when dict of functions is used. Otherwise unused.
"""
# Case #1: a dictionary with 'red'/'green'/'blue' values as list of ranges (e.g. 'jet')
# The parameter 'cmap' is a 'matplotlib.colors.LinearSegmentedColormap' instance ...
if hasattr(cmap, '_segmentdata'):
colordata = getattr(cmap, '_segmentdata')
if ('red' in colordata) and isinstance(colordata['red'], collections.Sequence):
# print("[cmapToColormap] RGB dicts with ranges")
# collect the color ranges from all channels into one dict to get unique indices
posDict = {}
for idx, channel in enumerate(('red', 'green', 'blue')):
for colorRange in colordata[channel]:
posDict.setdefault(colorRange[0], [-1, -1, -1])[idx] = colorRange[2]
indexList = list(posDict.keys())
indexList.sort()
# interpolate missing values (== -1)
for channel in range(3): # R,G,B
startIdx = indexList[0]
emptyIdx = []
for curIdx in indexList:
if posDict[curIdx][channel] == -1:
emptyIdx.append(curIdx)
elif curIdx != indexList[0]:
for eIdx in emptyIdx:
rPos = (eIdx - startIdx) / (curIdx - startIdx)
vStart = posDict[startIdx][channel]
vRange = (posDict[curIdx][channel] - posDict[startIdx][channel])
posDict[eIdx][channel] = rPos * vRange + vStart
startIdx = curIdx
del emptyIdx[:]
for channel in range(3): # R,G,B
for curIdx in indexList:
posDict[curIdx][channel] *= 255
posList = [[i, posDict[i]] for i in indexList]
return posList
# Case #2: a dictionary with 'red'/'green'/'blue' values as functions (e.g. 'gnuplot')
elif ('red' in colordata) and isinstance(colordata['red'], collections.Callable):
# print("[cmapToColormap] RGB dict with functions")
indices = np.linspace(0., 1., nTicks)
luts = [np.clip(np.array(colordata[rgb](indices), dtype=np.float), 0, 1) * 255 \
for rgb in ('red', 'green', 'blue')]
return list(zip(indices, list(zip(*luts))))
# If the parameter 'cmap' is a 'matplotlib.colors.ListedColormap' instance, with the attributes 'colors' and 'N'
elif hasattr(cmap, 'colors') and hasattr(cmap, 'N'):
colordata = getattr(cmap, 'colors')
# Case #3: a list with RGB values (e.g. 'seismic')
if len(colordata[0]) == 3:
# print("[cmapToColormap] list with RGB values")
indices = np.linspace(0., 1., len(colordata))
scaledRgbTuples = [(rgbTuple[0] * 255, rgbTuple[1] * 255, rgbTuple[2] * 255) for rgbTuple in colordata]
return list(zip(indices, scaledRgbTuples))
# Case #4: a list of tuples with positions and RGB-values (e.g. 'terrain')
# -> this section is probably not needed anymore!?
elif len(colordata[0]) == 2:
# print("[cmapToColormap] list with positions and RGB-values. Just scale the values.")
scaledCmap = [(idx, (vals[0] * 255, vals[1] * 255, vals[2] * 255)) for idx, vals in colordata]
return scaledCmap
# Case #X: unknown format or datatype was the wrong object type
else:
raise ValueError("[cmapToColormap] Unknown cmap format or not a cmap!")
class MplCmapImageView(pyqtgraph.ImageView):
def __init__(self, additionalCmaps=[], setColormap=None, **kargs):
super(MplCmapImageView, self).__init__(**kargs)
self.gradientEditorItem = self.ui.histogram.item.gradient
self.activeCm = "grey"
self.mplCmaps = {}
if len(additionalCmaps) > 0:
self.registerCmap(additionalCmaps)
if setColormap is not None:
self.gradientEditorItem.restoreState(setColormap)
def registerCmap(self, cmapNames):
""" Add matplotlib cmaps to the GradientEditors context menu"""
self.gradientEditorItem.menu.addSeparator()
savedLength = self.gradientEditorItem.length
self.gradientEditorItem.length = 100
# iterate over the list of cmap names and check if they're avaible in MPL
for cmapName in cmapNames:
if not hasattr(matplotlib.cm, cmapName):
print('[MplCmapImageView] Unknown cmap name: \'{}\'. Your Matplotlib installation might be outdated.'.format(cmapName))
else:
# create a Dictionary just as the one at the top of GradientEditorItem.py
cmap = getattr(matplotlib.cm, cmapName)
self.mplCmaps[cmapName] = {'ticks': cmapToColormap(cmap), 'mode': 'rgb'}
# Create the menu entries
# The following code is copied from pyqtgraph.ImageView.__init__() ...
px = QtGui.QPixmap(100, 15)
p = QtGui.QPainter(px)
self.gradientEditorItem.restoreState(self.mplCmaps[cmapName])
grad = self.gradientEditorItem.getGradient()
brush = QtGui.QBrush(grad)
p.fillRect(QtCore.QRect(0, 0, 100, 15), brush)
p.end()
label = QtGui.QLabel()
label.setPixmap(px)
label.setContentsMargins(1, 1, 1, 1)
act = QtGui.QWidgetAction(self.gradientEditorItem)
act.setDefaultWidget(label)
act.triggered.connect(self.cmapClicked)
act.name = cmapName
self.gradientEditorItem.menu.addAction(act)
self.gradientEditorItem.length = savedLength
def cmapClicked(self, b=None):
"""onclick handler for our custom entries in the GradientEditorItem's context menu"""
act = self.sender()
self.gradientEditorItem.restoreState(self.mplCmaps[act.name])
self.activeCm = act.name
## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
app = QtGui.QApplication([])
## Create window with ImageView widget
win = QtGui.QMainWindow()
win.resize(800,800)
# Instantiate the modified ImageView class ...
# imv = pyqtgraph.ImageView()
imv = MplCmapImageView(additionalCmaps=['jet', 'viridis', 'seismic', 'cubehelix'])
win.setCentralWidget(imv)
win.show()
win.setWindowTitle('pyqtgraph example: ImageView')
## Create random 3D data set with noisy signals
img = pyqtgraph.gaussianFilter(np.random.normal(size=(200, 200)), (5, 5)) * 20 + 100
img = img[np.newaxis,:,:]
decay = np.exp(-np.linspace(0,0.3,100))[:,np.newaxis,np.newaxis]
data = np.random.normal(size=(100, 200, 200))
data += img * decay
data += 2
## Add time-varying signal
sig = np.zeros(data.shape[0])
sig[30:] += np.exp(-np.linspace(1,10, 70))
sig[40:] += np.exp(-np.linspace(1,10, 60))
sig[70:] += np.exp(-np.linspace(1,10, 30))
sig = sig[:,np.newaxis,np.newaxis] * 3
data[:,50:60,50:60] += sig
## Display the data and assign each frame a time value from 1.0 to 3.0
imv.setImage(data, xvals=np.linspace(1., 3., data.shape[0]))
QtGui.QApplication.instance().exec_()