detectionview.py 32.7 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
# -*- coding: utf-8 -*-
"""
GEPARD - Gepard-Enabled PARticle Detection
Copyright (C) 2018  Lars Bittrich and Josef Brandt, Leibniz-Institut für 
Polymerforschung Dresden e. V. <bittrich-lars@ipfdd.de>    

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program, see COPYING.  
If not, see <https://www.gnu.org/licenses/>.
"""
import numpy as np
from PyQt5 import QtCore, QtWidgets, QtGui
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
import matplotlib.pyplot as plt
from threading import Thread

27 28 29
from .segmentation import Segmentation
from .analysis.particleCharacterization import getParticleStatsWithPixelScale, loadZValImageFromDataset
from .errors import InvalidParticleError
30
from .uielements import TimeEstimateProgressbar
31
from .scenePyramid import ScenePyramid
32

33 34 35 36 37 38 39
Nscreen = 1000

class HistWidget(QtWidgets.QWidget):
    def __init__(self, histcallback, curvecallback, parent=None):
        super().__init__(parent)
        
        self.updateCallbacks(histcallback, curvecallback)
40 41 42 43
        if parent.dataset is None:
            self.points = np.array([[50,0],[100,220],[200,255]])
        else:
            self.points = parent.dataset.detectParams['points']
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
        
        self.fig = plt.Figure()
        self.canvas = FigureCanvasQTAgg(self.fig)
        self.canvas.setParent(self)
        
        self.ax = self.fig.add_subplot(111, autoscale_on=False)
        self.ax.axis("off")
        self.fig.subplots_adjust(left=0.05, top=0.98, bottom=0.05, right=0.995)
        self.canvas.mpl_connect('pick_event', self.moveControlPoint)
        self.canvas.mpl_connect('button_release_event', self.releaseAxes)
        self.canvas.mpl_connect('motion_notify_event', self.moveAxes)
        
        self.moveind = None
        
        self.plot()
        self.setMaximumSize(200,200)
        
        vbox = QtWidgets.QVBoxLayout()
        vbox.addWidget(self.canvas)
        self.setLayout(vbox)
        
    def value(self):
        return self.points
        
    def moveAxes(self, event):
        if (event.inaxes==self.ax) and self.moveind is not None:
            x = event.xdata
            y = event.ydata
            if self.moveind == 0:
                self.points[0,0] = max(0,min(x, self.points[1,0]))
            elif self.moveind == 1:
                self.points[1,0] = max(self.points[0,0]+1, min(x, self.points[2,0]-1))
                self.points[1,1] = max(0, min(y, 255))
            else:
                self.points[2,0] = max(self.points[1,0]+1, min(x, 255))
            self.plot()
                
    def releaseAxes(self, event):
        self.moveind = None
        
    def plot(self):
        self.ax.lines = []
        self.ax.collections = []
        self.ax.artists = []
        
        hist = self.histcallback()[:,0]
        hist /= hist.max()
        hist *= 255
        hist[0] = 0
        hist[-1] = 0
        xarr, arr = self.curvecallback(self.points)
        
        self.ax.fill(xarr, hist, color=(.7,.7,.7))
        self.ax.plot([0,0], [255,255], "k-")
        self.ax.plot(xarr, arr, "b-")
        self.ax.plot(self.points[:,0], self.points[:,1], "go", picker=5)
        self.ax.set_xlim(0,255)
        self.ax.set_ylim(0,255)
        
        self.canvas.draw()        
        self.repaint()
        
    def updateCallbacks(self, histcallback, curvecallback):
        self.histcallback = histcallback
        self.curvecallback = curvecallback
                
    def moveControlPoint(self, event):
        if self.moveind is None:
            self.moveind = event.ind
    

class ImageView(QtWidgets.QLabel):
    seedChanged = QtCore.pyqtSignal()
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.overlay = None
        self.drag = False
        self.alpha = .8
        self.contours = []
        self.seedradius = 3
        self.showseedpoints = True
        self.measpoints = []
        self.seedpoints = []
        self.seeddeletepoints = []
        
    @QtCore.pyqtSlot(int)
    def resetAlpha(self, num):
        self.alpha = num/100.
        self.update()
    
    @QtCore.pyqtSlot(int)
    def setSeedRadius(self, num):
        self.seedradius = num
        self.update()
        
    @QtCore.pyqtSlot(int)
    def changeSeedDisplay(self, state):
        self.showseedpoints = (state==QtCore.Qt.Checked)
        self.update()
        
    def showStep(self, img, imgtype):
        self.overlay = None
        if imgtype==0:
            img = img.repeat(3).reshape(img.shape[0],img.shape[1],3)
            self.setOverlay(img)
        elif imgtype==1:
            levels = img
            img = np.zeros(tuple(levels.shape)+(3,), dtype=np.uint8)
            img[:,:,0][np.nonzero(levels&1)] = 255.
            img[:,:,1][np.nonzero(levels&2)] = 255.
            self.setOverlay(img)
        self.update()
        
    def removeSeeds(self,p0):
        p0 = np.array([p0])
        if len(self.seedpoints)>0:
            arr = np.array(self.seedpoints)
