-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot2D.py
More file actions
264 lines (210 loc) · 9.46 KB
/
Copy pathplot2D.py
File metadata and controls
264 lines (210 loc) · 9.46 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import sys
import logging
from collections import OrderedDict
import numpy as np
from silx.gui import qt
from silx.gui import icons
import silx
from silx.gui.plot import PlotWindow
from silx.gui.plot.items.roi import RectangleROI
from silx.gui.plot import items
from silx.gui.plot.tools.roi import RegionOfInterestManager
# from silx.gui.plot.Profile import ProfileToolBar
from Profile import MyProfileToolBar as ProfileToolBar
from silx.utils.weakref import WeakMethodProxy
from actions import SaveAction, CopyAction
logger = logging.getLogger(__name__)
class PlotWindowCustom(PlotWindow):
"""PlotWindow with a toolbar specific for images.
This widgets provides the plot API of :~:`.PlotWidget`.
:param parent: The parent of this widget
:param backend: The backend to use for the plot (default: matplotlib).
See :class:`.PlotWidget` for the list of supported backend.
:type backend: str or :class:`BackendBase.BackendBase`
"""
def __init__(self, parent=None, backend=None):
# List of information to display at the bottom of the plot
posInfo = [
('X', lambda x, y: x),
('Y', lambda x, y: y),
('Data', WeakMethodProxy(self._getImageValue)),
('Dims', WeakMethodProxy(self._getImageDims)),
]
super(PlotWindowCustom, self).__init__(parent=parent, backend=backend,
resetzoom=True, autoScale=False,
logScale=False, grid=False,
curveStyle=False, colormap=True,
aspectRatio=True, yInverted=True,
copy=False, save=False, print_=False,
control=True, position=posInfo,
roi=False, mask=False)
if parent is None:
self.setWindowTitle('Plot2D')
self.getXAxis().setLabel('Columns')
self.getYAxis().setLabel('Rows')
if silx.config.DEFAULT_PLOT_IMAGE_Y_AXIS_ORIENTATION == 'downward':
self.getYAxis().setInverted(True)
self.profile = ProfileToolBar(plot=self)
self.addToolBar(self.profile)
self.colorbarAction.setVisible(True)
self.getColorBarWidget().setVisible(True)
# Put colorbar action after colormap action
actions = self.toolBar().actions()
for action in actions:
if action is self.getColormapAction():
break
self.sigActiveImageChanged.connect(self.__activeImageChanged)
def __activeImageChanged(self, previous, legend):
"""Handle change of active image
:param Union[str,None] previous: Legend of previous active image
:param Union[str,None] legend: Legend of current active image
"""
if previous is not None:
item = self.getImage(previous)
if item is not None:
item.sigItemChanged.disconnect(self.__imageChanged)
if legend is not None:
item = self.getImage(legend)
item.sigItemChanged.connect(self.__imageChanged)
positionInfo = self.getPositionInfoWidget()
if positionInfo is not None:
positionInfo.updateInfo()
def __imageChanged(self, event):
"""Handle update of active image item
:param event: Type of changed event
"""
if event == items.ItemChangedType.DATA:
positionInfo = self.getPositionInfoWidget()
if positionInfo is not None:
positionInfo.updateInfo()
def _getImageValue(self, x, y):
"""Get status bar value of top most image at position (x, y)
:param float x: X position in plot coordinates
:param float y: Y position in plot coordinates
:return: The value at that point or '-'
"""
pickedMask = None
for picked in self.pickItems(
*self.dataToPixel(x, y, check=False),
lambda item: isinstance(item, items.ImageBase)):
if isinstance(picked.getItem(), items.MaskImageData):
if pickedMask is None: # Use top-most if many masks
pickedMask = picked
else:
image = picked.getItem()
indices = picked.getIndices(copy=False)
if indices is not None:
row, col = indices[0][0], indices[1][0]
value = image.getData(copy=False)[row, col]
if pickedMask is not None: # Check if masked
maskItem = pickedMask.getItem()
indices = pickedMask.getIndices()
row, col = indices[0][0], indices[1][0]
if maskItem.getData(copy=False)[row, col] != 0:
return value, "Masked"
return value
return '-' # No image picked
def _getImageDims(self, *args):
activeImage = self.getActiveImage()
if (activeImage is not None and
activeImage.getData(copy=False) is not None):
dims = activeImage.getData(copy=False).shape[1::-1]
return 'x'.join(str(dim) for dim in dims)
else:
return '-'
def getProfileToolbar(self):
"""Profile tools attached to this plot
See :class:`silx.gui.plot.Profile.ProfileToolBar`
"""
return self.profile
def getProfilePlot(self):
"""Return plot window used to display profile curve.
:return: :class:`Plot1D`
"""
return self.profile.getProfilePlot()
class Plot2D(PlotWindowCustom):
"""Customized silx.gui.plot.PlotWindow.Plot2D window for roi selection
:param parent: The parent of this widget
:param backend: The backend to use for the plot (default: matplotlib).
See :class:`.PlotWidget` for the list of supported backend.
"""
sigRoiUpdated = qt.Signal(object, object)
def __init__(self, parent=None, backend='gl'):
super().__init__(parent=parent, backend=backend)
self.fitImage = None
# ROI manager
self._roiManager = RegionOfInterestManager(self)
# Adjust margins
self.setAxesMargins(0.05, 0.05, 0.05, 0.05)
# Create default ROI
self._roi = RectangleROI()
self._roi.setGeometry(origin=(640, 640), size=(200, 200))
self._roi.setName('ROI')
self._roi.setEditable(True)
self._roi.setVisible(False)
self._roi.sigEditingFinished.connect(self.updateRoiRegion)
self._roiManager.addRoi(self._roi)
# Set tif as default selection on save action
try:
# create new saveAction
saveAction = SaveAction(parent=self._outputToolBar, plot=self)
self._outputToolBar._saveAction = saveAction
self._outputToolBar.addAction(saveAction)
# New copy action
copyAction = CopyAction(parent=self._outputToolBar, plot=self)
self._outputToolBar._copyAction = copyAction
self._outputToolBar.addAction(copyAction)
except Exception as ex:
print("Exception occured customizing SaveAction in Plot2D : {}".format(ex))
def toggleROI(self, checked):
"""Show/Hide ROI"""
self._roi.setVisible(checked)
def getRoi(self):
"""Return RectangleROI"""
return self._roi
def setRoiEditable(self, value=True):
"""Change editing mode of roi"""
editable = self.getRoi().isEditable()
if editable != value:
self.getRoi().setEditable(value)
def updateRoiRegion(self):
"""Emit orgin and size signal when the ROI selection updated"""
origin = np.array(self._roi.getOrigin()).astype(int)
size = np.array(self._roi.getSize()).astype(int)
# print("origin : {}, size : {}".format(origin, size))
self.sigRoiUpdated.emit(origin, size)
def _getImageValue(self, x, y):
"""Get status bar value of top most image at position (x, y)
:param float x: X position in plot coordinates
:param float y: Y position in plot coordinates
:return: The value at that point or '-'
"""
pickedMask = None
for picked in self.pickItems(
*self.dataToPixel(x, y, check=False),
lambda item: isinstance(item, items.ImageBase)):
if isinstance(picked.getItem(), items.MaskImageData):
if pickedMask is None: # Use top-most if many masks
pickedMask = picked
else:
image = picked.getItem()
indices = picked.getIndices(copy=False)
if indices is not None:
row, col = indices[0][0], indices[1][0]
value = image.getData(copy=False)[row, col]
if isinstance(value, np.ndarray):
if self.fitImage is not None:
value = self.fitImage[row, col]
if pickedMask is not None: # Check if masked
maskItem = pickedMask.getItem()
indices = pickedMask.getIndices()
row, col = indices[0][0], indices[1][0]
if maskItem.getData(copy=False)[row, col] != 0:
return value, "Masked"
return value
return '-' # No image picked
if __name__ == '__main__':
app = qt.QApplication([])
plot = Plot2D()
plot.show()
sys.exit(app.exec_())