Commit a6fa4f0e authored by JosefBrandt's avatar JosefBrandt
Browse files

No further ContourApproximation + Code Cleanup

Contour approximation can lead to wrong ellipse fits...
parent c90f7b26
Loading
Loading
Loading
Loading
+1 −13
Original line number Diff line number Diff line
@@ -45,7 +45,6 @@ except:
class ParticleAnalysis(QtWidgets.QMainWindow):
    def __init__(self, dataset, viewparent=None):
        super(ParticleAnalysis, self).__init__(viewparent)
#        self.resize(1680, 1050)
        self.setWindowTitle('Results of polymer analysis')
        self.layout = QtWidgets.QHBoxLayout()
        self.widget = QtWidgets.QWidget()
@@ -600,14 +599,3 @@ class ParticleAnalysis(QtWidgets.QMainWindow):
                
        self.viewparent.imparent.particelAnalysisAct.setChecked(False)
        event.accept()
 No newline at end of file


if __name__ == '__main__':
    from ..dataset import DataSet
    def run():
        app = QtWidgets.QApplication(sys.argv)
        meas = ParticleAnalysis(DataSet("dummydata"))
        meas.showMaximized()
        return app.exec_()
    
    run()
 No newline at end of file
+10 −46
Original line number Diff line number Diff line
@@ -27,8 +27,7 @@ with permission from github user CJ Carey (perimosocordiae)

from PyQt5 import QtWidgets, QtCore
import numpy as np
import sys
import dill
import dill   #TODO: Make it run with pickle... Having two different methods is not so sensefull...
import os
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
@@ -317,15 +316,13 @@ class DataBaseWindow(QtWidgets.QMainWindow):
        self.removeSpecBtn.setText('Remove {}'.format(self.activeSpectrumName))
        self.removeSpecBtn.setDisabled(False)
    
    def save(self):
    def save(self, showMessage=True):
        for index, db in enumerate(self.databases):
#            pickling_on = open(db.title+'.dbpkl', 'wb')
#            pickle.dump(db, pickling_on)
#            pickling_on.close()
            savename = os.path.join(self.path, db.title+'.db')
            with open(savename, 'wb') as f:
                dill.dump(db, f)
        
        if showMessage:
            QtWidgets.QMessageBox.about(self, 'Done.', 'Saved {} database(s)'.format(len(self.databases)))
    
    def updateDBSelectorList(self):
@@ -339,7 +336,6 @@ class DataBaseWindow(QtWidgets.QMainWindow):
                self.db_selector.setCurrentText(self.activeDatabase.title)
    
    def selectDataBase(self, refreshParent=False):
#        if not self.noDBFound:
        if len(self.databases) > 0:
            self.activeDatabaseIndex = self.db_selector.currentIndex()
            self.activeDatabase = self.databases[self.activeDatabaseIndex]
@@ -352,13 +348,7 @@ class DataBaseWindow(QtWidgets.QMainWindow):
                self.parent.populateRefSelector()
    
    def closeEvent(self, event):
#        response = QtWidgets.QMessageBox.question(self, 'Warning', 'Exit without saving?', QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)
#        if response == QtWidgets.QMessageBox.Yes:
#            if self.parent is not None:
#                self.parent.setDisabled(False)
#            event.accept()
#        else:
#            event.ignore()
        self.save(showMessage=False)
        if self.parent is not None:
            self.parent.setDisabled(False)

@@ -426,8 +416,6 @@ class BaseLineCorrect(QtWidgets.QDialog):
        for i in range(len(spectra)):
            spectra[i][:, 1] = self.origspectra[i][:, 1].copy() - self.als_baseline(self.origspectra[i][:, 1].copy(), asymmetry_param=self.asymSpinBox.value(), 
                                    smoothness_param=self.smoothSpinBox.value(), max_iters = self.iterSpinBox.value())