162
            d = np.linalg.norm(arr[:, :2]-p0, axis=1)
163 164 165 166
            ind = d>self.seedradius
            self.seedpoints = arr[ind,:].tolist()
        if len(self.seeddeletepoints)>0:
            arr = np.array(self.seeddeletepoints)
167
            d = np.linalg.norm(arr[:, :2]-p0, axis=1)
168 169 170 171
            ind = d>self.seedradius
            self.seeddeletepoints = arr[ind,:].tolist()
        
    def mousePressEvent(self, event):
172
        if event.button()==QtCore.Qt.LeftButton:
173 174 175 176 177 178 179
            if event.modifiers()&QtCore.Qt.ShiftModifier:
                self.drag = "delete"
            elif event.modifiers()&QtCore.Qt.AltModifier:
                self.drag = "remove"
            else:
                self.drag = "add"
            p0 = event.pos()
Josef Brandt's avatar
Josef Brandt committed
180 181 182 183 184 185 186 187
            self.appendSeedPoints(p0)
            # print(p0)
            # if self.drag =="add":
            #     self.seedpoints.append([p0.x(), p0.y(), self.seedradius])
            # elif self.drag =="delete":
            #     self.seeddeletepoints.append([p0.x(), p0.y(), self.seedradius])
            # elif self.drag == "remove":
            #     self.removeSeeds([p0.x(), p0.y()])
188 189 190 191 192 193 194
                
            self.update()
        super().mousePressEvent(event)
        
    def mouseMoveEvent(self, event):
        if self.drag:
            p0 = event.pos()
Josef Brandt's avatar
Josef Brandt committed
195 196 197 198 199 200 201
            self.appendSeedPoints(p0)
            # if self.drag == "add":
            #     self.seedpoints.append([p0.x(),p0.y(),self.seedradius])
            # elif self.drag == "delete":
            #     self.seeddeletepoints.append([p0.x(),p0.y(),self.seedradius])
            # else:
            #     self.removeSeeds([p0.x(),p0.y()])
202 203 204 205 206 207 208 209
            self.update()
        super().mouseMoveEvent(event)
        
    def mouseReleaseEvent(self, event):
        if self.drag:
            self.seedChanged.emit()
        self.drag = False
        super().mouseReleaseEvent(event)
Josef Brandt's avatar
Josef Brandt committed
210 211 212 213 214 215 216 217 218 219

    def appendSeedPoints(self, pos):
        if 0 <= pos.x() < Nscreen and 0 <= pos.y() < Nscreen:
            print(pos)
            if self.drag == "add":
                self.seedpoints.append([pos.x(), pos.y(), self.seedradius])
            elif self.drag == "delete":
                self.seeddeletepoints.append([pos.x(), pos.y(), self.seedradius])
            elif self.drag == "remove":
                self.removeSeeds([pos.x(), pos.y()])
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 265 266
        
    def clearData(self):
        self.contours = []
        self.measpoints = []
        self.seedpoints = []
        self.seeddeletepoints = []
        self.overlay = None
        
    def updateSeedPoints(self, seedpoints=[], seeddeletepoints=[]):
        self.seedpoints = seedpoints
        self.seeddeletepoints = seeddeletepoints
        
    def updateDetectionResults(self, contours, measpoints):
        self.overlay = None
        cp = []
        for c in contours:
            polygon = QtGui.QPolygonF()
            for ci in c:
                polygon.append(QtCore.QPointF(ci[0,0],ci[0,1]))
            cp.append(polygon)
        
        self.contours = cp
        self.measpoints = measpoints
        self.update()
        
    def setOverlay(self, img):
        height, width, channel = img.shape
        assert channel==3
        bytesPerLine = 3 * width
        pix = QtGui.QPixmap()
        pix.convertFromImage(QtGui.QImage(img.data, width, height, 
                                          bytesPerLine, QtGui.QImage.Format_RGB888))
        self.overlay = pix
        
    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.drawPixmap(0, 0, self.pixmap())
        painter.setOpacity(self.alpha)
        if self.overlay is not None:
            painter.drawPixmap(0, 0, self.overlay)
        else:
            painter.setPen(QtCore.Qt.blue)
            painter.setBrush(QtCore.Qt.green)
            for c in self.contours:
                painter.drawPolygon(c)
            painter.setPen(QtCore.Qt.red)
            painter.setBrush(QtCore.Qt.red)
