particleeditor.py 8.72 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
Hackmet's avatar
Hackmet committed
30
from PyQt5 import QtWidgets
31 32

class ParticleEditor(object):
JosefBrandt's avatar
 
JosefBrandt committed
33 34
    def __init__(self, particleContainer, parent):
        self.particleContainer = particleContainer
35
        self.parent = parent    #the assigned analysis widget
Hackmet's avatar
Hackmet committed
36 37 38
        self.backupFreq = 3     #save a backup every n actions
        self.neverBackedUp = True
        self.actionCounter = 0
39 40

    def createSafetyBackup(self):
Hackmet's avatar
Hackmet committed
41 42
        self.actionCounter += 1
        if self.actionCounter == self.backupFreq-1 or self.neverBackedUp:            
JosefBrandt's avatar
 
JosefBrandt committed
43
            backupname = self.parent.dataset.saveBackup()
Hackmet's avatar
Hackmet committed
44
            print('backing up as', backupname)
Hackmet's avatar
Hackmet committed
45 46 47 48 49 50 51 52
            self.neverBackedUp = False
            self.actionCounter = 0
        
    def getNewEntry(self):
        text, okClicked = QtWidgets.QInputDialog.getText(self.parent.parent, "Custom assignment", "Enter new assignment")
        if okClicked and text != '':
            return text
    
53
    def combineParticles(self, contourIndices, new_assignment):
Hackmet's avatar
Hackmet committed
54 55
        if new_assignment == 'other':
            new_assignment = self.getNewEntry()
56 57
        if new_assignment is None:
            return
Hackmet's avatar
Hackmet committed
58
        
59 60
        contourIndices = sorted(contourIndices)   #we want to keep the contour with lowest index
        #get contours:
JosefBrandt's avatar
 
JosefBrandt committed
61 62
        contours = self.particleContainer.getParticleContoursByIndex(contourIndices)
#        contours = [self.datastats.dataset.particlecontours[i] for i in contourIndices]
63 64 65 66 67 68 69 70 71 72 73
        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))
Hackmet's avatar
Hackmet committed
74
        for i in contourIndices:
JosefBrandt's avatar
 
JosefBrandt committed
75 76
            curCnt = self.particleContainer.getParticleContoursByIndex(i).copy()
#            curCnt = self.datastats.dataset.particlecontours[i].copy()
Hackmet's avatar
Hackmet committed
77 78 79 80 81 82 83
            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)
        
84 85
        img = np.uint8(cv2.morphologyEx(img, cv2.MORPH_CLOSE, np.ones((3, 3))))
        
86 87 88 89
        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)
90

Lars Bittrich's avatar
Lars Bittrich committed
91 92 93 94 95
        if len(contours)>1:
            QtWidgets.QMessageBox.critical(self.parent, 'ERROR!', 
                                           'Particle contours are not connected and cannot be combined!')
            return
        
96 97 98 99 100 101 102
        newContour = contours[0]
        stats = self.characterizeParticle(newContour)

        for i in range(len(newContour)):
            newContour[i][0][0] += xmin-padding
            newContour[i][0][1] += ymin-padding
        
Lars Bittrich's avatar
Lars Bittrich committed
103 104
        print('merging contours:', contourIndices)
        self.createSafetyBackup()
105
        
JosefBrandt's avatar
 
JosefBrandt committed
106 107 108 109 110
#        #check, if dataset contains (already modified) particle2spectra, otherwise create new.
#        if self.datastats.dataset.particles2spectra is None:  #create default assignment
#            print('recreating particles2spectra from within edit particles...')
#            sortindices = self.datastats.dataset.ramanscansortindex
#            self.datastats.dataset.particles2spectra = [[int(np.where(sortindices == i)[0])] for i in range(len(sortindices))]
111 112 113 114
        
        #Contour indices are the same as the original particlestats, which are contained in the dataset. 
        #We have to modify that and reload in the analysisview
        #first, overwrite first index with new particlestats
115
        self.datastats.dataset.particlestats[contourIndices[0]] = stats
