noiseRemovalWidget.py 18.2 KB
Newer Older
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-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.
#
# ###########################################################################*/


__authors__ = ["J. Garriga"]
__license__ = "MIT"
29
__date__ = "09/02/2021"
30

31
32
import logging

33
34
35
36
from silx.gui import qt
from silx.gui.colors import Colormap
from silx.gui.plot.StackView import StackViewMainWindow

37
import darfix
38
from darfix.core.dataset import Operation
39
from darfix.core.imageOperations import Method
40
41
42

from .operationThread import OperationThread

43
44
_logger = logging.getLogger(__file__)

45

46
class _ParametersDock(qt.QDockWidget):
47
48

    def __init__(self, parent=None):
49
        """
50
        Dock widget containing the input parameters for the noise removal operations.
51
52
53
        """
        qt.QDockWidget.__init__(self, parent)
        widget = qt.QWidget()
54
        self.layout = qt.QGridLayout()
55
56

        # Background subtraction
57
        bsLabel = qt.QLabel("Background Substraction")
58
        # Font for operations titles
59
60
61
        font = qt.QFont()
        font.setBold(True)
        bsLabel.setFont(font)
62
        self.layout.addWidget(bsLabel, 0, 0, 1, 2)
63
        self.bsMethodsCB = qt.QComboBox(self)
64
        for method in Method.values():
65
66
67
            self.bsMethodsCB.addItem(method)
        self.bsBackgroundCB = qt.QComboBox(self)
        self.computeBS = qt.QPushButton("Compute")
68
69
        self.abortBS = qt.QPushButton("Abort")
        self.abortBS.hide()
70
71
        methodLabel = qt.QLabel("Method:")
        bgLabel = qt.QLabel("Background:")
72
        methodLabel.setMargin(0)
73
74
75
76
        # Step widget
        self.stepWidget = qt.QWidget()
        stepLayout = qt.QHBoxLayout()
        stepLayout.addWidget(qt.QLabel("Step:"))
77
        self.step = qt.QLineEdit("1")
78
79
        self.step.setSizePolicy(qt.QSizePolicy.Ignored, qt.QSizePolicy.Preferred)
        stepLayout.setContentsMargins(0, 0, 0, 0)
80
81
82
        stepLayout.addWidget(self.step)
        self.stepWidget.setLayout(stepLayout)
        # Chunks widget
83
84
85
86
87
88
89
90
91
92
        self.chunksWidget = qt.QWidget()
        chunksLayout = qt.QHBoxLayout()
        chunksLabel = qt.QLabel("Chunks:")
        self.verticalChunkSize = qt.QLineEdit("100")
        self.verticalChunkSize.setValidator(qt.QIntValidator())
        self.horizontalChunkSize = qt.QLineEdit("100")
        self.horizontalChunkSize.setValidator(qt.QIntValidator())
        chunksLayout.addWidget(chunksLabel)
        chunksLayout.addWidget(self.verticalChunkSize)
        chunksLayout.addWidget(self.horizontalChunkSize)
93
        chunksLayout.setContentsMargins(0, 0, 0, 0)
94
        self.chunksWidget.setLayout(chunksLayout)
95

96
        self.inDiskCheckbox = qt.QCheckBox("Use chunks to compute median")
97
98
99
100
        self.inDiskWidget = qt.QWidget()
        inDiskLayout = qt.QVBoxLayout()
        inDiskLayout.addWidget(self.stepWidget)
        inDiskLayout.addWidget(self.chunksWidget)
101
        inDiskLayout.addWidget(self.inDiskCheckbox, alignment=qt.Qt.AlignRight)
102
        self.chunksWidget.hide()
103
        self.inDiskCheckbox.stateChanged.connect(self._toggleChunks)
104
        inDiskLayout.setContentsMargins(0, 0, 0, 0)
105
106
        self.inDiskWidget.setLayout(inDiskLayout)

107
108
        self.layout.addWidget(methodLabel, 1, 0, 1, 1)
        self.layout.addWidget(bgLabel, 2, 0, 1, 1)