267 268
            for points in self.measpoints:
                for point in points:
269
                    painter.drawEllipse(point.x-2, point.y-2, 5, 5)
270 271 272 273 274

        if self.showseedpoints:
            painter.setPen(QtCore.Qt.white)
            painter.setBrush(QtCore.Qt.white)
            for p in self.seedpoints:
275 276 277 278 279 280 281
                painter.drawEllipse(p[0]-p[2], p[1]-p[2], 2*p[2], 2*p[2])
            
            painter.setPen(QtCore.Qt.magenta)           #I think it is more useful when the deletpoints override the seedpoints
            painter.setBrush(QtCore.Qt.magenta)
            
            for p in self.seeddeletepoints:
                painter.drawEllipse(p[0]-p[2], p[1]-p[2], 2*p[2], 2*p[2])
282 283
            
class ParticleDetectionView(QtWidgets.QWidget):
284
    imageUpdate = QtCore.pyqtSignal(str, name='imageUpdate')    #str = 'df' (= darkfield) or 'bf' (=bright field)
285 286
    detectionFinished = QtCore.pyqtSignal(name='detectionFinished')
    
287
    def __init__(self, pyramid: ScenePyramid, dataset, parent=None):
288
        super().__init__(parent, QtCore.Qt.Window)
289
        self.dataset = self.verifySeedpoints(dataset)
290
        self.pyramid = pyramid
291
        self.img = pyramid.getFullImage()
292
        self.imgclip = 0, 0, 0, 0
293
        self.seg = Segmentation(self.dataset, self)
294
        self.seg.detectionState.connect(self.updateDetectionState)
295
        self.thread = None
296
        self.threadrunning = False
297
        self.view = parent
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
        
        vbox = QtWidgets.QVBoxLayout()
        hbox = QtWidgets.QHBoxLayout()
        
        def makeShowLambda(name):
            def f(): return self.detectShow(name)
            return QtCore.pyqtSlot()(f)
        def makeValueLambda(objmethod):
            return lambda : objmethod()
        
        self.imglabel = ImageView(self)
        self.imglabel.seedChanged.connect(self.seedChanged)
        self.drag = False
        self.seedradiusedit = QtWidgets.QSpinBox(self)
        self.seedradiusedit.setMinimum(1)
        self.seedradiusedit.valueChanged.connect(self.imglabel.setSeedRadius)
        self.seedradiusedit.valueChanged.connect(self.updateImageSeeds)
        self.seedradiusedit.setValue(3)
        self.showseedpoints = QtWidgets.QCheckBox("Show manual seed points", self)
        self.showseedpoints.stateChanged.connect(self.imglabel.changeSeedDisplay)
        self.showseedpoints.setChecked(True)
        self.setImageCenter()
320
        
321
        self.detectParamsGroup = QtWidgets.QGroupBox("Detection settings", self)
322 323
        grid = QtWidgets.QGridLayout()
        self.parameters = []
324 325
        checkBoxesToLink = {}
        
326
        # create editable parameters:
327 328
        for i, p in enumerate(self.seg.parlist):
            label, colstretch = None, 1
329
            if p.name == "contrastCurve":
330 331 332 333 334 335
                paramui = HistWidget(lambda : self.seg.calculateHist(self.seg.convert2Gray(self.subimg)),
                                     self.seg.calculateHistFunction, self)
                valuefunc = makeValueLambda(paramui.value)
                colstretch = 2
            if p.dtype == np.bool:
                paramui = QtWidgets.QCheckBox(p.helptext, self)
336
                paramui.stateChanged.connect(self.autoUpdateIfDesired)
337 338 339
                paramui.setChecked(p.value)
                valuefunc = makeValueLambda(paramui.isChecked)
                colstretch = 2
340 341
                if p.linkedParameter is not None:
                    checkBoxesToLink[paramui] = p.linkedParameter