116 117
        
        #now, delete the rest...
118
        self.datastats.dataset.particlestats = [i for ind, i in enumerate(self.datastats.dataset.particlestats) if ind not in contourIndices[1:]]
119 120
        
        #same with the contours
121 122
        self.datastats.dataset.particlecontours[contourIndices[0]] = newContour
        self.datastats.dataset.particlecontours = [i for ind, i in enumerate(self.datastats.dataset.particlecontours) if ind not in contourIndices[1:]]
123 124 125 126 127 128
        
        #update particle2spectra_list
        #what is the current particle index??
        specIndices = []
        #other spectra indices:
        for index in contourIndices:
129
            specIndices.append(self.datastats.particles2spectra[index])
130 131
        
        #flatten index list (in case, that a nested list was created...)
Hackmet's avatar
Hackmet committed
132
        specIndices = list(np.concatenate(specIndices))
133
        for i in specIndices:
134 135
            self.datastats.spectraResults[i] = new_assignment
            self.datastats.hqis[i] = 100   #avoid sorting them out again by hqi-filter...
136 137 138
            print(f'spectrum {i} of particle{contourIndices[0]} is now {new_assignment}')
        
        #modify particles2spectra..         
139
        self.datastats.dataset.particles2spectra[contourIndices[0]] = specIndices
140 141
        for index in reversed(contourIndices[1:]):
            print('removing index from particles2spectra:', index)
142
            del self.datastats.dataset.particles2spectra[index]
143

Lars Bittrich's avatar
Lars Bittrich committed
144 145 146
        #update contours in sampleview
        self.parent.parent.contouritem.resetContours(self.datastats.dataset.particlecontours)
        self.parent.loadParticleData()
Hackmet's avatar
Hackmet committed
147
        #save data
Lars Bittrich's avatar
Lars Bittrich committed
148 149 150 151 152 153
        minHQI = self.parent.hqiSpinBox.value()
        compHQI = self.parent.compHqiSpinBox.value()
        if not self.datastats.saveAnalysisResults(minHQI, compHQI):
            QtWidgets.QMessageBox.warning(self.parent, 'Error!',
                    'Data inconsistency after saving!', QtWidgets.QMessageBox.Ok, 
                    QtWidgets.QMessageBox.Ok)
154 155 156 157
        
       
    
    def reassignParticles(self, contourindices, new_assignment):
Hackmet's avatar
Hackmet committed
158 159
        if new_assignment == 'other':
            new_assignment = self.getNewEntry()
160 161
        if new_assignment is None:
            return
Hackmet's avatar
Hackmet committed
162
            
163
        self.createSafetyBackup()
Hackmet's avatar
Hackmet committed
164
        print(f'reassigning indices {contourindices} into {new_assignment}')
165
        for partIndex in contourindices:
166 167 168 169
            for specIndex in self.datastats.particles2spectra[partIndex]:
                self.datastats.currentPolymers[specIndex] = new_assignment
                self.datastats.spectraResults[specIndex] = new_assignment
                self.datastats.hqis[specIndex] = 100
170

Lars Bittrich's avatar
Lars Bittrich committed
171 172 173
        #update contours in sampleview
        self.parent.parent.contouritem.resetContours(self.datastats.dataset.particlecontours)
        self.parent.loadParticleData()
Hackmet's avatar
Hackmet committed
174
        #save data
Lars Bittrich's avatar
Lars Bittrich committed
175 176 177 178 179 180
        minHQI = self.parent.hqiSpinBox.value()
        compHQI = self.parent.compHqiSpinBox.value()
        if not self.datastats.saveAnalysisResults(minHQI, compHQI):
            QtWidgets.QMessageBox.warning(self.parent, 'Error!',
                                'Data inconsistency after saving!',
                                QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.Ok)
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
            
    
    def deleteParticles(self):
        self.createSafetyBackup()
        pass
    
    def splitParticles(self):
        self.createSafetyBackup()
        pass
    
    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)
Hackmet's avatar
Hackmet committed
207 208
            

209
    
Hackmet's avatar
Hackmet committed
210