summaryrefslogtreecommitdiff
path: root/examples/plotInteractiveImageROI.py
blob: 7254b7eac69e58af81ce0601a7aa38c41d2d4ea9 (plain)
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
#!/usr/bin/env python
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2018-2020 European Synchrotron Radiation Facility
#
# 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 script illustrates image ROI selection in a :class:`~silx.gui.plot.PlotWidget`

It uses :class:`~silx.gui.plot.tools.roi.RegionOfInterestManager` and
:class:`~silx.gui.plot.tools.roi.RegionOfInterestTableWidget` to handle the
interactive ROI selection and to display the list of ROIs.
"""

import sys
import numpy

from silx.gui import qt
from silx.gui.plot import Plot2D
from silx.gui.plot.tools.roi import RegionOfInterestManager
from silx.gui.plot.tools.roi import RegionOfInterestTableWidget
from silx.gui.plot.tools.roi import RoiModeSelectorAction
from silx.gui.plot.items.roi import RectangleROI
from silx.gui.plot.items import LineMixIn, SymbolMixIn
from silx.gui.plot.actions import control as control_actions


def dummy_image():
    """Create a dummy image"""
    x = numpy.linspace(-1.5, 1.5, 1024)
    xv, yv = numpy.meshgrid(x, x)
    signal = numpy.exp(- (xv ** 2 / 0.15 ** 2 + yv ** 2 / 0.25 ** 2))
    # add noise
    signal += 0.3 * numpy.random.random(size=signal.shape)
    return signal


app = qt.QApplication([])  # Start QApplication

# Create the plot widget and add an image
plot = Plot2D()
plot.getDefaultColormap().setName('viridis')
plot.setKeepDataAspectRatio(True)
plot.addImage(dummy_image())

toolbar = qt.QToolBar()
toolbar.addAction(control_actions.OpenGLAction(parent=toolbar, plot=plot))
plot.addToolBar(toolbar)

# Create the object controlling the ROIs and set it up
roiManager = RegionOfInterestManager(plot)
roiManager.setColor('pink')  # Set the color of ROI


# Set the name of each created region of interest
def updateAddedRegionOfInterest(roi):
    """Called for each added region of interest: set the name"""
    if roi.getName() == '':
        roi.setName('ROI %d' % len(roiManager.getRois()))
    if isinstance(roi, LineMixIn):
        roi.setLineWidth(1)
        roi.setLineStyle('--')
    if isinstance(roi, SymbolMixIn):
        roi.setSymbolSize(5)
    roi.setSelectable(True)
    roi.setEditable(True)


roiManager.sigRoiAdded.connect(updateAddedRegionOfInterest)


# Add a rectangular region of interest
roi = RectangleROI()
roi.setGeometry(origin=(50, 50), size=(200, 200))
roi.setName('Initial ROI')
roiManager.addRoi(roi)

# Create the table widget displaying
roiTable = RegionOfInterestTableWidget()
roiTable.setRegionOfInterestManager(roiManager)

# Create a toolbar containing buttons for all ROI 'drawing' modes
roiToolbar = qt.QToolBar()  # The layout to store the buttons
roiToolbar.setIconSize(qt.QSize(16, 16))

for roiClass in roiManager.getSupportedRoiClasses():
    # Create a tool button and associate it with the QAction of each mode
    action = roiManager.getInteractionModeAction(roiClass)
    roiToolbar.addAction(action)

class AutoHideToolBar(qt.QToolBar):
    """A toolbar which hide itself if no actions are visible"""

    def actionEvent(self, event):
        if event.type() == qt.QEvent.ActionChanged:
            self._updateVisibility()
        return qt.QToolBar.actionEvent(self, event)

    def _updateVisibility(self):
        visible = False
        for action in self.actions():
            if action.isVisible():
                visible = True
                break
        self.setVisible(visible)

roiToolbarEdit = AutoHideToolBar()
modeSelectorAction = RoiModeSelectorAction()
modeSelectorAction.setRoiManager(roiManager)
roiToolbarEdit.addAction(modeSelectorAction)

# Add the region of interest table and the buttons to a dock widget
widget = qt.QWidget()
layout = qt.QVBoxLayout()
widget.setLayout(layout)
layout.addWidget(roiToolbar)
layout.addWidget(roiToolbarEdit)
layout.addWidget(roiTable)


def roiDockVisibilityChanged(visible):
    """Handle change of visibility of the roi dock widget

    If dock becomes hidden, ROI interaction is stopped.
    """
    if not visible:
        roiManager.stop()


dock = qt.QDockWidget('Image ROI')
dock.setWidget(widget)
dock.visibilityChanged.connect(roiDockVisibilityChanged)
plot.addTabbedDockWidget(dock)

# Show the widget and start the application
plot.show()
result = app.exec_()
app.deleteLater()
sys.exit(result)