342 343 344 345 346 347 348 349 350 351 352 353 354 355
            elif p.dtype == int or p.dtype == float:
                label = QtWidgets.QLabel(p.helptext, self)
                if p.dtype == int:
                    paramui = QtWidgets.QSpinBox(self)
                else:
                    paramui = QtWidgets.QDoubleSpinBox(self)
                    paramui.setDecimals(p.decimals)
                if p.valrange[0] is not None:
                    paramui.setMinimum(p.valrange[0])
                if p.valrange[1] is not None:
                    paramui.setMaximum(p.valrange[1])
                paramui.setSingleStep(p.stepsize)
                paramui.setValue(p.value)
                paramui.setMinimumWidth(70)
356
                paramui.valueChanged.connect(self.autoUpdateIfDesired)
357 358 359 360
                valuefunc = makeValueLambda(paramui.value)
            elif p.dtype is None:
                label = QtWidgets.QLabel(p.helptext, self)
                paramui = None
361
            
362
            if paramui is not None:
363
                self.parameters.append([paramui, p.name, valuefunc, None])
364 365 366
                if colstretch == 1:
                    grid.addWidget(paramui, i, 1, QtCore.Qt.AlignLeft)
                else:
367 368 369
                    grid.addWidget(paramui, i, 0, 1, 2, QtCore.Qt.AlignLeft) 
                    
                
370 371
            if label is not None:
                grid.addWidget(label, i, 0, QtCore.Qt.AlignLeft)
372
                
373 374 375 376
            if p.show is True:
                pshow = QtWidgets.QPushButton(">", self)
                pshow.released.connect(makeShowLambda(p.name))
                grid.addWidget(pshow, i, 2, QtCore.Qt.AlignRight)
377 378 379
                
                if paramui is not None:
                    self.parameters[-1][3] = pshow
Josef Brandt's avatar
Josef Brandt committed
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
        #link checkboxes to other parameters:
        def makeEnableLambda(checkbox, parameter):
            return lambda: parameter.setEnabled(checkbox.isChecked())
        
        for box in checkBoxesToLink:
            linkedName = checkBoxesToLink[box]
            for p in self.parameters:
                if p[1] == linkedName:
                    p[0].setEnabled(box.isChecked())
                    box.stateChanged.connect(makeEnableLambda(box, p[0]))   #the actual control element
                    if p[3] is not None: #the "show" box, if present
                        box.stateChanged.connect(makeEnableLambda(box, p[3]))   
                        p[3].setEnabled(box.isChecked())
        
        
396 397 398 399 400
        
        label = QtWidgets.QLabel("Seed radius", self)
        grid.addWidget(label, i+1, 0, QtCore.Qt.AlignLeft)
        grid.addWidget(self.seedradiusedit, i+1, 1, QtCore.Qt.AlignLeft)
        grid.addWidget(self.showseedpoints, i+2, 0, 1, 2, QtCore.Qt.AlignLeft) 
401 402
        grid.addWidget(QtWidgets.QLabel("Click mouse to add seeds, Click+Shift to add deletepoints"), i+3, 0, 1, 2, QtCore.Qt.AlignLeft) 
        grid.addWidget(QtWidgets.QLabel("Click+Alt removes seeds near cursor"), i+4, 0, 1, 2, QtCore.Qt.AlignLeft) 
403 404
        self.detectParamsGroup.setLayout(grid)
        vbox.addWidget(self.detectParamsGroup)
405 406 407 408 409 410 411 412
        
        self.updateSeedsInSampleViewBtn = QtWidgets.QPushButton("Update Seedpoints in fullimage view", self)
        self.updateSeedsInSampleViewBtn.released.connect(self.updateSeedsInSampleview)
        self.hideSeedsInSampleViewBtn = QtWidgets.QPushButton("Hide Seedpoints in fullimage view", self)
        self.hideSeedsInSampleViewBtn.released.connect(self.removeSeedsInSampleView)
        
        vbox.addWidget(self.updateSeedsInSampleViewBtn)
        vbox.addWidget(self.hideSeedsInSampleViewBtn)
413 414 415 416 417 418 419
            
        self.slider = QtWidgets.QSlider(self)
        self.slider.setRange(0,100)
        self.slider.setValue(80)
        self.slider.setOrientation(QtCore.Qt.Horizontal)
        self.slider.sliderMoved.connect(self.imglabel.resetAlpha)
        vbox.addWidget(self.slider)
420
        