109
110
        self.layout.addWidget(self.bsMethodsCB, 1, 1, 1, 1)
        self.layout.addWidget(self.bsBackgroundCB, 2, 1, 1, 1)
111
        self.layout.addWidget(self.inDiskWidget, 3, 0, 1, 2)
112
113
114
115
        self.layout.addWidget(self.computeBS, 4, 1, 1, 1)
        self.layout.addWidget(self.abortBS, 4, 0, 1, 1)
        self.computeBS.hide()
        self.abortBS.hide()
116
        self.inDiskWidget.hide()
117
118
119
        # Hot pixel removal
        hpLabel = qt.QLabel("Hot Pixel Removal")
        hpLabel.setFont(font)
120
        self.layout.addWidget(hpLabel, 0, 2, 1, 2)
121
        ksizeLabel = qt.QLabel("Kernel size:")
122
        self.layout.addWidget(ksizeLabel, 1, 2, 1, 1)
123
124
125
126
        self.hpSizeCB = qt.QComboBox(self)
        self.hpSizeCB.addItem("3")
        self.hpSizeCB.addItem("5")
        self.computeHP = qt.QPushButton("Compute")
127
        self.abortHP = qt.QPushButton("Abort")
128
        self.layout.addWidget(self.hpSizeCB, 1, 3, 1, 1)
129
130
        self.layout.addWidget(self.computeHP, 4, 3, 1, 1)
        self.layout.addWidget(self.abortHP, 4, 2, 1, 1)
131
        self.computeHP.hide()
132
        self.abortHP.hide()
133
134
135
        # Threshold removal
        tpLabel = qt.QLabel("Threshold Removal")
        tpLabel.setFont(font)
136
        self.layout.addWidget(tpLabel, 0, 4, 1, 2)
137
        bottomLabel = qt.QLabel("Bottom threshold:")
138
        self.layout.addWidget(bottomLabel, 1, 4, 1, 1)
139
140
141
142
143
        self.bottomLE = qt.QLineEdit("0")
        self.bottomLE.setValidator(qt.QIntValidator())
        self.bottomLE.setSizePolicy(qt.QSizePolicy.Ignored, qt.QSizePolicy.Preferred)
        self.computeTP = qt.QPushButton("Compute")
        self.abortTP = qt.QPushButton("Abort")
144
        self.layout.addWidget(self.bottomLE, 1, 5, 1, 1)
145
146
        self.layout.addWidget(self.computeTP, 4, 5, 1, 1)
        self.layout.addWidget(self.abortTP, 4, 4, 1, 1)
147
148
        self.computeTP.hide()
        self.abortTP.hide()
149

150
        self.layout.setHorizontalSpacing(10)
151
        widget.setLayout(self.layout)
152
153
        self.setWidget(widget)

154
    def _toggleChunks(self, checked):
155
156
157
158
        widgets = [self.chunksWidget, self.stepWidget]

        widgets[1 if checked else 0].hide()
        widgets[0 if checked else 1].show()
159

160
161

class NoiseRemovalDialog(qt.QDialog):
Julia Garriga Ferrer's avatar
Docs    
Julia Garriga Ferrer committed
162
163
164
    """
    Dialog with `NoiseRemovalWidget` as main window and standard buttons.
    """
165
166
167
168
169
170
171

    okSignal = qt.Signal()

    def __init__(self, parent=None):
        qt.QDialog.__init__(self, parent)
        self.setWindowFlags(qt.Qt.Widget)
        types = qt.QDialogButtonBox.Ok
172
173
174
175
        self._buttons = qt.QDialogButtonBox(parent=self)
        self._buttons.setStandardButtons(types)
        self._buttons.setEnabled(False)
        resetB = self._buttons.addButton(self._buttons.Reset)
176
177
178
179
        self.mainWindow = NoiseRemovalWidget(parent=self)
        self.mainWindow.setAttribute(qt.Qt.WA_DeleteOnClose)
        self.setLayout(qt.QVBoxLayout())
        self.layout().addWidget(self.mainWindow)
