From 96e557861a55c62d0ca679dfa04e5a78c519916d Mon Sep 17 00:00:00 2001 From: JosefBrandt Date: Fri, 12 Jul 2019 15:18:15 +0200 Subject: [PATCH] Particle Combination works (bugfix needed) --- analysis/analysisview.py | 15 +-- analysis/particleInfo.py | 66 +++++++++++--- analysis/particleeditor.py | 181 ++++++++++++++----------------------- dataset.py | 2 +- detectionview.py | 2 +- sampleview.py | 108 +++++++++++++--------- viewitems.py | 2 + 7 files changed, 202 insertions(+), 174 deletions(-) diff --git a/analysis/analysisview.py b/analysis/analysisview.py index d37c501..1acfc67 100644 --- a/analysis/analysisview.py +++ b/analysis/analysisview.py @@ -229,7 +229,7 @@ class ParticleAnalysis(QtWidgets.QMainWindow): self.fullOverlayAct = QtWidgets.QAction("&Full Overlay", self) self.transpAct = QtWidgets.QAction("&Transparent Overlay", self) - self.transpAct.triggered.connect(self.updateContours) + self.transpAct.triggered.connect(self.updateContourColors) self.hideLabelAct = QtWidgets.QAction('&Hide Polymer Numbers', self) self.hideLabelAct.triggered.connect(self.show_hide_labels) @@ -262,7 +262,7 @@ class ParticleAnalysis(QtWidgets.QMainWindow): self.dispMenu = QtWidgets.QMenu("&Display", self) self.overlayActGroup = QtWidgets.QActionGroup(self.dispMenu) self.overlayActGroup.setExclusive(True) - self.overlayActGroup.triggered.connect(self.updateContours) + self.overlayActGroup.triggered.connect(self.updateContourColors) self.overlayActGroup.triggered.connect(self.updateDisplays) for act in [self.noOverlayAct, self.selOverlayAct, self.fullOverlayAct]: @@ -385,8 +385,9 @@ class ParticleAnalysis(QtWidgets.QMainWindow): # else: # print('displaying new type with resetting index') # self.displayNewPolymerType() - + def updateDisplays(self): + self.createHistogramData() t0 = time.time() self.updateTypeHistogram() print('update type hist:', round((time.time()-t0)*1000)) @@ -394,7 +395,7 @@ class ParticleAnalysis(QtWidgets.QMainWindow): self.updateSizeHistogram() print('update size hist:', round((time.time()-t0)*1000)) t0 = time.time() - self.updateContours() + self.updateContourColors() print('update contours:', round((time.time()-t0)*1000)) t0 = time.time() self.updateLegend() @@ -471,7 +472,7 @@ class ParticleAnalysis(QtWidgets.QMainWindow): ref = self.dbWin.activeDatabase.spectra[refID] self.specPlot.updateReferenceSpectrum(ref[:, 0], ref[:, 1]) - def updateContours(self): + def updateContourColors(self): contours = self.parent.contourItems alpha = (128 if self.transpAct.isChecked() else 255) selectedPolymers = self.getSelectedPolymers() @@ -521,7 +522,9 @@ class ParticleAnalysis(QtWidgets.QMainWindow): self.spectrumSelector.setValue(1) self.currentParticleIndex = self.getParticleIndexFromParticleSelector() - self.spectrumSelector.setMaximum(self.particleContainer.getNumberOfSpectraOfParticle(self.currentParticleIndex)) + numSpectra = self.particleContainer.getNumberOfSpectraOfParticle(self.currentParticleIndex) + self.spectrumSelector.setMaximum(numSpectra) + self.spectrumNumberLabel.setText(f'of {numSpectra} Spectra') self.currentSpectrumIndex = self.getSpectrumIndexFromSpectrumSelector() self.updateSpecPlot(centerOn=False) diff --git a/analysis/particleInfo.py b/analysis/particleInfo.py index 18bb12c..16a56ec 100644 --- a/analysis/particleInfo.py +++ b/analysis/particleInfo.py @@ -38,13 +38,15 @@ class ParticleContainer(object): self.inconsistentParticles = [] self.typeHistogram = None - + def initializeParticles(self, numParticles): self.particles = [] for i in range(numParticles): - self.particles.append(Particle(i)) + newParticle = Particle() + newParticle.index = i + self.particles.append(newParticle) - def setParticlecontours(self, contours): + def setParticleContours(self, contours): assert len(self.particles) == len(contours) for index, particle in enumerate(self.particles): particle.contour = contours[index] @@ -212,14 +214,49 @@ class ParticleContainer(object): typehistogram[assignment] += 1 ##sort typehistogram, it will be converted into a list!! sorted_typehistogram = sorted(typehistogram.items(), key = operator.itemgetter(1), reverse = True) - #convert back to dict + #convert back to dsetParticlecontoursict final_typehistogram = {i[0]: i[1] for i in sorted_typehistogram} return final_typehistogram + def mergeParticles(self, particleIndices, newContour, newStats, newAssignment=None): + newParticle = Particle() + #copy Measurements + for index in particleIndices: + particle = self.getParticleOfIndex(index) + for meas in particle.getMeasurements(): + if newAssignment is not None: + meas.setAssignment(newAssignment) + meas.setHQI(100) + newParticle.addExistingMeasurement(meas) + + #set Particle Stats + long, short, longellipse, shortellipse, area = newStats + newParticle.longSize_box = long + newParticle.shortSize_box = short + newParticle.longSize_ellipse = longellipse + newParticle.shortSize_ellipse = shortellipse + newParticle.area = area + newParticle.contour = newContour + + self.particles.append(newParticle) + self.removeParticles(particleIndices) + self.resetParticleIndices() + + def removeParticles(self, indexList): + for index in indexList: + particle = self.getParticleOfIndex(index) + print('removing particle of index', index) + self.particles.remove(particle) + + def resetParticleIndices(self): + for newIndex, particle in enumerate(self.particles): + particle.index = newIndex + class Particle(object): - def __init__(self, index): - self.index = index + def __init__(self): + super(Particle, self).__init__() + self.index = None self.longSize_ellipse = np.nan self.shortSize_ellipse = np.nan self.longSize_box = np.nan @@ -227,7 +264,10 @@ class Particle(object): self.area = None self.contour = None self.measurements = [] - + + def addExistingMeasurement(self, meas): + self.measurements.append(meas) + def addEmptyMeasurement(self): self.measurements.append(Measurement()) indexOfNewMeasurment = len(self.measurements)-1 @@ -318,6 +358,7 @@ class Particle(object): class Measurement(object): def __init__(self): + super(Measurement, self).__init__() self.ramanScanIndex = None self.pixelcoord_x= None self.pixelcoord_y = None @@ -328,17 +369,18 @@ class Measurement(object): def setAssignment(self, assignment): self.assignment_orig = assignment - self.assignment_afterHQI = 'unknown' + self.applyHQIThreshold() def setHQI(self, hqi): self.hqi = hqi self.applyHQIThreshold() def applyHQIThreshold(self, minHQI=0): - if self.hqi >= minHQI: - self.assignment_afterHQI = self.assignment_orig - else: - self.assignment_afterHQI = 'unknown' + if self.hqi is not None: #i.e. skip for initial setup, when hqi is not yet aplied... + if self.hqi >= minHQI: + self.assignment_afterHQI = self.assignment_orig + else: + self.assignment_afterHQI = 'unknown' def getHQI(self): return self.hqi diff --git a/analysis/particleeditor.py b/analysis/particleeditor.py index dbf0c67..7bc332c 100644 --- a/analysis/particleeditor.py +++ b/analysis/particleeditor.py @@ -70,15 +70,26 @@ class ParticleContextMenu(QtWidgets.QMenu): action = self.exec_(screenPos) if action in self.combineActs: - newAssignment = action.text() + newAssignment = self.validifyAssignment(action.text()) self.combineParticlesSignal.emit(self.selectedParticleIndices, newAssignment) elif action in self.reassignActs: - newAssignment = action.text() + newAssignment = self.validifyAssignment(action.text()) self.reassignParticlesSignal.emit(self.selectedParticleIndices, newAssignment) + + def validifyAssignment(self, assignment): + if assignment == "other": + assignment = self.getNewEntry() + return assignment + + def getNewEntry(self): + text, okClicked = QtWidgets.QInputDialog.getText(QtWidgets.QWidget(), "Custom assignment", "Enter new assignment") + if okClicked and text != '': + return text class ParticleEditor(QtCore.QObject): - particlesWereEdited = QtCore.pyqtSignal() + particleEditProcessStarted = QtCore.pyqtSignal() + particlesEdited = QtCore.pyqtSignal() def __init__(self, sampleView, particleContainer): super(ParticleEditor, self).__init__() self.particleContainer = particleContainer @@ -98,109 +109,19 @@ class ParticleEditor(QtCore.QObject): print('backing up as', backupname) self.neverBackedUp = False self.actionCounter = 0 - - def getNewEntry(self): - text, okClicked = QtWidgets.QInputDialog.getText(QtWidgets.QWidget(), "Custom assignment", "Enter new assignment") - if okClicked and text != '': - return text @QtCore.pyqtSlot(list, str) - def combineParticles(self, contourIndices, new_assignment): - print(contourIndices, new_assignment) - -# if new_assignment == 'other': -# new_assignment = self.getNewEntry() -# if new_assignment is None: -# return -# -# contourIndices = sorted(contourIndices) #we want to keep the contour with lowest index -# #get contours: -# contours = self.particleContainer.getParticleContoursByIndex(contourIndices) -## contours = [self.datastats.dataset.particlecontours[i] for i in contourIndices] -# 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 i in contourIndices: -# curCnt = self.particleContainer.getParticleContoursByIndex(i).copy() -## curCnt = self.datastats.dataset.particlecontours[i].copy() -# 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: -# QtWidgets.QMessageBox.critical(self.parent, 'ERROR!', -# 'Particle contours are not connected and cannot be combined!') -# return -# -# newContour = contours[0] -# stats = self.characterizeParticle(newContour) -#dateContours() -# for i in range(len(newContour)): -# newContour[i][0][0] += xmin-padding -# newContour[i][0][1] += ymin-padding -# -# print('merging contours:', contourIndices) -# self.createSafetyBackup() -# -## #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))] -# -# #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 -# self.datastats.dataset.particlestats[contourIndices[0]] = stats -# -# #now, delete the rest... -# self.datastats.dataset.particlestats = [i for ind, i in enumerate(self.datastats.dataset.particlestats) if ind not in contourIndices[1:]] -# -# #same with the contours -# 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:]] -# -# #update particle2spectra_list -# #what is the current particle index?? -# specIndices = [] -# #other spectra indices: -# for index in contourIndices: -# specIndices.append(self.datastats.particles2spectra[index]) -# -# #flatten index list (in case, that a nested list was created...) -# specIndices = list(np.concatenate(specIndices)) -# for i in specIndices: -# self.datastats.spectraResults[i] = new_assignment -# self.datastats.hqis[i] = 100 #avoid sorting them out again by hqi-filter... -# print(f'spectrum {i} of particle{contourIndices[0]} is now {new_assignment}') -# -# #modify particles2spectra.. -# self.datastats.dataset.particles2spectra[contourIndices[0]] = specIndices -# for index in reversed(contourIndices[1:]): -# print('removing index from particles2spectra:', index) -# del self.datastats.dataset.particles2spectra[index] -# -# #update contours in sampleview -# self.parent.parent.contouritem.resetContours(self.datastats.dataset.particlecontours) -# self.parent.loadParticleData() + def combineParticles(self, contourIndices, newAssignment): + self.particleEditProcessStarted.emit() + 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) + self.particlesEdited.emit() + # #save data # minHQI = self.parent.hqiSpinBox.value() # compHQI = self.parent.compHqiSpinBox.value() @@ -210,19 +131,53 @@ class ParticleEditor(QtCore.QObject): # QtWidgets.QMessageBox.Ok) @QtCore.pyqtSlot(list, str) - def reassignParticles(self, contourindices, new_assignment): - if new_assignment == 'other': - new_assignment = self.getNewEntry() - if new_assignment is None: - return - + def reassignParticles(self, contourindices, newAssignment): + self.particleEditProcessStarted.emit() self.createSafetyBackup() - print(f'reassigning indices {contourindices} into {new_assignment}') + print(f'reassigning indices {contourindices} into {newAssignment}') for partIndex in contourindices: - self.particleContainer.reassignParticleToAssignment(partIndex, new_assignment) + self.particleContainer.reassignParticleToAssignment(partIndex, newAssignment) - self.particlesWereEdited.emit() + self.particlesEdited.emit() + + 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: + QtWidgets.QMessageBox.critical(self.parent, 'ERROR!', + '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 + return newContour + + def characterizeParticle(self, contours): ##characterize particle longellipse, shortellipse = np.nan, np.nan diff --git a/dataset.py b/dataset.py index 2076b0b..968a8fb 100644 --- a/dataset.py +++ b/dataset.py @@ -257,7 +257,7 @@ class DataSet(object): self.particleContainer.initializeParticles(len(self.particlestats)) - self.particleContainer.setParticlecontours(self.particlecontours) + self.particleContainer.setParticleContours(self.particlecontours) self.particleContainer.setParticleStats(self.particlestats) self.particleContainer.applyPixelScaleToParticleStats(self.getPixelScale()) if hasattr(self, 'particles2spectra'): diff --git a/detectionview.py b/detectionview.py index af94d5e..5aea227 100644 --- a/detectionview.py +++ b/detectionview.py @@ -664,7 +664,7 @@ class ParticleDetectionView(QtWidgets.QWidget): particleContainer = self.dataset.particleContainer particleContainer.initializeParticles(numParticles) - particleContainer.setParticlecontours(contours) + particleContainer.setParticleContours(contours) particleContainer.setParticleStats(particlestats) particleContainer.applyPixelScaleToParticleStats(self.dataset.getPixelScale()) diff --git a/sampleview.py b/sampleview.py index 5cefd4d..746e4de 100644 --- a/sampleview.py +++ b/sampleview.py @@ -58,6 +58,8 @@ class SampleView(QtWidgets.QGraphicsView): self.setRenderHint(QtGui.QPainter.Antialiasing) self.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse) self.setResizeAnchor(QtWidgets.QGraphicsView.AnchorViewCenter) + self.disableSelection = False + self.ramanctrl = RamanControl() self.simulatedRaman = simulatedRaman #determine, if ramanSwitch is needed: @@ -177,7 +179,7 @@ class SampleView(QtWidgets.QGraphicsView): self.detectionwidget.close() self.detectionwidget.destroy() self.ramanwidget.setVisible(False) - self.updateParticleContours() + self.resetParticleContours() self.mode = mode self.loadPixmap(self.microscopeMode) if mode == "OpticalScan": @@ -202,7 +204,7 @@ class SampleView(QtWidgets.QGraphicsView): print('creating new analysiswidget') self.analysiswidget = ParticleAnalysis(self.dataset, self) self.analysiswidget.showMaximized() - self.particleEditor.particlesWereEdited.connect(self.analysiswidget.updateDisplays) + self.setupParticleEditor() else: print('show maximized already exisiting analysiswidget') self.analysiswidget.showMaximized() @@ -228,10 +230,9 @@ class SampleView(QtWidgets.QGraphicsView): widget.destroy() del widget - self.updateParticleContours() - self.dataset = loadData(fname) - self.particleEditor = ParticleEditor(self, self.dataset.particleContainer) + self.resetParticleContours() + self.setupParticleEditor() self.setMicroscopeMode() self.imparent.setWindowTitle(self.dataset.name + (" SIMULATION" if simulatedRaman else "")) self.imgdata = None @@ -250,13 +251,23 @@ class SampleView(QtWidgets.QGraphicsView): if self.dataset is not None: self.dataset.save() self.dataset = DataSet(fname, newProject=True) - self.particleEditor = ParticleEditor(self, self.dataset.particleContainer) + self.setupParticleEditor() 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 setupParticleEditor(self): + if self.particleEditor is None: + self.particleEditor = ParticleEditor(self, self.dataset.particleContainer) + self.particleEditor.particleEditProcessStarted.connect(self.disableContourSelection) + self.particleEditor.particlesEdited.connect(self.resetParticleContours) + self.particleEditor.particlesEdited.connect(self.enableContourSelection) + if self.analysiswidget is not None: + self.particleEditor.particlesEdited.connect(self.analysiswidget.updateDisplays) + + def setMicroscopeMode(self): if self.ramanSwitchNeeded: self.imparent.ramanSwitch.connectToSampleView() @@ -295,38 +306,39 @@ class SampleView(QtWidgets.QGraphicsView): return maxmode def mousePressEvent(self, event): - if event.button()==QtCore.Qt.MiddleButton: - self.drag = event.pos() - elif event.button()==QtCore.Qt.LeftButton: - self.checkForContourSelection(event) - event.ignore() - elif event.button()==QtCore.Qt.LeftButton and self.mode in ["OpticalScan", "RamanScan"] \ - and event.modifiers()==QtCore.Qt.ControlModifier: - p0 = self.mapToScene(event.pos()) - 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 not self.disableSelection: + if event.button()==QtCore.Qt.MiddleButton: + self.drag = event.pos() + elif event.button()==QtCore.Qt.LeftButton: + self.checkForContourSelection(event) + event.ignore() + elif event.button()==QtCore.Qt.LeftButton and self.mode in ["OpticalScan", "RamanScan"] \ + and event.modifiers()==QtCore.Qt.ControlModifier: + p0 = self.mapToScene(event.pos()) + 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 + # x, y, z = self.dataset.mapToLengthRaman([p0.x(), p0.y()], + # microscopeMode=self.microscopeMode, + # noz=(False if self.mode=="RamanScan" else True)) + x, y, z = self.dataset.mapToLengthRaman([p0.x(), p0.y()], microscopeMode=self.microscopeMode, noz=False) + if z is not None: + assert z>-100. + self.ramanctrl.moveToAbsolutePosition(x, y, z) + elif event.button()==QtCore.Qt.LeftButton and self.mode=="ParticleDetection": + p0 = self.mapToScene(event.pos()) + self.detectionwidget.setImageCenter([p0.x(), p0.y()]) - if reply == QtWidgets.QMessageBox.Yes: - self.dataset.readin = False - else: - return -# x, y, z = self.dataset.mapToLengthRaman([p0.x(), p0.y()], -# microscopeMode=self.microscopeMode, -# noz=(False if self.mode=="RamanScan" else True)) - x, y, z = self.dataset.mapToLengthRaman([p0.x(), p0.y()], microscopeMode=self.microscopeMode, noz=False) - if z is not None: - assert z>-100. - self.ramanctrl.moveToAbsolutePosition(x, y, z) - elif event.button()==QtCore.Qt.LeftButton and self.mode=="ParticleDetection": - p0 = self.mapToScene(event.pos()) - self.detectionwidget.setImageCenter([p0.x(), p0.y()]) - - else: - p0 = self.mapToScene(event.pos()) - super(SampleView, self).mousePressEvent(event) + else: + p0 = self.mapToScene(event.pos()) + super(SampleView, self).mousePressEvent(event) def mouseMoveEvent(self, event): if self.drag is not None: @@ -411,7 +423,7 @@ class SampleView(QtWidgets.QGraphicsView): @QtCore.pyqtSlot(str) def detectionUpdate(self): - self.updateParticleContours() + self.resetParticleContours() self.prepareAnalysis() self.update() @@ -424,7 +436,7 @@ class SampleView(QtWidgets.QGraphicsView): data = self.imgdata fname = self.dataset.getImageName() if self.mode == "ParticleDetection" or self.mode == "ParticleAnalysis": - self.updateParticleContours() + self.resetParticleContours() if data is None and os.path.exists(fname): data = cv2.cvtColor(cv2imread_fix(fname), cv2.COLOR_BGR2RGB) self.imgdata = data @@ -527,12 +539,17 @@ class SampleView(QtWidgets.QGraphicsView): self.scene().addItem(item) self.ramanscanitems.append(item) - def updateParticleContours(self): + def resetParticleContours(self): for cnt in self.contourItems: self.scene().removeItem(cnt) self.contourItems = [] if self.dataset is not None: for particleIndex, contour in enumerate(self.dataset.particleContainer.getParticleContours()): + ### + part = self.dataset.particleContainer.getParticleOfIndex(particleIndex) + if part.index != particleIndex: + print('missmatch at countour index and particleIndex', part.index, particleIndex) + ### newCnt = SegmentationContour(self, contour) newCnt.setIndex(particleIndex) assignment = self.dataset.particleContainer.getParticleAssignmentByIndex(particleIndex) @@ -540,8 +557,17 @@ class SampleView(QtWidgets.QGraphicsView): newCnt.setColor(QtGui.QColor(color[0], color[1], color[2], 255)) self.contourItems.append(newCnt) self.scene().addItem(newCnt) + self.update() - + def disableContourSelection(self): + self.disableSelection = True +# for contourItem in self.contourItems: +# contourItem.setAcceptedMouseButtons(QtCore.Qt.NoButton) + + def enableContourSelection(self): + self.disableSelection = False +# for contourItem in self.contourItems: +# contourItem.setAcceptedMouseButtons(QtCore.Qt.AllButtons) def updateLegend(self, legendItems): self.imparent.legend.setTextColorItems(legendItems) diff --git a/viewitems.py b/viewitems.py index 0b3e5df..bfdbd15 100644 --- a/viewitems.py +++ b/viewitems.py @@ -26,6 +26,7 @@ class SegmentationContour(QtWidgets.QGraphicsItem): def __init__(self, parent, contourData, pos=(0,0)): super().__init__() self.parent = parent + self.setZValue(1) self.setPos(pos[0], pos[1]) self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable) self.setAcceptedMouseButtons(QtCore.Qt.AllButtons) @@ -254,6 +255,7 @@ class RamanScanIndicator(QtWidgets.QGraphicsItem): super().__init__() # self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) + self.setZValue(100) #higher numbers will be in foreground. Shall always be in foreground! self.view = view self.number = number self.radius = radius -- GitLab