Josef Brandt's avatar
Josef Brandt committed
421 422 423 424
        self.autoUpdateCheckBox = QtWidgets.QCheckBox('Auto-update detection')
        self.autoUpdateCheckBox.setMaximumWidth(200)
        self.autoUpdateCheckBox.setChecked(True)
        vbox.addWidget(self.autoUpdateCheckBox)
425 426 427
        
        self.progressbar = TimeEstimateProgressbar()
        vbox.addWidget(self.progressbar)
Josef Brandt's avatar
Josef Brandt committed
428

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
        hbox2 = QtWidgets.QHBoxLayout()
        self.pdetectsub = QtWidgets.QPushButton("Detect", self)
        self.pdetectall = QtWidgets.QPushButton("Detect all", self)
        self.pclear = QtWidgets.QPushButton("Clear detection", self)
        self.pdetectsub.released.connect(makeShowLambda(None))
        self.pdetectall.released.connect(self.detectParticles)
        self.pclear.released.connect(self.clearDetection)
        hbox2.addWidget(self.pdetectsub)
        hbox2.addWidget(self.pdetectall)
        hbox2.addWidget(self.pclear)
        vbox.addLayout(hbox2)

        vbox.addStretch()
        hbox.addLayout(vbox,0)
        hbox.addWidget(self.imglabel,1)
        
        self.setLayout(hbox)
        self.setWindowTitle("Particle Detection")
447 448 449 450
    
    def saveDetectParams(self, ds=None):
        if ds is not None:
            for param in self.parameters:
451
                if param[1] == 'contrastCurve':
452
                    print(param[0].value())
453
                try:                # is it a spinbox or the histWidget? Read out the value
454
                    ds.detectParams[param[1]] = param[0].value()
455
                except:             # otherwise checkbox -> take its state
456 457 458 459 460 461 462 463
                    ds.detectParams[param[1]] = param[0].isChecked()
            ds.detectParams['seedRad'] = self.seedradiusedit.value()
            ds.save()

    def verifySeedpoints(self, dataset):
        seedpoints = dataset.seedpoints
        seeddeletepoints = dataset.seeddeletepoints
        
464 465
        if len(seedpoints) > 0:     # points are present
            if seedpoints.shape[1] == 2:    # old entries with only x,y coordinates
466 467 468 469
                radii = np.ones((seedpoints.shape[0], 1))*3
                dataset.seedpoints = np.hstack((seedpoints, radii))
        else:
            dataset.seedpoints = np.array([])
470
        
471
        if len(seeddeletepoints) > 0:     # points are present
472 473 474 475 476 477 478
            if seeddeletepoints.shape[1] == 2:    #old entries with only x,y coordinates
                radii = np.ones((seeddeletepoints.shape[0], 1))*3
                dataset.seeddeletepoints = np.hstack((seeddeletepoints, radii))
        else:
            dataset.seeddeletepoints = np.array([])
        return dataset
    
479 480 481 482 483 484 485 486 487
    @QtCore.pyqtSlot()
    def seedChanged(self):
        seedradius = self.seedradiusedit.value()
        def clipdata(arr0, arr1, p0, n1, n2, m1, m2):
            if arr0.shape[0]>0:
                ind = (arr0[:,0]>m1-seedradius)&(arr0[:,0]<=m2+seedradius) 
                ind &= (arr0[:,1]>n1-seedradius)&(arr0[:,1]<=n2+seedradius)
                arr0 = arr0[~ind,:]
            else:
488 489
                arr0 = arr0.reshape(0,3)

490
            if arr1.shape[0]>0:
491
                arr1[:,:2] += p0
492
            else:
493
                arr1 = arr1.reshape(0,3)
494 495 496 497 498 499 500 501
            return np.concatenate((arr0, arr1), axis=0)
        
        if self.dataset is not None:
            n1,n2,m1,m2 = self.imgclip
            p0 = np.array([[m1,n1]], dtype=np.int32)
            self.dataset.seedpoints = clipdata(self.dataset.seedpoints,
                                               np.array(self.imglabel.seedpoints, dtype=np.int32),
                                               p0, n1, n2, m1, m2)
502
            
503 504 505 506 507 508 509 510 511 512 513 514
            self.dataset.seeddeletepoints = clipdata(self.dataset.seeddeletepoints,
                                                     np.array(self.imglabel.seeddeletepoints, dtype=np.int32),
                                                     p0, n1, n2, m1, m2)
            self.dataset.save()
            
    @QtCore.pyqtSlot()
    def updateImageSeeds(self):
        if self.dataset is not None:
            n1,n2,m1,m2 = self.imgclip
            p0 = np.array([[m1,n1]], dtype=np.int32)
            seedpoints = []
            seeddeletepoints = []