180
        self.layout().addWidget(self._buttons)
181

182
        self._buttons.accepted.connect(self.okSignal.emit)
183
        resetB.clicked.connect(self.mainWindow.resetStack)
184
        self.mainWindow.computingSignal.connect(self._toggleButton)
185

186
187
188
189
190
191
    def setDataset(self, dataset, indices=None, bg_indices=None, bg_dataset=None):

        if dataset is not None:
            self._buttons.setEnabled(True)
            self.mainWindow.setDataset(dataset, indices, bg_indices, bg_dataset)

192
193
194
    def _toggleButton(self, state):
        self._buttons.button(qt.QDialogButtonBox.Ok).setEnabled(not state)

195
196
197

class NoiseRemovalWidget(qt.QMainWindow):
    """
198
    Widget to apply noise removal from a dataset.
Julia Garriga Ferrer's avatar
Docs    
Julia Garriga Ferrer committed
199
    For now it can apply both background subtraction and hot pixel removal.
200
201
202
    For background subtraction the user can choose the background to use:
    dark frames, low intensity data or all the data. From these background
    frames, an image is computed either using the mean or the median.
203
204
    """

205
206
    computingSignal = qt.Signal(bool)

207
208
209
    def __init__(self, parent=None):
        qt.QMainWindow.__init__(self, parent)

210
211
212
213
        self._update_dataset = None
        self.indices = None
        self.bg_indices = None
        self.bg_dataset = None
214
215
216
        self.setWindowFlags(qt.Qt.Widget)

        self._parametersDock = _ParametersDock()
217
        self._parametersDock.setFeatures(qt.QDockWidget.DockWidgetMovable)
218
        self._sv = StackViewMainWindow()
219
        self._sv.setColormap(Colormap(name=darfix.config.DEFAULT_COLORMAP_NAME,
220
                                      normalization=darfix.config.DEFAULT_COLORMAP_NORM))
221

222
223
        self._size = None
        self._method = None
224
        self._background = self._parametersDock.bsBackgroundCB.currentText()
225
        self._bottom_threshold = self._parametersDock.bottomLE.text()
226
227
228
        self._step = self._parametersDock.step.text()
        self._chunks = [int(self._parametersDock.verticalChunkSize.text()),
                        int(self._parametersDock.horizontalChunkSize.text())]
229
        self.setCentralWidget(self._sv)
230
        self.addDockWidget(qt.Qt.BottomDockWidgetArea, self._parametersDock)
231

232
233
234
235
236
237
238
239
240
241
        # Add connections
        self._parametersDock.computeBS.clicked.connect(self.__computeBS)
        self._parametersDock.computeHP.clicked.connect(self.__computeHP)
        self._parametersDock.computeTP.clicked.connect(self.__computeTP)
        self._parametersDock.abortBS.clicked.connect(self.__abortBS)
        self._parametersDock.abortHP.clicked.connect(self.__abortHP)
        self._parametersDock.abortTP.clicked.connect(self.__abortTP)
        self._parametersDock.bsMethodsCB.currentTextChanged.connect(self._toggleMethod)
        self._parametersDock.bsBackgroundCB.currentIndexChanged.connect(self._toggleInDiskWidget)

242
243
244
245
246
247
248
249
250
251
252
253
254
    def setDataset(self, dataset, indices=None, bg_indices=None, bg_dataset=None):
        """
        Dataset setter. Saves the dataset and updates the stack with the dataset
        data

        :param Dataset dataset: dataset
        """
        self.dataset = dataset
        self._update_dataset = dataset
        self.indices = indices
        self.setStack()
        self.bg_indices = bg_indices
        self.bg_dataset = bg_dataset
255

256
        self._parametersDock.computeBS.show()
257
        self._parametersDock.computeHP.show()
258
        self._parametersDock.computeTP.show()
