particleeditor.py 11.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
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 12:43:00 2019

@author: brandt
"""

"""
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/>.
"""
Lars Bittrich's avatar
Lars Bittrich committed
27

28 29
import numpy as np
import cv2
JosefBrandt's avatar
 
JosefBrandt committed
30
from PyQt5 import QtWidgets, QtCore
31

JosefBrandt's avatar
 
JosefBrandt committed
32 33
from analysis.particlePainter import ParticlePainter

JosefBrandt's avatar
 
JosefBrandt committed
34 35 36
class ParticleContextMenu(QtWidgets.QMenu):
    combineParticlesSignal = QtCore.pyqtSignal(list, str)
    reassignParticlesSignal = QtCore.pyqtSignal(list, str)
JosefBrandt's avatar
 
JosefBrandt committed
37
    paintParticlesSignal = QtCore.pyqtSignal(list, str)
JosefBrandt's avatar
JosefBrandt committed
38 39
    deleteParticlesSignal = QtCore.pyqtSignal(list)
    
JosefBrandt's avatar
 
JosefBrandt committed
40
    def __init__(self, viewparent):
JosefBrandt's avatar
 
JosefBrandt committed
41
        super(ParticleContextMenu, self).__init__()
JosefBrandt's avatar
 
JosefBrandt committed
42 43 44
        self.viewparent = viewparent
        self.selectedParticleIndices = self.viewparent.selectedParticleIndices
        self.particleContainer = self.viewparent.dataset.particleContainer
JosefBrandt's avatar
 
JosefBrandt committed
45 46 47 48
        
    def executeAtScreenPos(self, screenPos):
        self.combineActs = []
        self.combineMenu = QtWidgets.QMenu("Combine Particles into")
JosefBrandt's avatar
 
JosefBrandt committed
49 50 51 52 53

        self.paintActs = []
        self.paintMenu = QtWidgets.QMenu("Paint Mode, merge into")

        selctedAssignments = []
JosefBrandt's avatar
 
JosefBrandt committed
54 55

        for particleIndex in self.selectedParticleIndices:
JosefBrandt's avatar
 
JosefBrandt committed
56 57 58 59
            try:
                assignment = self.particleContainer.getParticleAssignmentByIndex(particleIndex)
            except:
                return
JosefBrandt's avatar
 
JosefBrandt committed
60
            selctedAssignments.append(assignment)
JosefBrandt's avatar
 
JosefBrandt committed
61
        
JosefBrandt's avatar
 
JosefBrandt committed
62
        for assignment in np.unique(selctedAssignments):
JosefBrandt's avatar
 
JosefBrandt committed
63
            self.combineActs.append(self.combineMenu.addAction(assignment))
JosefBrandt's avatar
 
JosefBrandt committed
64
            self.paintActs.append(self.paintMenu.addAction(assignment))
JosefBrandt's avatar
 
JosefBrandt committed
65
        self.combineActs.append(self.combineMenu.addAction("other"))
JosefBrandt's avatar
 
JosefBrandt committed
66 67
        self.paintActs.append(self.paintMenu.addAction("other"))
        
JosefBrandt's avatar
 
JosefBrandt committed
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
        
        self.reassignActs = []
        self.reassignMenu = QtWidgets.QMenu("Reassign particle(s) into")
        for polymType in self.particleContainer.getUniquePolymers():
            self.reassignActs.append(self.reassignMenu.addAction(polymType))
        self.reassignActs.append(self.reassignMenu.addAction("other"))
        
        numParticles = len(self.selectedParticleIndices)
        if numParticles == 0:
            self.reassignMenu.setDisabled(True)
            self.combineMenu.setDisabled(True)
        elif numParticles == 1:
            self.combineMenu.setDisabled(True)
            
        self.addMenu(self.combineMenu)        
        self.addMenu(self.reassignMenu)
JosefBrandt's avatar
 
JosefBrandt committed
84
        self.addMenu(self.paintMenu)
JosefBrandt's avatar
JosefBrandt committed
85
        self.deleteAct = self.addAction("Delete particle(s)")
JosefBrandt's avatar
 
JosefBrandt committed
86 87 88
        
        action = self.exec_(screenPos)

JosefBrandt's avatar
 
JosefBrandt committed
89
        if action:
90
            newAssignment = self.validifyAssignment(action.text())
JosefBrandt's avatar
 
JosefBrandt committed
91 92 93 94 95 96 97

            if action in self.combineActs:
                self.combineParticlesSignal.emit(self.selectedParticleIndices, newAssignment)
            elif action in self.reassignActs:
                self.reassignParticlesSignal.emit(self.selectedParticleIndices, newAssignment)
            elif action in self.paintActs:
                self.paintParticlesSignal.emit(self.selectedParticleIndices, newAssignment)
JosefBrandt's avatar
JosefBrandt committed
98 99
            elif action == self.deleteAct:
                self.deleteParticlesSignal.emit(self.selectedParticleIndices)
100 101 102 103 104 105 106
    
    def validifyAssignment(self, assignment):
        if assignment == "other":
            assignment = self.getNewEntry()
        return assignment
    
    def getNewEntry(self):
JosefBrandt's avatar
 
JosefBrandt committed
107
        text, okClicked = QtWidgets.QInputDialog.getText(self.viewparent, "Custom assignment", "Enter new assignment")
108 109
        if okClicked and text != '':
            return text
JosefBrandt's avatar
 
JosefBrandt committed
110 111 112


class ParticleEditor(QtCore.QObject):
113
#    particleContoursChanged = QtCore.pyqtSignal()
JosefBrandt's avatar
 
JosefBrandt committed
114
    particleAssignmentChanged = QtCore.pyqtSignal()
JosefBrandt's avatar
 
JosefBrandt committed
115
    def __init__(self, viewparent, particleContainer):
JosefBrandt's avatar
 
JosefBrandt committed
116
        super(ParticleEditor, self).__init__()
JosefBrandt's avatar
 
JosefBrandt committed
117
        self.particleContainer = particleContainer
JosefBrandt's avatar
 
JosefBrandt committed
118
        self.viewparent = viewparent #the assigned analysis widget
Hackmet's avatar
Hackmet committed
119 120 121
        self.backupFreq = 3     #save a backup every n actions
        self.neverBackedUp = True
        self.actionCounter = 0
JosefBrandt's avatar
 
JosefBrandt committed
122 123 124
        
        self.storedIndices = []
        self.storedAssignmend = None
JosefBrandt's avatar
 
JosefBrandt committed
125 126 127 128
    
    def connectToSignals(self, contextMenu):
        contextMenu.combineParticlesSignal.connect(self.combineParticles)
        contextMenu.reassignParticlesSignal.connect(self.reassignParticles)
JosefBrandt's avatar
 
JosefBrandt committed
129
        contextMenu.paintParticlesSignal.connect(self.paintParticles)
JosefBrandt's avatar
JosefBrandt committed
130
        contextMenu.deleteParticlesSignal.connect(self.deleteParticles)
JosefBrandt's avatar
 
JosefBrandt committed
131
    
132
    def createSafetyBackup(self):
Hackmet's avatar
Hackmet committed
133 134
        self.actionCounter += 1
        if self.actionCounter == self.backupFreq-1 or self.neverBackedUp:            
JosefBrandt's avatar
 
JosefBrandt committed
135
            backupname = self.viewparent.dataset.saveBackup()
Hackmet's avatar
Hackmet committed
136
            print('backing up as', backupname)
Hackmet's avatar
Hackmet committed
137
            self.neverBackedUp = False
JosefBrandt's avatar
 
JosefBrandt committed
138
            self.actionCounter = 0        
Hackmet's avatar
Hackmet committed
139
    
JosefBrandt's avatar
 
JosefBrandt committed
140
    @QtCore.pyqtSlot(list, str)
141 142 143 144 145 146 147 148
    def combineParticles(self, contourIndices, newAssignment):     
        self.createSafetyBackup()
        print(f'Combining particles {contourIndices} into {newAssignment}')
        contours = self.particleContainer.getParticleContoursByIndex(contourIndices)
        newContour = self.mergeContours(contours.copy())        
        stats = self.characterizeParticle(newContour)

        self.particleContainer.mergeParticles(contourIndices, newContour, stats, newAssignment=newAssignment)
JosefBrandt's avatar
 
JosefBrandt committed
149 150 151 152 153 154
        for ind in contourIndices:
            self.viewparent.removeParticleContour(ind)
        
        self.viewparent.resetContourIndices()
        self.viewparent.addParticleContour(newContour, len(self.viewparent.contourItems))
        
155
        self.particleAssignmentChanged.emit()
JosefBrandt's avatar
 
JosefBrandt committed
156
        #TODO: INCLUDE SANITY CHECK!!!!!!!!!
157
    
JosefBrandt's avatar
 
JosefBrandt committed
158
    @QtCore.pyqtSlot(list, str)
159
    def reassignParticles(self, contourindices, newAssignment):
160
        self.createSafetyBackup()
161
        print(f'reassigning indices {contourindices} into {newAssignment}')
162
        for partIndex in contourindices:
163
            self.particleContainer.reassignParticleToAssignment(partIndex, newAssignment)
164

JosefBrandt's avatar
 
JosefBrandt committed
165
        self.particleAssignmentChanged.emit()
JosefBrandt's avatar
 
JosefBrandt committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
     
    @QtCore.pyqtSlot(list, str)
    def paintParticles(self, contourIndices, newAssignment):
        self.createSafetyBackup
        self.storedIndices = contourIndices
        self.storedAssignmend = newAssignment
        contours = self.particleContainer.getParticleContoursByIndex(contourIndices)
        self.particlePainter = ParticlePainter(self, contours)
        self.viewparent.normalSize()
        self.viewparent.particlePainter = self.particlePainter
        self.viewparent.scene().addItem(self.particlePainter)
        self.viewparent.update()
        
    def acceptPaintedResult(self):
        newContour = self.mergeContours(self.particlePainter.contours.copy())
        stats = self.characterizeParticle(newContour)
        
        self.particleContainer.mergeParticles(self.storedIndices, newContour, stats, newAssignment=self.storedAssignmend)
        for ind in self.storedIndices:
            self.viewparent.removeParticleContour(ind)
        
187
        self.particleAssignmentChanged.emit()
JosefBrandt's avatar
 
JosefBrandt committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201
        self.viewparent.resetContourIndices()
        self.viewparent.addParticleContour(newContour, len(self.viewparent.contourItems))
        
        #TODO: INCLUDE SANITY CHECK!!!!!!!!!
        self.storedIndices = []
        self.storedAssignmend = None
        self.destroyParticlePainter()
    
    def destroyParticlePainter(self):
        if self.particlePainter is not None:
            self.viewparent.particlePainter = None
            self.viewparent.scene().removeItem(self.particlePainter)
            self.viewparent.update()
            self.particlePainter = None
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    
    def mergeContours(self, contours):
        cnt = np.vstack(tuple(contours))  #combine contous
        #draw contours
        xmin, xmax = cnt[:,0,:][:, 0].min(), cnt[:,0,:][:, 0].max()
        ymin, ymax = cnt[:,0,:][:, 1].min(), cnt[:,0,:][:, 1].max()        
        padding = 2    #pixel in each direction
        rangex = int(np.round((xmax-xmin)+2*padding))
        rangey = int(np.round((ymax-ymin)+2*padding))

        img = np.zeros((rangey, rangex))
        for curCnt in contours:
            for i in range(len(curCnt)):
                curCnt[i][0][0] -= xmin-padding
                curCnt[i][0][1] -= ymin-padding
                
            cv2.drawContours(img, [curCnt], -1, 1, -1)
            cv2.drawContours(img, [curCnt], -1, 1, 1)
        
        img = np.uint8(cv2.morphologyEx(img, cv2.MORPH_CLOSE, np.ones((3, 3))))
        
        if cv2.__version__ > '3.5':
            contours, hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
        else:
            temp, contours, hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)

        if len(contours)>1:
JosefBrandt's avatar
 
JosefBrandt committed
229
            QtWidgets.QMessageBox.critical(self.viewparent, 'ERROR!', 
230 231 232 233 234 235 236
                                           'Particle contours are not connected and cannot be combined!')
            return
        
        newContour = contours[0]
        for i in range(len(newContour)):
            newContour[i][0][0] += xmin-padding
            newContour[i][0][1] += ymin-padding
237
            
238 239
        return newContour
        
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    def characterizeParticle(self, contours):
        ##characterize particle
        longellipse, shortellipse = np.nan, np.nan
        
        cnt = contours
        
        if cnt.shape[0] >= 5:       ##at least 5 points required for ellipse fitting...
            ellipse = cv2.fitEllipse(cnt)
            shortellipse, longellipse = ellipse[1]

        rect = cv2.minAreaRect(cnt)
        long, short = rect[1]
        if short>long:
            long, short = short, long
    
        return long, short, longellipse, shortellipse, cv2.contourArea(cnt)
JosefBrandt's avatar
 
JosefBrandt committed
256

JosefBrandt's avatar
JosefBrandt committed
257 258 259 260 261 262
    @QtCore.pyqtSlot(list)
    def deleteParticles(self, contourIndices):
        reply = QtWidgets.QMessageBox.question(self, f'About to delete {len(contourIndices)} particles.',
                                "Are you sure to permanantly delete these particles?",
                                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
        if reply == QtWidgets.QMessageBox.Yes:
Hackmet's avatar
Hackmet committed
263

JosefBrandt's avatar
JosefBrandt committed
264 265 266 267 268 269 270 271 272
            for partIndex in sorted(contourIndices, reverse=True):
                self.viewparent.removeParticleContour(partIndex)
                self.viewparent.dataset.particleContainer.removeParticles([partIndex])
                
            self.viewparent.dataset.particleContainer.resetParticleIndices()
            self.viewparent.resetContourIndices()
            self.viewparent.analysiswidget.updateHistogramsAndContours()
        
        
Hackmet's avatar
Hackmet committed
273