515

516
            arr1 = self.dataset.seedpoints
517
            # what seeds are actually in image view?
Josef Brandt's avatar
Josef Brandt committed
518
            for point in arr1:
519 520
                if point[0] > (m1-point[2]) and point[0] <= (m2+point[2]) and point[1] > (n1-point[2]) and point[1] <= (n2+point[2]):
                    seedpoints.append([point[0] - p0[0][0], point[1] - p0[0][1], point[2]])
521
            arr2 = self.dataset.seeddeletepoints
Josef Brandt's avatar
Josef Brandt committed
522
            for point in arr2:
523 524 525
                if point[0] > (m1-point[2]) and point[0] <= (m2+point[2]) and point[1] > (n1-point[2]) and point[1] <= (n2+point[2]):
                    seeddeletepoints.append([point[0] - p0[0][0], point[1] - p0[0][1], point[2]])

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
            self.imglabel.updateSeedPoints(seedpoints, seeddeletepoints)
        
    def closeEvent(self, event):
        self.detectionFinished.emit()
        
    def mousePressEvent(self, event):
        if event.button()==QtCore.Qt.RightButton:
            self.drag = True
            self.p0 = event.pos()
        
    def mouseMoveEvent(self, event):
        if self.drag:
            dp = self.p0-event.pos()
            self.lastmove = (self.lastcenter[0]+dp.x(),self.lastcenter[1]+dp.y())
            self.setImageCenter(self.lastmove)
541 542 543 544 545 546
            
    def wheelEvent(self, event):
        if event.angleDelta().y() > 0:
            self.seedradiusedit.setValue(self.seedradiusedit.value()+1)
        else:
            self.seedradiusedit.setValue(self.seedradiusedit.value()-1)
547 548 549 550 551
        
    def mouseReleaseEvent(self, event):
        if self.drag:
            self.lastcenter = self.lastmove
        self.drag = False
552 553 554 555 556 557 558 559 560
        self.autoUpdateIfDesired()
    
    def autoUpdateIfDesired(self):
        try:
            if self.autoUpdateCheckBox.isChecked():
                self.detectShow(None)
        except:   #the method is already called when automatically setting default parameters, which causes various errors because initialization is not yet finished...
            pass
    
561 562 563 564 565
    def setDataSet(self, ds):
        self.dataset = ds
        self.updateImageSeeds()
        
    def setImageCenter(self, center=None):
566 567 568 569 570 571 572 573
        '''
        as more than the tiles are part of the scene
        bounding rect may be bigger than just a rect around the tiles
        tiles should be grouped

        '''
        width, height = self.pyramid.getBoundingRectDim()

574
        if center is None:
575 576
            centerx = width//2
            centery = height//2
577 578
        else:
            centerx, centery = center
579 580 581 582 583 584

        if height < Nscreen:
            centery = height//2
        if width < Nscreen:
            centerx = width//2

585 586
        if not self.drag:  
            self.lastcenter = centerx, centery
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628

        y1, y2 = centery-Nscreen//2, centery+Nscreen//2+1
        x1, x2 = centerx-Nscreen//2, centerx+Nscreen//2+1
        if y1 < 0:
            y2 -= y1
            y1 = 0
        if y2 > height:
            y1 -= y2-height
            if y1 < 0:
                y1 = 0
            y2 = height
        if x1 < 0:
            x2 -= x1
            x1 = 0
        if x2 > width:
            x1 -= x2-width
            if x1 < 0:
                x1 = 0
            x2 = width

        self.imgclip = int(y1), int(y2), int(x1), int(x2)
        self.subimg, pix = self.pyramid.getSubImage(self.imgclip)
        '''
        img = QtGui.QImage(x2 - x1, y2 - y1, QtGui.QImage.Format_RGB888)
        self.view.scene().render(
            QtGui.QPainter(img),
            QtCore.QRectF(0, 0, img.width(), img.height()),
            #QtCore.QRectF(x1 + x0, y1 + y0, x2 - x1, y2 - y1)
            QtCore.QRectF(x1, y1, x2 - x1, y2 - y1)
        )

        #pix = self.view.grab(QtCore.QRect(x1 + x0, y1 + y0, x2 - x1, y2 - y1))
        # @see https://stackoverflow.com/a/11399959
        #img = pix.toImage().convertToFormat(QtGui.QImage.Format_RGB888)
        ptr = img.bits()
        #ptr.setsize(img.byteCount())
        ptr.setsize(img.height() * img.width() * 3)
        self.subimg = np.asarray(ptr).reshape(img.height(), img.width(), 3)
        pix = QtGui.QPixmap()
        pix.convertFromImage(img)
        '''
        '''
629 630 631 632 633 634 635 636
        sub = self.img[n1:n2,m1:m2,:].copy()
        self.imgclip = n1,n2,m1,m2
        self.subimg = sub
        height, width, channel = sub.shape
        bytesPerLine = 3 * width
        pix = QtGui.QPixmap()
        pix.convertFromImage(QtGui.QImage(sub.data, width, height, 
                                          bytesPerLine, QtGui.QImage.Format_RGB888))
637
        '''