259
260
261
262
263
264
265
266
267
268
269

        """
        Sets the available background for the user to choose.
        """
        self._parametersDock.bsBackgroundCB.clear()
        if bg_dataset is not None:
            self._parametersDock.bsBackgroundCB.addItem("Dark data")
        if bg_indices is not None:  # TODO: modify
            self._parametersDock.bsBackgroundCB.addItem("Low intensity data")
        self._parametersDock.bsBackgroundCB.addItem("Data")

270
271
272
    def __computeBS(self):
        """
        Function that starts the thread to compute the background
273
        subtraction.
274
        """
275
276
        self._background = self._parametersDock.bsBackgroundCB.currentText()
        if self._background == "Dark data":
277
            bg = self.bg_dataset
278
        elif self._background == "Low intensity data":
279
            bg = self.bg_indices
280
281
282
        else:
            bg = None

283
284
        self._chunks = None
        self._step = None
285
286
        if self._parametersDock.inDiskWidget.isVisible():
            if self._parametersDock.inDiskCheckbox.isChecked():
287
288
                self._chunks = [int(self._parametersDock.verticalChunkSize.text()),
                                int(self._parametersDock.horizontalChunkSize.text())]
289
            else:
290
                self._step = int(self._parametersDock.step.text())
291
292
293

        self._thread = OperationThread(self, self._update_dataset.apply_background_subtraction)
        self._method = self._parametersDock.bsMethodsCB.currentText()
294
        self._thread.setArgs(bg, self._method, self.indices, self._step, self._chunks)
295
        self._thread.finished.connect(self._updateData)
296
297
        if not self._update_dataset.in_memory:
            self._parametersDock.abortBS.show()
298
        self._thread.start()
299
        self._setComputingState(True)
300
301
302
303
304
305

    def __computeHP(self):
        """
        Function that starts the thread to compute the hot pixel
        removal.
        """
306
        self._size = self._parametersDock.hpSizeCB.currentText()
307
        self._thread = OperationThread(self, self._update_dataset.apply_hot_pixel_removal)
308
        self._thread.setArgs(int(self._size), self.indices)
309
        self._thread.finished.connect(self._updateData)
310
311
        if not self._update_dataset.in_memory:
            self._parametersDock.abortHP.show()
312
        self._thread.start()
313
        self._setComputingState(True)
314
315
316
317
318
319

    def __computeTP(self):
        """
        Function that starts the thread to compute the threshold
        removal.
        """
320
        self._bottom_threshold = self._parametersDock.bottomLE.text()
321
        self._thread = OperationThread(self, self._update_dataset.apply_threshold_removal)
322
        self._thread.setArgs(int(self._bottom_threshold))
323
        self._thread.finished.connect(self._updateData)
324
325
        if not self._update_dataset.in_memory:
            self._parametersDock.abortTP.show()
326
        self._thread.start()
327
        self._setComputingState(True)
328

329
330
331
332
333
334
335
336
    def __abortBS(self):
        self._parametersDock.abortBS.setEnabled(False)
        self._update_dataset.stop_operation(Operation.BS)

    def __abortHP(self):
        self._parametersDock.abortHP.setEnabled(False)
        self._update_dataset.stop_operation(Operation.HP)

337
338
    def __abortTP(self):
        self._parametersDock.abortTP.setEnabled(False)
339
        self._update_dataset.stop_operation(Operation.THRESHOLD)
340

341
342
343
344
345
346
347
348
    def _setComputingState(self, state):

        self._parametersDock.computeBS.setEnabled(not state)
        self._parametersDock.computeHP.setEnabled(not state)
        self._parametersDock.computeTP.setEnabled(not state)

        self.computingSignal.emit(state)

349
350
351
352
    def _updateData(self):
        """
        Updates the stack with the data computed in the thread
        """
353
354
355
356
        try:
            self._thread.finished.disconnect(self._updateData)
        except TypeError as e:
            _logger.warning(e)
357
358
        self._parametersDock.abortBS.setEnabled(True)
        self._parametersDock.abortHP.setEnabled(True)
359
        self._parametersDock.abortTP.setEnabled(True)