#        self.newSpectra = spectra.copy()
#        self.parent.drawSpectrum(spectra[self.parent.activeSpectrumIndex], self.parent.activeSpectrumName)
        self.saveBtn.setDisabled(False)
    
    def als_baseline(self, intensities, asymmetry_param=0.05, smoothness_param=1e4,
@@ -453,26 +441,16 @@ class BaseLineCorrect(QtWidgets.QDialog):
        if conv < conv_thresh:
          break
        w = new_w
    #  else:
    #    print( 'ALS did not converge in %d iterations' % max_iters)
      else:
        print( 'ALS did not converge in %d iterations' % max_iters)
      return z
    
    def save(self):
#        self.parent.databases[self.parent.activeDatabaseIndex].spectra = self.spectra
#        self.parent.activeDatabase = self.parent.databases[self.parent.activeDatabaseIndex]
#        self.parent.activeSpectrum = self.parent.activeDatabase.spectra[self.parent.activeSpectrumIndex]
#        self.parent.drawSpectrum(self.parent.activeSpectrum, self.parent.activeSpectrumName)
        self.close()
    
    def cancel(self):
        self.close()
    
    def closeEvent(self, event):
        if self.parent is not None:
            self.parent.setDisabled(False)
#            self.parent.drawSpectrum(self.parent.activeSpectrum, self.parent.activeSpectrumName)
            
            


class WhittakerSmoother(object):
@@ -550,17 +528,3 @@ class CropSpectra(QtWidgets.QDialog):
        if self.parent is not None:
            self.parent.setDisabled(False)
        event.accept()
 No newline at end of file
        


def main():
    global dbWin
    #start Application
    app = QtWidgets.QApplication(sys.argv)
    dbWin = DataBaseWindow(None)
    app.exec_()
    

if __name__ == '__main__':
    main()
    
 No newline at end of file
+2 −4
Original line number Diff line number Diff line
@@ -30,14 +30,12 @@ class ExpExcelDialog(QtWidgets.QDialog):
        super(ExpExcelDialog, self).__init__()
        self.setWindowTitle('Export Options')
        self.setGeometry(200, 200, 300, 300)
        self.layout = QtWidgets.QHBoxLayout()
        self.setLayout(self.layout)
        
        self.dataset = dataset
        self.particleContainer = dataset.particleContainer
        
        
        self.layout = QtWidgets.QHBoxLayout()
        self.setLayout(self.layout)

        excelvbox = QtWidgets.QVBoxLayout()
        excelvbox.addWidget(QtWidgets.QLabel('Select Parameters for Export'))
        excelgroup = QtWidgets.QGroupBox("Export to Excel", self)
+8 −12
Original line number Diff line number Diff line
@@ -45,8 +45,8 @@ def particleIsValid(particle):
        return False
    return True
    

def getParticleStatsWithPixelScale(cnt, fullimage, dataset):
def getParticleStatsWithPixelScale(contour, fullimage, dataset):
    cnt = deepcopy(contour)
    pixelscale = dataset.getPixelScale()
    
    newStats = ParticleStats()
@@ -76,8 +76,6 @@ def getFibreDimension(contour):
    maxThickness = np.max(dist)*2
    return longSize, maxThickness
    
    

def getParticleColor(imgRGB, colorClassifier=None):
    img = cv2.cvtColor(imgRGB, cv2.COLOR_RGB2HSV_FULL)
    meanHSV = cv2.mean(img)
@@ -130,6 +128,7 @@ def getParticleImageFromFullimage(contour, fullimage):
    xmin, xmax, ymin, ymax = getContourExtrema(contourCopy)

    img = fullimage[ymin:ymax, xmin:xmax]
    img = img.copy()
    mask = np.zeros(img.shape[:2])
    
    for i in range(len(contourCopy)):
@@ -164,11 +163,11 @@ def contoursToImg(contours, padding=0):
    return img, xmin, ymin, padding

def imgToCnt(img, xmin, ymin, padding=0):
    def getContour(img, flag):
    def getContour(img, contourMode):
        if cv2.__version__ > '3.5':
            contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, flag)
            contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, contourMode)
        else:
            temp, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, flag)
            temp, contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, contourMode)
        
        if len(contours) == 0:   #i.e., no contour found
            raise InvalidParticleError
@@ -188,10 +187,7 @@ def imgToCnt(img, xmin, ymin, padding=0):
        return contours[maxIndex]

    img = closeHolesOfSubImage(img)
    contour = getContour(img, flag=cv2.CHAIN_APPROX_SIMPLE)

    if len(contour) < 5:
        contour = getContour(img, flag=cv2.CHAIN_APPROX_NONE)
    contour = getContour(img, contourMode=cv2.CHAIN_APPROX_NONE)
    
    for i in range(len(contour)):
        contour [i][0][0] += xmin-padding
+21 −19
Original line number Diff line number Diff line
@@ -20,6 +20,26 @@ along with this program, see COPYING.
If not, see <https://www.gnu.org/licenses/>.
"""

class ColorClassifier(object):
    def __init__(self):
        hue_tolerance = 50
        self.colors = [ColorRangeHSV('yellow', 30, hue_tolerance, 40, 255),
                  ColorRangeHSV('blue', 120, hue_tolerance, 40, 255),
                  ColorRangeHSV('red', 180, hue_tolerance, 40, 255),
                  ColorRangeHSV('red', 0, hue_tolerance, 40, 255),
                  ColorRangeHSV('green', 70, hue_tolerance, 40, 255),
                  ColorRangeHSV('white', 128, 256, 0, 40)]
    
    def classifyColor(self, meanHSV):
        result = 'non-determinable'
        for color in self.colors:
            if color.containsHSV(meanHSV):
                result = color.name
                break
        
        return result
    

class ColorRangeHSV(object):
    def __init__(self, name, hue, hue_tolerance, min_sat, max_sat):
        self.name = name
@@ -41,21 +61,3 @@ class ColorRangeHSV(object):
                if sat < 128 and hsv[2] > 70:
                    return True
            
 No newline at end of file
class ColorClassifier(object):
    def __init__(self):
        hue_tolerance = 50
        self.colors = [ColorRangeHSV('yellow', 30, hue_tolerance, 40, 255),
                  ColorRangeHSV('blue', 120, hue_tolerance, 40, 255),
                  ColorRangeHSV('red', 180, hue_tolerance, 40, 255),
                  ColorRangeHSV('red', 0, hue_tolerance, 40, 255),
                  ColorRangeHSV('green', 70, hue_tolerance, 40, 255),
                  ColorRangeHSV('white', 128, 256, 0, 40)]
    
    def classifyColor(self, meanHSV):
        result = 'non-determinable'
        for color in self.colors:
            if color.containsHSV(meanHSV):
                result = color.name
                break
        
        return result
 No newline at end of file
Loading