638 639 640 641 642
        self.imglabel.clearData()
        self.imglabel.setPixmap(pix)
        self.updateImageSeeds()
        
    def detectShow(self, showname):
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
        if not self.threadrunning:
            self.saveDetectParams(self.dataset)
            img = self.subimg.copy()
            kwargs = {}
            for ui, name, valuefunc, showbtn in self.parameters:
                kwargs[name] = valuefunc()
            self.seg.setParameters(**kwargs)
            seedradius = self.seedradiusedit.value()
            if showname is not None:
                stepImg, imgtype = self.seg.apply2Image(img, self.imglabel.seedpoints, self.imglabel.seeddeletepoints,
                                                        seedradius, self.dataset, return_step=showname)
                self.imglabel.showStep(stepImg, imgtype)
            else:
                measurementpoints, contours = self.seg.apply2Image(img, self.imglabel.seedpoints, self.imglabel.seeddeletepoints, 
                                                                   seedradius, self.dataset)
                self.imglabel.updateDetectionResults(contours, measurementpoints)
659 660 661 662
            
    @QtCore.pyqtSlot()
    def clearDetection(self):
        if self.dataset is not None:
663 664 665
            self.dataset.particleContainer.clearParticles()
            self.dataset.particleContainer.clearMeasurements()
            self.dataset.particleDetectionDone = False
666 667 668
            self.dataset.ramanscandone = False
            self.dataset.mode = "opticalscan"
            self.dataset.save()
669
            self.imageUpdate.emit(self.view.microscopeMode)
670
            self.view.resetParticleContours()
671 672 673 674 675 676 677 678 679 680 681
    
    @QtCore.pyqtSlot()
    def cancelThread(self):
        self.seg.cancelcomputation = True
        self.thread.join()
        self.seg.cancelcomputation = False
        self.threadrunning = False
        
    def blockUI(self):
        self.pdetectsub.setEnabled(False)
        self.pclear.setEnabled(False)
682 683 684
        self.detectParamsGroup.setEnabled(False)
        self.updateSeedsInSampleViewBtn.setEnabled(False)
        self.hideSeedsInSampleViewBtn.setEnabled(False)
685 686 687 688
    
    def unBlockUI(self):
        self.pdetectsub.setEnabled(True)
        self.pclear.setEnabled(True)
689 690 691
        self.detectParamsGroup.setEnabled(True)
        self.updateSeedsInSampleViewBtn.setEnabled(True)
        self.hideSeedsInSampleViewBtn.setEnabled(True)
692
    
693 694 695
    def raiseWarning(self, warning):
        QtWidgets.QMessageBox.critical(self, "Warning", warning)
    
696 697
    @QtCore.pyqtSlot()
    def detectParticles(self):
698 699 700 701
        """
        Detect all particles
        :return:
        """
702
        self.saveDetectParams(self.dataset)
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
        if self.thread is not None and self.thread.is_alive():
            self.cancelThread()
            return
        self.blockUI()
        self.pdetectall.setText("Cancel")
        self.threadrunning = True
        self.thread = Thread(target=self._worker)
        self.thread.start()
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.checkOnComputation)
        self.timer.setSingleShot(True)
        self.timer.start(100.)
        
    @QtCore.pyqtSlot()      
    def checkOnComputation(self):
        if self.thread is not None:
            if not self.threadrunning:
                self.thread = None
721
                self.progressbar.disable()
722 723
                self.unBlockUI()
                self.pdetectall.setText("Detect all")
724
                self.imageUpdate.emit(self.view.microscopeMode)
725
                if self.dataset is not None:
