summaryrefslogtreecommitdiff
path: root/silx/gui/plot/actions/histogram.py
blob: f3e6370d501372127b9523eeebf6c1c470d66471 (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
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2004-2017 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.
#
# ###########################################################################*/
"""
:mod:`silx.gui.plot.actions.histogram` provides actions relative to histograms
for :class:`.PlotWidget`.

The following QAction are available:

- :class:`PixelIntensitiesHistoAction`
"""

from __future__ import division

__authors__ = ["V.A. Sole", "T. Vincent", "P. Knobel"]
__date__ = "10/10/2018"
__license__ = "MIT"

import numpy
import logging
import weakref

from .PlotToolAction import PlotToolAction
from silx.math.histogram import Histogramnd
from silx.math.combo import min_max
from silx.gui import qt
from silx.gui.plot import items

_logger = logging.getLogger(__name__)


class _LastActiveItem(qt.QObject):

    sigActiveItemChanged = qt.Signal(object, object)
    """Emitted when the active plot item have changed"""

    def __init__(self, parent, plot):
        assert plot is not None
        super(_LastActiveItem, self).__init__(parent=parent)
        self.__plot = weakref.ref(plot)
        self.__item = None
        item = self.__findActiveItem()
        self.setActiveItem(item)
        plot.sigActiveImageChanged.connect(self._activeImageChanged)
        plot.sigActiveScatterChanged.connect(self._activeScatterChanged)

    def getPlotWidget(self):
        return self.__plot()

    def __findActiveItem(self):
        plot = self.getPlotWidget()
        image = plot.getActiveImage()
        if image is not None:
            return image
        scatter = plot.getActiveScatter()
        if scatter is not None:
            return scatter

    def getActiveItem(self):
        if self.__item is None:
            return None
        item = self.__item()
        if item is None:
            self.__item = None
        return item

    def setActiveItem(self, item):
        previous = self.getActiveItem()
        if previous is item:
            return
        if item is None:
            self.__item = None
        else:
            self.__item = weakref.ref(item)
        self.sigActiveItemChanged.emit(previous, item)

    def _activeImageChanged(self, previous, current):
        """Handle active image change"""
        plot = self.getPlotWidget()
        item = plot.getImage(current)
        if item is None:
            self.setActiveItem(None)
        elif isinstance(item, items.ImageBase):
            self.setActiveItem(item)
        else:
            # Do not touch anything, which is consistent with silx v0.12 behavior
            pass

    def _activeScatterChanged(self, previous, current):
        """Handle active scatter change"""
        plot = self.getPlotWidget()
        item = plot.getScatter(current)
        self.setActiveItem(item)


class PixelIntensitiesHistoAction(PlotToolAction):
    """QAction to plot the pixels intensities diagram

    :param plot: :class:`.PlotWidget` instance on which to operate
    :param parent: See :class:`QAction`
    """

    def __init__(self, plot, parent=None):
        PlotToolAction.__init__(self,
                                plot,
                                icon='pixel-intensities',
                                text='pixels intensity',
                                tooltip='Compute image intensity distribution',
                                parent=parent)
        self._lastItemFilter = _LastActiveItem(self, plot)
        self._histo = None
        self._item = None

    def _connectPlot(self, window):
        self._lastItemFilter.sigActiveItemChanged.connect(self._activeItemChanged)
        item = self._lastItemFilter.getActiveItem()
        self._setSelectedItem(item)
        PlotToolAction._connectPlot(self, window)

    def _disconnectPlot(self, window):
        self._lastItemFilter.sigActiveItemChanged.disconnect(self._activeItemChanged)
        PlotToolAction._disconnectPlot(self, window)
        self._setSelectedItem(None)

    def _getSelectedItem(self):
        item = self._item
        if item is None:
            return None
        else:
            return item()

    def _activeItemChanged(self, previous, current):
        if self._isWindowInUse():
            self._setSelectedItem(current)

    def _setSelectedItem(self, item):
        if item is not None:
            if not isinstance(item, (items.ImageBase, items.Scatter)):
                # Filter out other things
                return

        old = self._getSelectedItem()
        if item is old:
            return
        if old is not None:
            old.sigItemChanged.disconnect(self._itemUpdated)
        if item is None:
            self._item = None
        else:
            self._item = weakref.ref(item)
            item.sigItemChanged.connect(self._itemUpdated)
        self.computeIntensityDistribution()

    def _itemUpdated(self, event):
        if event == items.ItemChangedType.DATA:
            self.computeIntensityDistribution()

    def _cleanUp(self):
        plot = self.getHistogramPlotWidget()
        try:
            plot.remove('pixel intensity', kind='item')
        except Exception:
            pass

    def computeIntensityDistribution(self):
        """Get the active image and compute the image intensity distribution
        """
        item = self._getSelectedItem()

        if item is None:
            self._cleanUp()
            return

        if isinstance(item, items.ImageBase):
            array = item.getData(copy=False)
            if array.ndim == 3:  # RGB(A) images
                _logger.info('Converting current image from RGB(A) to grayscale\
                    in order to compute the intensity distribution')
                array = (array[:, :, 0] * 0.299 +
                         array[:, :, 1] * 0.587 +
                         array[:, :, 2] * 0.114)
        elif isinstance(item, items.Scatter):
            array = item.getValueData(copy=False)
        else:
            assert(False)

        if array.size == 0:
            self._cleanUp()
            return

        xmin, xmax = min_max(array, min_positive=False, finite=True)
        nbins = min(1024, int(numpy.sqrt(array.size)))
        data_range = xmin, xmax

        # bad hack: get 256 bins in the case we have a B&W
        if numpy.issubdtype(array.dtype, numpy.integer):
            if nbins > xmax - xmin:
                nbins = xmax - xmin

        nbins = max(2, nbins)

        data = array.ravel().astype(numpy.float32)
        histogram = Histogramnd(data, n_bins=nbins, histo_range=data_range)
        assert len(histogram.edges) == 1
        self._histo = histogram.histo
        edges = histogram.edges[0]
        plot = self.getHistogramPlotWidget()
        plot.addHistogram(histogram=self._histo,
                          edges=edges,
                          legend='pixel intensity',
                          fill=True,
                          color='#66aad7')
        plot.resetZoom()

    def getHistogramPlotWidget(self):
        """Create the plot histogram if needed, otherwise create it

        :return: the PlotWidget showing the histogram of the pixel intensities
        """
        return self._getToolWindow()

    def _createToolWindow(self):
        from silx.gui.plot.PlotWindow import Plot1D
        window = Plot1D(parent=self.plot)
        window.setWindowFlags(qt.Qt.Window)
        window.setWindowTitle('Image Intensity Histogram')
        window.setDataMargins(0.1, 0.1, 0.1, 0.1)
        window.getXAxis().setLabel("Value")
        window.getYAxis().setLabel("Count")
        return window

    def getHistogram(self):
        """Return the last computed histogram

        :return: the histogram displayed in the HistogramPlotWiget
        """
        return self._histo