360
361
        self._parametersDock.abortBS.hide()
        self._parametersDock.abortHP.hide()
362
        self._parametersDock.abortTP.hide()
363
        self._setComputingState(False)
364
365
366
        if self._thread.data is not None:
            self._update_dataset = self._thread.data
            self.setStack(self._update_dataset)
367
368
        else:
            print("\nComputation aborted")
369

370
371
372
373
    def _toggleMethod(self, text):
        if text == Method.mean.value:
            self._parametersDock.inDiskWidget.hide()
        elif text == Method.median.value:
374
            self._toggleInDiskWidget(self._parametersDock.bsBackgroundCB.currentIndex())
375

376
    def _toggleInDiskWidget(self, index):
377
        if self._parametersDock.bsMethodsCB.currentText() == Method.median.value:
378
379
380
381
            if self.bg_dataset is None:
                self._parametersDock.inDiskWidget.hide() if self.dataset.in_memory else \
                    self._parametersDock.inDiskWidget.show()
            elif not (index or self.bg_dataset.in_memory) or (index and not self.dataset.in_memory):
382
383
384
                self._parametersDock.inDiskWidget.show()
            else:
                self._parametersDock.inDiskWidget.hide()
385
386
        else:
            self._parametersDock.inDiskWidget.hide()
387

388
389
390
    def getDataset(self):
        return self._update_dataset, self.indices, self.bg_indices, self. bg_dataset

391
    def resetStack(self):
392
        self._update_dataset = self.dataset
393
        self.setStack()
394

395
396
397
    def clearStack(self):
        self._sv.setStack(None)

398
399
400
    def getStack(self):
        return self._sv.getStack(False, True)[0]

401
    def setStack(self, dataset=None):
402
        """
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
403
        Sets new data to the stack.
404
        Mantains the current frame showed in the view.
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
405
406

        :param Dataset dataset: if not None, data set to the stack will be from the given dataset.
407
        """
408
409
        if dataset is None:
            dataset = self.dataset
410
        nframe = self._sv.getFrameNumber()
411
        self._sv.setStack(dataset.get_data(self.indices))
412
        self._sv.setFrameNumber(nframe)
413

414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    def getStackViewColormap(self):
        """
        Returns the colormap from the stackView

        :rtype: silx.gui.colors.Colormap
        """
        return self._sv.getColormap()

    def setStackViewColormap(self, colormap):
        """
        Sets the stackView colormap

        :param colormap: Colormap to set
        :type colormap: silx.gui.colors.Colormap
        """
        self._sv.setColormap(colormap)

431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
    @property
    def size(self):
        return self._size

    @size.setter
    def size(self, size):
        self._size = size
        self._parametersDock.hpSizeCB.setCurrentText(size)

    @property
    def method(self):
        return self._method

    @method.setter
    def method(self, method):
        self._method = method
        self._parametersDock.bsMethodsCB.setCurrentText(method)

449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
    @property
    def step(self):
        return self._step

    @method.setter
    def step(self, step):
        self._step = step
        if step is not None:
            self._parametersDock.step.setCurrentText(step)

    @property
    def chunks(self):
        return self._chunks

    @method.setter
    def chunks(self, chunks):
        self._chunks = chunks
        if chunks is not None:
            self._parametersDock.verticalChunkSize.setCurrentText(chunks[0])
            self._parametersDock.horizontalChunkSize.setCurrentText(chunks[1])

470
471
472
473
474
475
    @property
    def background(self):
        return self._background

    @background.setter
    def background(self, background):
476
477
478
        if self._parametersDock.bsBackgroundCB.findText(background) >= 0:
            self._background = background
            self._parametersDock.bsBackgroundCB.setCurrentText(background)
479
480
481
482
483
484
485
486
487

    @property
    def bottom_threshold(self):
        return self._bottom_threshold

    @bottom_threshold.setter
    def bottom_threshold(self, bottom):
        self._bottom_threshold = bottom
        self._parametersDock.bottomLE.setText(bottom)