726 727 728
                    numParticles = self.dataset.particleContainer.getNumberOfParticles()
                    numMeasurements = self.dataset.particleContainer.getNumberOfMeasurements()
                    self.setWindowTitle(f'{numParticles} Particles ({numMeasurements}  Measurements)')
729
            else:
730
                self.timer.start(100.)
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
    
    @QtCore.pyqtSlot(str)
    def updateDetectionState(self, message):
        """
        Updates the progressbar and its text-label to the current state of the detection
        :return:
        """
        if message.find('DO') == -1:
            self.progressbar.setMessage(message)
        else:
            if message.find('setup') != -1:
                self.progressbar.resetTimerAndCounter()
                self.progressbar.enable()
            elif message.find('maxVal') != -1:
                maxVal = int(message.split('=')[-1])
                self.progressbar.setMaxValue(maxVal)
            elif message.find('newVal') != -1:
                newVal = int(message.split('=')[-1])
                self.progressbar.setValue(newVal)
750 751 752 753 754 755 756
        
    def _worker(self):
        kwargs = {}
        seedpoints, deletepoints = [], []
        if self.dataset is not None:
            seedpoints = self.dataset.seedpoints
            deletepoints = self.dataset.seeddeletepoints
757
        for ui, name, valuefunc, showbtn in self.parameters:
758 759 760
            kwargs[name] = valuefunc()
        seedradius = self.seedradiusedit.value()
        self.seg.setParameters(**kwargs)
761
        
762
        measurementPoints, contours= self.seg.apply2Image(self.img, seedpoints, deletepoints, seedradius, self.dataset)
763
        
JosefBrandt's avatar
JosefBrandt committed
764
        if measurementPoints is None: # computation was canceled
765 766
            return
        
767
        if self.dataset is not None:
768
            self.applyResultsToDataset(measurementPoints, contours)
769
        self.threadrunning = False
770
    
771
    def applyResultsToDataset(self, measurementPoints, contours):
772 773
        self.dataset.ramanscandone = False
        
774 775 776
        particlestats, invalidParticleIndices = self.getParticleStats(contours)
        contours = self.removeInvalidContours(contours, invalidParticleIndices)
        measurementPoints = self.removeInvalidMeasurementPoints(measurementPoints, invalidParticleIndices)
777
        
778 779
        particleContainer = self.dataset.particleContainer
        numParticles = len(contours)
780

781 782 783 784
        particleContainer.initializeParticles(numParticles)
        particleContainer.setParticleContours(contours)
        particleContainer.setParticleStats(particlestats)
        
785
        particleContainer.clearMeasurements()
786
        for particleIndex, measPoints in enumerate(measurementPoints):
787 788 789 790 791 792 793 794 795
            for index, point in enumerate(measPoints):
                curParticle = particleContainer.getParticleOfIndex(particleIndex)
                indexOfNewMeas = particleContainer.addEmptyMeasurement()
                particleContainer.setMeasurementPixelCoords(indexOfNewMeas, point.x, point.y)
                curParticle.addMeasurement(particleContainer.measurements[indexOfNewMeas])
                
        self.dataset.particleDetectionDone = True
        self.dataset.mode = "prepareraman"
        self.dataset.save()
796 797 798 799

    def getParticleStats(self, contours):
        particlestats = []
        zvalimg = loadZValImageFromDataset(self.dataset)
800 801
        invalidParticleIndices = []
        for contourIndex, contour in enumerate(contours):
802 803 804
            try:
                stats = getParticleStatsWithPixelScale(contour, self.dataset, fullimage=self.img, zimg=zvalimg)
            except InvalidParticleError: 
805 806
                print('invalid contour in detection, skipping particle. Contour is:', contour)
                invalidParticleIndices.append(contourIndex)
807
                continue
808 809 810 811 812 813 814 815 816 817 818
            particlestats.append(stats)

        return particlestats, invalidParticleIndices
    
    def removeInvalidContours(self, contours, invalidParticleIndices):
        validContours = [cnt for index, cnt in enumerate(contours) if index not in invalidParticleIndices]
        return validContours
    
    def removeInvalidMeasurementPoints(self, measurementPoints, invalidParticleIndices):
        validMeasPoints = [points for index, points in enumerate(measurementPoints) if index not in invalidParticleIndices]
        return validMeasPoints
819 820 821 822 823 824

    def updateSeedsInSampleview(self):
        self.view.updateSeedPointMarkers()
    
    def removeSeedsInSampleView(self):
        self.view.removeSeedPointMarkers()