sampleview.py 31.4 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
# -*- 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/>.
"""
from PyQt5 import QtCore, QtGui, QtWidgets
import numpy as np
import os
JosefBrandt's avatar
 
JosefBrandt committed
24
import cv2
JosefBrandt's avatar
 
JosefBrandt committed
25
import time
26 27 28 29 30 31 32
from .dataset import DataSet, loadData
from .ramancom.ramancontrol import RamanControl, simulatedRaman
from .opticalscan import OpticalScan
from .ramanscanui import RamanScanUI
from .detectionview import ParticleDetectionView
from .analysis.analysisview import ParticleAnalysis
from .zeissimporter import ZeissImporter
33
from .viewitems import FitPosIndicator, Node, Edge, ScanIndicator, RamanScanIndicator, SegmentationContour, ParticleInfo
34
from .helperfunctions import polygoncovering, cv2imread_fix
35 36
from .analysis.colorlegend import getColorFromNameWithSeed
from .analysis.particleEditor import ParticleEditor
37
from .ramancom.configRaman import RamanConfigWin
JosefBrandt's avatar
JosefBrandt committed
38

39 40
class SampleView(QtWidgets.QGraphicsView):
    ScalingChanged = QtCore.pyqtSignal(float)
41
    ParticleOfIndexSelected = QtCore.pyqtSignal(int)
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    
    def __init__(self, logpath):
        super(SampleView, self).__init__()
        
        self.logpath = logpath
        self.item = QtWidgets.QGraphicsPixmapItem()
        self.item.setPos(0, 0)
        self.item.setAcceptedMouseButtons(QtCore.Qt.NoButton)
        self.scaleFactor = 1.0
        scene = QtWidgets.QGraphicsScene(self)
        scene.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)
        scene.addItem(self.item)
        scene.setBackgroundBrush(QtCore.Qt.darkGray)
        self.setScene(scene)
        self.setCacheMode(QtWidgets.QGraphicsView.CacheBackground)
        self.setViewportUpdateMode(QtWidgets.QGraphicsView.BoundingRectViewportUpdate)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
        self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorViewCenter)
61
        
62 63 64 65 66 67 68 69 70
        self.ramanctrl = RamanControl()
        self.simulatedRaman = simulatedRaman        
        #determine, if ramanSwitch is needed:
        self.ramanctrl.connect()
        if not self.ramanctrl.connected:
            QtWidgets.QMessageBox.warning(self, 'Error', 'Please enable Raman Connection')
            return
        if self.ramanctrl.getImageDimensions(mode='bf')[0] == self.ramanctrl.getImageDimensions(mode='df')[0]:
            self.ramanSwitchNeeded = False
71
        else:
72 73 74 75 76 77
            self.ramanSwitchNeeded = True
        self.ramanctrl.disconnect()
        
        self.drag = None
        self.mode = None
        self.dataset = None
JosefBrandt's avatar
 
JosefBrandt committed
78
        self.particleEditor = None
79 80 81 82
        self.fititems = []
        self.boundaryitems = [[],[]]
        self.scanitems = []
        self.ramanscanitems = []
JosefBrandt's avatar
JosefBrandt committed
83
        self.particleInfoBox = None
84 85
        self.imgdata = None
        self.isblocked = False
JosefBrandt's avatar
 
JosefBrandt committed
86
        self.contourItems = []
JosefBrandt's avatar
 
JosefBrandt committed
87
        self.selectedParticleIndices = []
JosefBrandt's avatar
 
JosefBrandt committed
88
        self.particlePainter = None
JosefBrandt's avatar
 
JosefBrandt committed
89
        
90 91 92 93 94 95 96 97 98 99 100
        self.detectionwidget = None
        self.ramanwidget = RamanScanUI(self.ramanctrl, None, self.logpath, self)
        self.ramanwidget.imageUpdate.connect(self.loadPixmap)
        self.oscanwidget = OpticalScan(self.ramanctrl, None, self.logpath, self)
        self.oscanwidget.imageUpdate.connect(self.loadPixmap)
        self.oscanwidget.boundaryUpdate.connect(self.resetBoundary)
        self.analysiswidget = None
        self.setMinimumSize(600, 600)
        self.darkenPixmap = False
        self.microscopeMode = None
        
JosefBrandt's avatar
 
JosefBrandt committed
101
        self.update()
JosefBrandt's avatar
JosefBrandt committed
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
    def takeScreenshot(self):
        #TODO:
        #LIMIT SCREENSHOT TO ACTUAL VIEWSIZE OF LOADED IMAGE...
        #hide scrollbars
        self.setHorizontalScrollBarPolicy(1)
        self.setVerticalScrollBarPolicy(1)
        #capture screen
        screen = QtWidgets.QApplication.primaryScreen()
        self.repaint()
        screenshot = screen.grabWindow(self.winId())
        #unhide scrollbars
        self.setHorizontalScrollBarPolicy(0)
        self.setVerticalScrollBarPolicy(0)
        
        fname = self.dataset.path + '/screenshot.png'
        validFileName = False
        incr = 1
        while not validFileName:
            if not os.path.exists(fname):
                validFileName = True
            else:
                fname = self.dataset.path + '/screenshot ({}).png'.format(incr)
                incr += 1
        screenshot.save(fname , 'png')
        QtWidgets.QMessageBox.about(self, 'Message', 'Saved as {} to project directory.'.format(fname.split('/')[-1]))
                    
    def closeEvent(self, event):
        reply = QtWidgets.QMessageBox.question(self, 'Message',
JosefBrandt's avatar
JosefBrandt committed
131
            "Do you really want to quit?", QtWidgets.QMessageBox.Yes | 
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
            QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)

        if reply == QtWidgets.QMessageBox.Yes:
            self.disconnectRaman()
            self.saveDataSet()
            event.accept()
            self.oscanwidget.close()
            if self.detectionwidget is not None:
                self.detectionwidget.close()
            if self.analysiswidget is not None:
                self.analysiswidget.close()
            self.ramanwidget.close()
        else:
            event.ignore()
    
    def configureRamanControl(self):
148 149 150 151
        """
        Launches a window for updating Raman instrument configuration.
        :return:
        """
152 153 154 155 156 157
        self.configWin = RamanConfigWin(self)
        self.configWin.show()
    
    def saveDataSet(self):
        if self.dataset is not None:
            self.dataset.save()
JosefBrandt's avatar
 
JosefBrandt committed
158

159 160
    @QtCore.pyqtSlot() 
    def zoomIn(self):
161
        self.zoomDisplay(1.25)
162 163 164

    @QtCore.pyqtSlot() 
    def zoomOut(self):
165
        self.zoomDisplay(0.8)
166 167 168 169 170 171 172 173 174

    @QtCore.pyqtSlot() 
    def normalSize(self):
        self.scaleFactor = 1.0
        self.setTransform(QtGui.QTransform.fromScale(1., 1.))
        self.announceScaling()

    @QtCore.pyqtSlot() 
    def fitToWindow(self):
175 176 177 178
        """
        Fits the window to show the entire sample.
        :return:
        """
179 180 181 182 183 184
        brect = self.item.sceneBoundingRect()
        self.fitInView(0, 0, brect.width(), brect.height(), QtCore.Qt.KeepAspectRatio)
        self.scaleFactor = self.transform().m11()
        self.announceScaling()
        
    def switchMode(self, mode, loadnew=False):
185 186 187 188
        """
        Switch the gepard to another module
        :return:
        """
189 190 191
        if mode is None:
            return
        assert mode in ["OpticalScan", "ParticleDetection", "RamanScan", "ParticleAnalysis"]
192
        print("switching to mode:", mode, flush=True)
193 194 195 196
        self.oscanwidget.setVisible(False)
        if self.detectionwidget is not None:
            self.detectionwidget.close()
            self.detectionwidget.destroy()
197
            self.detectionwidget = None
198 199 200 201 202 203 204 205 206 207 208 209
        self.ramanwidget.setVisible(False)
        self.mode = mode
        self.loadPixmap(self.microscopeMode)
        if mode == "OpticalScan":
            self.oscanwidget.setVisible(True)
            self.oscanwidget.resetDataset(self.dataset)
            
        elif mode == "ParticleDetection":
            if self.detectionwidget is None:
                self.detectionwidget = ParticleDetectionView(self.imgdata, self.dataset, self)
                self.detectionwidget.imageUpdate.connect(self.detectionUpdate)
                self.detectionwidget.detectionFinished.connect(self.activateMaxMode)
210
            self.detectionwidget.show()
211 212 213 214 215 216 217 218 219 220 221 222
            
        elif mode == "RamanScan":
            self.ramanwidget.resetDataset(self.dataset)
            self.ramanwidget.setVisible(True)
            
        elif mode == "ParticleAnalysis":
            if self.ramanwidget.isVisible():
                self.ramanwidget.setVisible(False)
            if self.analysiswidget is None:
                print('creating new analysiswidget')
                self.analysiswidget = ParticleAnalysis(self.dataset, self)
                self.analysiswidget.showMaximized()
223
                self.setupParticleEditor()
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            else:
                print('show maximized already exisiting analysiswidget')
                self.analysiswidget.showMaximized()
            
            if self.detectionwidget is not None:
                self.detectionwidget.setVisible(False)
            
            #show legend:
            self.imparent.legend.show()    
        
        if loadnew:
            self.fitToWindow()
        self.imparent.updateModes(mode, self.getMaxMode())
        
    def open(self, fname):       
        self.saveDataSet()
        
        #close all widgets
        for widget in [self.detectionwidget, self.ramanwidget, self.oscanwidget, self.analysiswidget]:
            if widget is not None:
                widget.close()
                widget.destroy()
                del widget
247
                
248
        self.dataset = loadData(fname)
249
        self.setupParticleEditor()
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        self.setMicroscopeMode()
        self.imparent.setWindowTitle(self.dataset.name + (" SIMULATION" if simulatedRaman else ""))
        self.imgdata = None
        self.activateMaxMode(loadnew=True)
        self.imparent.snapshotAct.setEnabled(True)
        
    def importProject(self, fname):
        zimp = ZeissImporter(fname, self.ramanctrl, self)
        if zimp.validimport:
            zimp.exec()
            if zimp.result() == QtWidgets.QDialog.Accepted:
                self.open(zimp.gepardname)
        
    def new(self, fname):
        self.saveDataSet()
        if self.dataset is not None:
            self.dataset.save()
        self.dataset = DataSet(fname, newProject=True)
268
        self.setupParticleEditor()
269 270 271 272 273 274
        self.setMicroscopeMode()
        self.imparent.setWindowTitle(self.dataset.name + (" SIMULATION" if simulatedRaman else ""))
        self.imgdata = None
        self.activateMaxMode(loadnew=True)
        self.imparent.snapshotAct.setEnabled(True)
    
275
    def setupParticleEditor(self):
276 277 278 279
        """
        Setting up the particle editor for editing properties or contours of particles. 
        It needs some connections to sampleview and analysisview.
        """
JosefBrandt's avatar
 
JosefBrandt committed
280 281 282 283 284 285
        def tryDisconnectingSignal(signal):
            try: 
                signal.disconnect()
            except TypeError:
                pass
            
286 287
        if self.particleEditor is None:
            self.particleEditor = ParticleEditor(self, self.dataset.particleContainer)
288
            
JosefBrandt's avatar
 
JosefBrandt committed
289 290
        tryDisconnectingSignal(self.particleEditor.particleAssignmentChanged)
        if self.analysiswidget is not None:
291
            self.particleEditor.particleAssignmentChanged.connect(self.analysiswidget.updatePlotsAndContours)
292
            self.particleEditor.particleAssignmentChanged.connect(self.analysiswidget.updateWidgetContents)
293

294
    def setMicroscopeMode(self):
295 296 297 298 299
        """
        The opical microscope can be in either Brightfield (bf) or Darkfield (df) mode. In the case of the Renishaw instrument
        this mode affects the current image size in µm. Hence, gepard needs to be aware of the current mode
        :return:
        """
300 301 302 303 304 305 306
        if self.ramanSwitchNeeded:
            self.imparent.ramanSwitch.connectToSampleView()
            self.imparent.ramanSwitch.show()
        self.microscopeMode = ('df' if self.imparent.ramanSwitch.df_btn.isChecked() else 'bf')
    
    @QtCore.pyqtSlot()    
    def activateMaxMode(self, loadnew=False):
307 308 309 310 311
        """
        Activates the "highest" available mode of gepard. The modes follow gepard's operation workflow: 
            OpticalScan, ParticleDetection, RamanScan, ParticleAnalysis
        :return:
        """
312 313 314 315 316
        mode = self.getMaxMode()
        self.imparent.updateModes(self.mode, self.getMaxMode())
        self.switchMode(mode, loadnew=loadnew)
        
    def getMaxMode(self):
317 318 319 320 321
        """
        Determines the "highest" available mode of gepard. The modes follow gepard's operation workflow: 
            OpticalScan, ParticleDetection, RamanScan, ParticleAnalysis
        :return:
        """
322 323 324 325 326 327 328 329 330
        if self.dataset is None:
            return None
        if not self.ramanctrl.connected:
            self.connectRaman()
        if not self.ramanctrl.connected:
            return None
        maxmode = "OpticalScan"
        if os.path.exists(self.dataset.getImageName()):
            maxmode = "ParticleDetection"
331
            if self.dataset.particleDetectionDone:
332
                maxmode = "RamanScan"
JosefBrandt's avatar
 
JosefBrandt committed
333
            if self.dataset.ramanscandone:  
334 335
                maxmode = "ParticleAnalysis"
        return maxmode
336 337 338 339 340 341 342 343 344 345
    
    def blockUI(self):
        self.isblocked = True
        self.imparent.blockUI()
        
    def unblockUI(self):
        self.isblocked = False
        self.imparent.unblockUI(self.ramanctrl.connected)
        self.imparent.updateModes(self.mode, self.getMaxMode())
        
346
    def mousePressEvent(self, event):
JosefBrandt's avatar
 
JosefBrandt committed
347 348 349
        if event.button()==QtCore.Qt.MiddleButton:
            self.drag = event.pos()
        
350
        if self.particlePainter is None:
JosefBrandt's avatar
 
JosefBrandt committed
351
            if event.button()==QtCore.Qt.LeftButton:
352 353
                if self.analysiswidget is not None:
                    self.checkForContourSelection(event)
354
                
JosefBrandt's avatar
 
JosefBrandt committed
355 356 357 358 359 360 361
                if self.mode in ["OpticalScan", "RamanScan"] and event.modifiers()==QtCore.Qt.ControlModifier:
                    p0 = self.mapToScene(event.pos())
                    self.moveStageToPosition(p0)
                    
                elif self.mode=="ParticleDetection":
                    p0 = self.mapToScene(event.pos())
                    self.detectionwidget.setImageCenter([p0.x(), p0.y()])
362 363 364 365
                
                else:
                    p0 = self.mapToScene(event.pos())
                    super(SampleView, self).mousePressEvent(event)
366
            
367
        else:
JosefBrandt's avatar
 
JosefBrandt committed
368 369
            self.particlePainter.mousePressEvent(event)

370 371 372 373 374 375 376 377
    def mouseMoveEvent(self, event):
        if self.drag is not None:
            p0 = event.pos()
            move = self.drag-p0
            self.horizontalScrollBar().setValue(move.x() + self.horizontalScrollBar().value())
            self.verticalScrollBar().setValue(move.y() + self.verticalScrollBar().value())
            
            self.drag = p0
JosefBrandt's avatar
 
JosefBrandt committed
378 379
        elif self.particlePainter is None:
            p0 = self.mapToScene(event.pos())
380
            super(SampleView, self).mouseMoveEvent(event)
JosefBrandt's avatar
 
JosefBrandt committed
381 382
        else:
            self.particlePainter.mouseMoveEvent(event)
383 384 385
                        
    def mouseReleaseEvent(self, event):
        self.drag = None
JosefBrandt's avatar
 
JosefBrandt committed
386 387 388 389
        if self.particlePainter is None:
            super(SampleView, self).mouseReleaseEvent(event)
        else:
            self.particlePainter.mouseReleaseEvent(event)
390 391
        
    def wheelEvent(self, event):
JosefBrandt's avatar
 
JosefBrandt committed
392 393
        if self.particlePainter is None:
            factor = 1.01**(event.angleDelta().y()/8)
394
            self.zoomDisplay(factor)
JosefBrandt's avatar
 
JosefBrandt committed
395 396 397 398 399 400 401 402
        else:
            self.particlePainter.wheelEvent(event)
            
    def keyPressEvent(self, event):
        if self.particlePainter is not None:
            self.particlePainter.keyPressEvent(event)
    
    def moveStageToPosition(self, pos):
403 404 405 406
        """
        Sends a command to the ramancontrol to move the microscope stage to the position of the click event.
        :return:
        """
JosefBrandt's avatar
 
JosefBrandt committed
407 408 409 410 411 412 413 414 415 416
        if self.dataset is not None and self.dataset.pshift is not None:
            if self.dataset.readin:
                reply = QtWidgets.QMessageBox.critical(self, 'Dataset is newly read from disk!',
                    "Coordinate systems might have changed since. Do you want to continue with saved coordinates?", 
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
        
                if reply == QtWidgets.QMessageBox.Yes:
                    self.dataset.readin = False
                else:
                    return
417

JosefBrandt's avatar
 
JosefBrandt committed
418 419 420 421 422 423
            noz = (self.mode in ['OpticalScan', 'RamanScan'])
            x, y, z = self.dataset.mapToLengthRaman([pos.x(), pos.y()], microscopeMode=self.microscopeMode, noz=noz)
            if z is not None:
                assert z>-100.
            self.ramanctrl.moveToAbsolutePosition(x, y, z)
    
JosefBrandt's avatar
 
JosefBrandt committed
424
    def checkForContourSelection(self, event):
425 426 427 428
        """
        Checks, if at the given event position any contour is selected.
        :return:
        """
JosefBrandt's avatar
 
JosefBrandt committed
429
        def acceptSelection(cnt):
430
            self.ParticleOfIndexSelected.emit(cnt.particleIndex)
JosefBrandt's avatar
 
JosefBrandt committed
431 432
            cnt.isSelected = True
            cnt.update()
Josef Brandt's avatar
Josef Brandt committed
433 434
            if cnt.particleIndex not in self.selectedParticleIndices:
                self.selectedParticleIndices.append(cnt.particleIndex)
435
                
JosefBrandt's avatar
 
JosefBrandt committed
436 437 438
        def removeContourFromSelection(cnt):
            cnt.isSelected = False
            cnt.update()
JosefBrandt's avatar
 
JosefBrandt committed
439
            self.selectedParticleIndices.remove(cnt.particleIndex)
440
        
JosefBrandt's avatar
 
JosefBrandt committed
441 442 443 444
        p = self.mapToScene(event.pos())
        p = QtCore.QPointF(p.x(), p.y())
        
        for index, cnt in enumerate(self.contourItems):
445
            
JosefBrandt's avatar
 
JosefBrandt committed
446 447
            if cnt.polygon.containsPoint(p, QtCore.Qt.OddEvenFill):   #clicked on particle
                if not event.modifiers()==QtCore.Qt.ShiftModifier:
JosefBrandt's avatar
 
JosefBrandt committed
448
                    acceptSelection(cnt)
JosefBrandt's avatar
 
JosefBrandt committed
449
                else:
JosefBrandt's avatar
 
JosefBrandt committed
450
                    if cnt.particleIndex not in self.selectedParticleIndices:
JosefBrandt's avatar
 
JosefBrandt committed
451
                        acceptSelection(cnt)
JosefBrandt's avatar
 
JosefBrandt committed
452
                    elif cnt.particleIndex in self.selectedParticleIndices:
JosefBrandt's avatar
 
JosefBrandt committed
453 454 455
                        removeContourFromSelection(cnt)
            
            else:    #not clicked on particle
JosefBrandt's avatar
JosefBrandt committed
456 457 458 459 460
                if event.modifiers()!=QtCore.Qt.ShiftModifier:
                    cnt.isSelected = False
                    cnt.update()
                    if cnt.particleIndex in self.selectedParticleIndices:
                        self.selectedParticleIndices.remove(cnt.particleIndex)
JosefBrandt's avatar
JosefBrandt committed
461 462

        if len(self.selectedParticleIndices) > 0:
JosefBrandt's avatar
JosefBrandt committed
463
            self.updateParticleInfoBox(self.selectedParticleIndices[-1])
JosefBrandt's avatar
JosefBrandt committed
464
        else:
JosefBrandt's avatar
JosefBrandt committed
465
            self.removeParticleInfoBox()
JosefBrandt's avatar
JosefBrandt committed
466
            
JosefBrandt's avatar
 
JosefBrandt committed
467
        self.update()
JosefBrandt's avatar
 
JosefBrandt committed
468

469 470 471 472 473
    def zoomDisplay(self, factor):
        """
        Zooms the GraphicsView in or out, according to the given factor.
        :return:
        """
474 475 476 477 478 479 480 481 482
        if factor<1 and not self.imparent.zoomOutAct.isEnabled():
            return
        if factor>1 and not self.imparent.zoomInAct.isEnabled():
            return
        self.scaleFactor *= factor      
        self.scale(factor, factor)
        self.announceScaling()
        
    def announceScaling(self):
483 484 485 486
        """
        Processes a new scaling of the GraphicsView.
        :return:
        """
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        pixelscale = self.dataset.getPixelScale(self.microscopeMode)
        if self.dataset is None or pixelscale is None:
            self.ScalingChanged.emit(-1.0)
        else:
            self.ScalingChanged.emit(pixelscale/self.scaleFactor)           ##CURRENTLY ONLY DARKFIELD!!! FIX NEEDED!!!
        
    def connectRaman(self):
        if not self.ramanctrl.connect():
            msg = QtWidgets.QMessageBox()
            msg.setText("Connection failed! Please enable remote control.")
            msg.exec()
        else:
            mode = self.getMaxMode()
            self.switchMode(mode)
        self.imparent.updateConnected(self.ramanctrl.connected)
    
    def disconnectRaman(self):
        self.ramanctrl.disconnect()
        self.imparent.updateConnected(self.ramanctrl.connected)

    @QtCore.pyqtSlot(str)
    def detectionUpdate(self):
509 510 511 512
        """
        Is connected to particle detection. When a new segmentation result was obtained, the sampleview has to update here.
        :return:
        """
513
        self.resetParticleContours()
514 515 516 517 518
        self.prepareAnalysis()
        self.update()

    @QtCore.pyqtSlot(str) 
    def loadPixmap(self, microscope_mode='df'):
519 520 521 522 523
        """
        Loads the pixmap image as background for the GraphicsView.
        It is stored in self.imgdata
        :return:
        """
524 525 526 527 528 529 530
        self.clearItems()
        if self.dataset is None:
            self.item.setPixmap(QtGui.QPixmap())
        else:
            data = self.imgdata
            fname = self.dataset.getImageName()
            if self.mode == "ParticleDetection" or self.mode == "ParticleAnalysis":
531
                self.resetParticleContours()
532
            if data is None and os.path.exists(fname):
533 534
#                data = cv2.cvtColor(cv2imread_fix(fname), cv2.COLOR_BGR2RGB)   ##With this line the B and R channel are swapped, which leads to a wrong presentation of the image in gepard..... Why was this line here?
                data = cv2imread_fix(fname)
535 536 537 538 539 540 541 542
                self.imgdata = data
            if data is not None:
                height, width, channel = data.shape
                bytesPerLine = 3 * width
                pix = QtGui.QPixmap()
                pix.convertFromImage(QtGui.QImage(data.data, 
                                width, height, bytesPerLine, QtGui.QImage.Format_RGB888))
                self.item.setPixmap(pix)
543
                
544 545 546 547 548 549
                if self.darkenPixmap:
                    self.scene().setBackgroundBrush(QtGui.QColor(5, 5, 5))
                    self.item.setOpacity(0.2)
                else:
                    self.scene().setBackgroundBrush(QtCore.Qt.darkGray)
                    self.item.setOpacity(1)
JosefBrandt's avatar
 
JosefBrandt committed
550

551
            else:
552
                self.item.setPixmap(QtGui.QPixmap())
553 554 555 556 557 558 559 560 561 562 563
            if self.mode == "OpticalScan":
                for i, p in zip(self.dataset.fitindices, self.dataset.fitpoints):
                    p = self.dataset.mapToPixel(p, mode=microscope_mode, force=True)
                    fititem = FitPosIndicator(i+1, pos=p)
                    self.scene().addItem(fititem)
                    self.fititems.append(fititem)                    
            if self.mode == "ParticleDetection" or self.mode == "ParticleAnalysis":
                self.prepareAnalysis()
            else:
                self.fitToWindow()
    
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
    def prepareAnalysis(self):
        """
        Is called after final particle detection. Raman Scan Indicators are added.
        """
        self.clearItems()
        if self.dataset.particleDetectionDone:
            for meas in self.dataset.particleContainer.measurements:
                if meas.ramanScanIndex is not None:
                    number = meas.ramanScanIndex+1
                    item = RamanScanIndicator(self, number, 20, (meas.pixelcoord_x, meas.pixelcoord_y))
                    self.scene().addItem(item)
                    self.ramanscanitems.append(item)
    
    def clearItems(self):
        """
        Removes items from the GraphicsScene. ContourItems remain, however..
        :return:
        """
        for itemList in [self.fititems, self.scanitems, self.ramanscanitems]:
            for item in itemList:
                self.scene().removeItem(item)
            itemList = []
        
        edges, nodes = self.boundaryitems
        for item in edges:
            self.scene().removeItem(item)
        for item in nodes:
            self.scene().removeItem(item)
        self.boundaryitems = [], []

    
595 596
    @QtCore.pyqtSlot()        
    def resetScanPositions(self):
597 598 599 600 601
        """
        Calculates position of scan tiles for the optical scan, according to the boundary and the polygoncovering method.
        The corresponding graphic items are added to the scene.
        :return:
        """
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 629 630 631 632 633 634 635 636 637 638
        micMode = ('df' if self.oscanwidget.df_btn.isChecked() else 'bf')
        for item in self.scanitems:
            self.scene().removeItem(item)
        edges, nodes = self.boundaryitems
        boundary = []
        for n in nodes:
            p = n.pos().x(), n.pos().y()
            boundary.append(self.dataset.mapToLength(p, self.microscopeMode, force=True))
        boundary = np.array(boundary)
        self.dataset.boundary = boundary
        if micMode == 'df':
            width, height, angle = self.dataset.imagedim_df
        else:
            width, height, angle = self.dataset.imagedim_bf
        
        margin = min(width, height)*0.02
        wx, wy = width-margin, height-margin
        print(wx,wy)
        p1 = polygoncovering(boundary, wx, wy)
        b2 = boundary.copy()
        b2 = b2[:,[1,0]]
        p2 = polygoncovering(b2, wy, wx)
        if len(p2)<len(p1):
            p1 = [[pi[1],pi[0]] for pi in p2]
        self.dataset.grid = p1
        pixelscale = self.dataset.getPixelScale(self.microscopeMode)
        wxs, wys = width/pixelscale, height/pixelscale
        
        self.scanitems = []
        for i, p in enumerate(p1):
            p = self.dataset.mapToPixel(p, self.microscopeMode, force=True)
            s = ScanIndicator(i+1, wxs, wys, p)
            self.scene().addItem(s)
            self.scanitems.append(s)
    
    @QtCore.pyqtSlot()        
    def resetBoundary(self):
639 640 641 642
        """
        Resets the Boundary Items in the GraphicsView.
        :return:
        """
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
        micMode = self.microscopeMode
        edges, nodes = self.boundaryitems
        for item in edges:
            self.scene().removeItem(item)
        for item in nodes:
            self.scene().removeItem(item)
        edges, nodes = [], []
        for p in self.dataset.boundary:
            p = self.dataset.mapToPixel(p, micMode, force=True)
            n = Node(p, self)
            nodes.append(n)
            self.scene().addItem(n)
        for i in range(len(nodes)):
            e = Edge(nodes[i-1], nodes[i])
            edges.append(e)
            self.scene().addItem(e)
        self.boundaryitems = edges, nodes
        self.resetScanPositions()
    
662
    def resetParticleContours(self):
663 664 665 666
        """
        Resets the Contour Indicator Items in the GraphicsView.
        :return:
        """
JosefBrandt's avatar
 
JosefBrandt committed
667
        t0 = time.time()
JosefBrandt's avatar
 
JosefBrandt committed
668 669 670 671
        for cnt in self.contourItems:
            self.scene().removeItem(cnt)
        self.contourItems = []
        if self.dataset is not None:
672 673
            for particle in self.dataset.particleContainer.particles:
                self.addParticleContourToIndex(particle.contour, particle.index)
674
            self.update()
JosefBrandt's avatar
 
JosefBrandt committed
675 676
        print('resetted contours: {} ms'.format(round((time.time()-t0)*1000)))
        
JosefBrandt's avatar
JosefBrandt committed
677
    def addParticleContourToIndex(self, contour, index):
678 679 680 681
        """
        Creates and adds a new ContourItem to the particle of a given index.
        :return:
        """
JosefBrandt's avatar
 
JosefBrandt committed
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
        newCnt = SegmentationContour(self, contour)
        newCnt.setIndex(index)
        assignment = self.dataset.particleContainer.getParticleAssignmentByIndex(index)
        color = getColorFromNameWithSeed(assignment, self.dataset.colorSeed)
        newCnt.setColor(QtGui.QColor(color[0], color[1], color[2], 255))
        self.contourItems.append(newCnt)
        self.scene().addItem(newCnt)
    
    def removeParticleContour(self, contourIndex):
        correspondingParticle = self.dataset.particleContainer.getParticleOfIndex(contourIndex)   #this checks validity of contourIndex
        self.scene().removeItem(self.contourItems[contourIndex])
        del self.contourItems[contourIndex]
    
    def resetContourIndices(self):
        for index, contour in enumerate(self.contourItems):
            contour.setIndex(index)    
    
JosefBrandt's avatar
 
JosefBrandt committed
699
    def updateLegend(self, legendItems):
700 701 702 703
        """
        Updates the color legend in the graphics view.
        :return:
        """
JosefBrandt's avatar
 
JosefBrandt committed
704 705
        self.imparent.legend.setTextColorItems(legendItems)
    
706
    def highLightContour(self, index):
707 708 709 710
        """
        Highlights a contour and fits the GraphicsView to the particle and its infobox.
        :return:
        """
711 712
        for contour in self.contourItems:
            contour.isSelected = False
713 714 715
            
        contour = self.contourItems[index]
        contour.isSelected = True
JosefBrandt's avatar
JosefBrandt committed
716
        self.selectedParticleIndices =[index]
717
       
JosefBrandt's avatar
JosefBrandt committed
718
        self.updateParticleInfoBox(index)
719
        self.fitToParticleAndInfoBox()
JosefBrandt's avatar
JosefBrandt committed
720 721 722 723 724
        self.update()
    
    def updateParticleInfoBox(self, particleIndex):
        self.removeParticleInfoBox()
        self.addParticleInfoBox(particleIndex)
725
        
JosefBrandt's avatar
JosefBrandt committed
726
    def removeParticleInfoBox(self):
JosefBrandt's avatar
JosefBrandt committed
727 728
        if self.particleInfoBox is not None:
            self.scene().removeItem(self.particleInfoBox)
JosefBrandt's avatar
JosefBrandt committed
729 730 731 732
            self.particleInfoBox = None
    
    def addParticleInfoBox(self, particleIndex):
        self.particleInfoBox = ParticleInfo(self.dataset.particleContainer.getParticleOfIndex(particleIndex))
JosefBrandt's avatar
JosefBrandt committed
733
        self.scene().addItem(self.particleInfoBox)
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
        
    def fitToParticleAndInfoBox(self):
        """
        Fits the view to display the current particleInfoBox and its associated particle
        ;return:
        """
        def getGlobalBrect(graphItem):
            """
            Calculates bounding rect relative to scene origin (0,0)
            :return:
            """
            top = graphItem.pos().y() + graphItem.brect.top()
            left = graphItem.pos().x() + graphItem.brect.left()
            width = graphItem.brect.width()
            height = graphItem.brect.height()
            return QtCore.QRectF(left, top, width, height)
        
        def combineRects(rect1, rect2, margin=20):
            """
            Calculates a combined bounding rect.
            :return:
            """
            top = min(rect1.top(), rect2.top()) - margin/2
            left = min(rect1.left(), rect2.left()) - margin/2
            bottom = max((rect1.top()+rect1.height()), (rect2.top()+rect2.height())) + margin/2
            right = max((rect1.left()+rect1.width()), (rect2.left()+rect2.width())) + margin/2
            return QtCore.QRectF(left, top, (right-left), (bottom-top))
JosefBrandt's avatar
JosefBrandt committed
761
    
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
        infoBoxRect = getGlobalBrect(self.particleInfoBox)
        particleIndex = self.particleInfoBox.particle.index
        selectedContour = self.contourItems[particleIndex]
        contourRect = getGlobalBrect(selectedContour)
        viewRect = combineRects(infoBoxRect, contourRect)
        self.fitInView(viewRect, QtCore.Qt.KeepAspectRatio)
        self.scaleFactor = self.transform().m11()
        self.announceScaling()
    
    def centerOnRamanIndex(self, index):
        """
        Centers the graphicsView to a given ScanIndicator Item.
        :return:
        """
        for scanItem in self.ramanscanitems:
            if scanItem.number == index+1:
                self.centerOn(scanItem)
                return
JosefBrandt's avatar
JosefBrandt committed
780 781
    
    def highLightRamanIndex(self, index):
782 783 784 785
        """
        Sets highlight parameter of a given ScanIndicator Item.
        :return:
        """
JosefBrandt's avatar
JosefBrandt committed
786 787 788 789 790 791
        if index < len(self.ramanscanitems):
            for item in self.ramanscanitems:
                if item.number == index+1:
                    item.setHighLight(True)
                else:
                    item.setHighLight(False)
792
        
793

794

795