segmentation.py 26.9 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 27 28
# -*- 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/>.
"""
import numpy as np
import cv2
cv2.useOptimized()
from time import time
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy import ndimage as ndi
from skimage.feature import peak_local_max
from skimage.morphology import watershed
29
import skfuzzy as fuzz
30
import random
31 32 33 34 35 36 37 38 39 40

def closeHolesOfSubImage(subimg):
    subimg = cv2.copyMakeBorder(subimg, 1, 1, 1, 1, 0)
    im_floodfill = subimg.copy()
    h, w = subimg.shape[:2]
    mask = np.zeros((h+2, w+2), np.uint8)
    cv2.floodFill(im_floodfill, mask, (0,0), 255);
    im_floodfill_inv = cv2.bitwise_not(im_floodfill)
    im_out = subimg | im_floodfill_inv
    return im_out[1:-1, 1:-1]
JosefBrandt's avatar
JosefBrandt committed
41

42
class Parameter(object):
43 44 45 46 47
    """
    A Parameter for driving the image segmentation. All Parameters are initialized in the Segmentation Class. 
    The DetectionView-Widget reads these parameters and creates and connects the necessary items in the ui.
    :return:
    """
48
    def __init__(self, name, dtype, value=None, minval=None, maxval=None, 
49
                 decimals=0, stepsize=1, helptext=None, show=False, linkedParameter=None):
50 51 52 53 54 55 56 57
        self.name = name
        self.dtype = dtype
        self.value = value
        self.valrange = (minval, maxval)
        self.decimals = decimals
        self.stepsize = stepsize
        self.helptext = helptext
        self.show = show
58
        self.linkedParameter = linkedParameter
59

JosefBrandt's avatar
JosefBrandt committed
60 61 62 63 64 65
class MeasurementPoint(object):
    def __init__(self, particleIndex, x, y):
        self.particleIndex = particleIndex
        self.x = x
        self.y = y

66
class Segmentation(object):
67
    def __init__(self, dataset=None, parent=None):        
68
        self.cancelcomputation = False
69
        self.parent = parent
Josef Brandt's avatar
 
Josef Brandt committed
70 71 72 73 74 75 76 77 78 79 80 81
        self.defaultParams = {'adaptiveHistEqu': False,
                              'claheTileSize': 128,
                              'contrastCurve': np.array([[50,0],[100,200],[200,255]]),
                              'activateContrastCurve': True,
                              'blurRadius': 9,
                              'activateLowThresh': True,
                              'lowThresh': 0.2,
                              'activateUpThresh': False,
                              'upThresh': 0.5,
                              'invertThresh': False,
                              'maxholebrightness': 0.5,
                              'minparticlearea': 20,
82 83
                              'enableMaxArea': False,
                              'maxparticlearea': 100000,
Josef Brandt's avatar
 
Josef Brandt committed
84
                              'minparticledistance': 20,
85
                              'closeBackground': False,
86
                              'fuzzycluster': False,
Josef Brandt's avatar
 
Josef Brandt committed
87
                              'measurefrac': 1,
88
                              'compactness': 0.0,
Josef Brandt's avatar
 
Josef Brandt committed
89
                              'seedRad': 3}
90 91 92 93 94 95 96 97
        if dataset is not None:
            self.detectParams = dataset.detectParams
            for key in self.defaultParams:
                if key not in self.detectParams:
                    self.detectParams[key] = self.defaultParams[key]
        else:
            self.detectParams = self.defaultParams        
        self.initializeParameters()
98
        
99
    def initializeParameters(self):
Josef Brandt's avatar
 
Josef Brandt committed
100 101 102
        parlist = [Parameter("adaptiveHistEqu", np.bool, self.detectParams['adaptiveHistEqu'], helptext="Adaptive histogram equalization", show=False, linkedParameter='claheTileSize'),
                   Parameter("claheTileSize", int, self.detectParams['claheTileSize'], 1, 2048, 1, 1, helptext="Tile size for adaptive histogram adjustment\nThe Image will be split into tiles with size approx. (NxN)", show=True),
                   Parameter("contrastCurve", np.ndarray, self.detectParams['contrastCurve'], helptext="Curve contrast"),
103
                   Parameter("activateContrastCurve", np.bool, self.detectParams['activateContrastCurve'], helptext="activate Contrast curve", show=True, linkedParameter='contrastCurve'),
104
                   Parameter("blurRadius", int, self.detectParams['blurRadius'], 3, 99, 1, 2, helptext="Blur radius", show=True),
105 106
                   Parameter("invertThresh", np.bool, self.detectParams['invertThresh'], helptext="Invert the current threshold", show=False),
                   Parameter("activateLowThresh", np.bool, self.detectParams['activateLowThresh'], helptext="activate lower threshold", show=False, linkedParameter='lowThresh'),
107
                   Parameter("lowThresh", float, self.detectParams['lowThresh'], .01, .9, 2, .02, helptext="Lower threshold", show=True),
108
                   Parameter("activateUpThresh", np.bool, self.detectParams['activateUpThresh'], helptext="activate upper threshold", show=False, linkedParameter='upThresh'),
109
                   Parameter("upThresh", float, self.detectParams['upThresh'], .01, 1.0, 2, .02, helptext="Upper threshold", show=False),
110
                   Parameter("maxholebrightness", float, self.detectParams['maxholebrightness'], 0, 1, 2, 0.02, helptext="Close holes brighter than..", show = True),
Josef Brandt's avatar
 
Josef Brandt committed
111
                   Parameter("minparticlearea", int, self.detectParams['minparticlearea'], 1, 1000, 0, 50, helptext="Min. particle pixel area", show=False),
112
                   Parameter("enableMaxArea", np.bool, self.detectParams['enableMaxArea'], helptext="enable filtering for maximal pixel area", show=False, linkedParameter='maxparticlearea'),
113
                   Parameter("maxparticlearea", int, self.detectParams['maxparticlearea'], 10, 1E9, 0, 50, helptext="Max. particle pixel area", show=False),
Josef Brandt's avatar
 
Josef Brandt committed
114
                   Parameter("minparticledistance", int, self.detectParams['minparticledistance'], 5, 1000, 0, 5, helptext="Min. distance between particles", show=False),
115
                   Parameter("measurefrac", float, self.detectParams['measurefrac'], 0, 1, 2, stepsize = 0.05, helptext="measure fraction of particles", show=False),
116
                   Parameter("closeBackground", np.bool, self.detectParams['closeBackground'], helptext="close holes in sure background", show=False),
117
                   Parameter("fuzzycluster", np.bool, self.detectParams['fuzzycluster'], helptext='Enable Fuzzy Clustering', show=False),
118
                   Parameter("sure_fg", None, helptext="Show sure foreground", show=True),
119
                   Parameter("compactness", float, self.detectParams['compactness'], 0, 1, 2, 0.05, helptext="watershed compactness", show=False),
120 121 122 123
                   Parameter("watershed", None, helptext="Show watershed markers", show=True),
                   ]
        # make each parameter accessible via self.name
        # the variables are defined as properties and because of how the local context
124
        # in for loops works the actual setter and getter functions are defined inside 
125 126 127 128 129 130 131 132 133 134 135 136
        # a separate contex in a local function
        def makeGetter(p):
            return lambda : p.value
        def makeSetter(p):
            def setter(value):
                p.value = value
            return setter
        for p in parlist:
            # variabels in self are writen directly to the name dictionary
            self.__dict__[p.name] = property(makeGetter(p), makeSetter(p))
        self.parlist = parlist
    
137
    def apply2Image(self, img, seedpoints, deletepoints, seedradius, dataset, return_step=None):
138 139 140 141
        """
        Takes an image with seedpoints and seeddeletepoints and runs segmentation on it.
        :return:
        """
142
        t0 = time()
143
        
144 145
        gray = self.convert2Gray(img)
        print("gray")
146
        
Josef Brandt's avatar
 
Josef Brandt committed
147 148 149 150 151 152 153 154 155
        if self.adaptiveHistEqu:
            numTilesX = round(img.shape[1]/self.claheTileSize)
            numTilesY = round(img.shape[0]/self.claheTileSize)
            clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(numTilesY,numTilesX))
            gray = clahe.apply(gray)
        if return_step=="claheTileSize": return gray, 0
        print("adaptive Histogram Adjustment")
        
        if self.cancelcomputation:
JosefBrandt's avatar
JosefBrandt committed
156
            return None, None
Josef Brandt's avatar
 
Josef Brandt committed
157
        
158 159
        if self.activateContrastCurve:
            xi, arr = self.calculateHistFunction(self.contrastCurve)
160 161 162
            gray = arr[gray]
        print("contrast curve")
        if self.cancelcomputation:
JosefBrandt's avatar
JosefBrandt committed
163
            return None, None
164 165
            
        # return even if inactive!
166
        if return_step=="activateContrastCurve": return gray, 0
167 168 169 170
        
        # image blur for noise-reduction
        blur = cv2.medianBlur(gray, self.blurRadius)
        blur = np.uint8(blur*(255/blur.max()))
JosefBrandt's avatar
JosefBrandt committed
171 172
        del gray
        
173 174 175
        if return_step=="blurRadius": return blur, 0
        print("blur")
        if self.cancelcomputation:
JosefBrandt's avatar
JosefBrandt committed
176
            return None, None
177 178
        
        # thresholding
179 180
        if self.activateLowThresh and not self.activateUpThresh:
            thresh = cv2.threshold(blur, int(255*self.lowThresh), 255, cv2.THRESH_BINARY)[1]
181 182
            if self.invertThresh:
                thresh = 255-thresh
183 184 185
            if return_step=="lowThresh": return thresh, 0
            print("lower threshold")
            if self.cancelcomputation:
JosefBrandt's avatar
JosefBrandt committed
186
                return None, None
187 188 189 190 191
            
        elif self.activateLowThresh and self.activateUpThresh:
            lowerLimit, upperLimit = np.round(self.lowThresh*255), np.round(self.upThresh*255)
            thresh = np.zeros_like(blur)
            thresh[np.where(np.logical_and(blur >= lowerLimit, blur <= upperLimit))] = 255
192 193
            if self.invertThresh:
                thresh = 255-thresh
194 195 196
            if return_step=="lowThresh" or return_step=="upThresh": return thresh, 0
            print("between threshold")
            if self.cancelcomputation:
JosefBrandt's avatar
JosefBrandt committed
197
                return None, None
198 199 200 201
            
        elif not self.activateLowThresh and self.activateUpThresh:
            thresh = np.zeros_like(blur)
            thresh[np.where(blur <= np.round(self.upThresh*255))] = 255
202 203
            if self.invertThresh:
                thresh = 255-thresh
204 205 206
            if return_step=="upThresh": return thresh, 0
            print("upper threshold")
            if self.cancelcomputation:
JosefBrandt's avatar
JosefBrandt committed
207
                return None, None
208 209 210 211
        else:   #no checkbox checked
            if self.parent is not None:
                self.parent.raiseWarning('No thresholding method selected!\nAborted detection..')
            print('NO THRESHOLDING SELECTED!')
212
            return blur, 0
213 214
        
        #close holes darkter than self.max_brightness
Josef Brandt's avatar
 
Josef Brandt committed
215
        thresh = self.closeBrightHoles(thresh, blur, self.maxholebrightness)
JosefBrandt's avatar
JosefBrandt committed
216 217
        del blur
        print("thresholded")
218
        
219 220 221 222 223 224
        # modify thresh with seedpoints and deletepoints
        for p in np.int32(seedpoints):
            cv2.circle(thresh, tuple([p[0], p[1]]), int(p[2]), 255, -1)
        for p in np.int32(deletepoints):
            cv2.circle(thresh, tuple([p[0], p[1]]), int(p[2]), 0, -1)
        
225 226
        if return_step=='maxholebrightness': return thresh, 0
        if self.cancelcomputation:
JosefBrandt's avatar
JosefBrandt committed
227
            return None, None
228
        
229 230 231 232
        if self.enableMaxArea:
            maxArea = self.maxparticlearea
        else:
            maxArea = np.inf
Josef Brandt's avatar
 
Josef Brandt committed
233
        
234
        ##get sure_fg
235 236
        '''the peak_local_max function takes the min distance between peaks. Unfortunately, that means that individual 
        particles smaller than that distance are consequently disregarded. Hence, we need a connectec_components approach'''
237 238
        n, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, 8, cv2.CV_32S)
        del thresh
239
        
240 241 242
        measurementPoints = {}
        finalcontours = []
        particleIndex = 0
243
        
244 245 246 247 248 249 250
        if return_step == "sure_fg":
            preview_surefg = np.zeros(img.shape[:2])
            preview_surebg = np.zeros(img.shape[:2])
        elif return_step is None:
            previewImage = None
        else:
            previewImage = np.zeros(img.shape[:2])
251
        
252
        
253 254 255 256 257 258 259
        for label in range(1, n):
            area = stats[label, cv2.CC_STAT_AREA]
            if self.minparticlearea < area < maxArea:
                up = stats[label, cv2.CC_STAT_TOP]
                left = stats[label, cv2.CC_STAT_LEFT]
                width = stats[label, cv2.CC_STAT_WIDTH]
                height = stats[label, cv2.CC_STAT_HEIGHT]
260 261 262
#                if width > 25000 or height > 25000:
                if False:
                    print(f'skipping{label} of {n} compontents, too large: {width} x {height} pixel!!!')
263
                else:
264 265 266
                    print(f'processing {label} of {n} compontents, {width} x {height} pixel')
                    subthresh = np.uint8(255 * (labels[up:(up+height), left:(left+width)] == label))
                    subdist = cv2.distanceTransform(subthresh, cv2.DIST_L2, 3)
267
                    
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                    sure_fg = self.getSureForeground(subthresh, subdist, self.minparticledistance)
                    sure_bg = cv2.dilate(subthresh, np.ones((5, 5)), iterations = 1)
                    if self.closeBackground:
                        sure_bg = self.closeHoles(sure_bg)
    
                    # modify sure_fg and sure_bg with seedpoints and deletepoints
                    for p in np.int32(seedpoints):
                        cv2.circle(sure_fg, tuple([p[0]-left, p[1]-up]), int(p[2]), 1, -1)
                        cv2.circle(sure_bg, tuple([p[0]-left, p[1]-up]), int(p[2]), 1, -1)
                    for p in np.int32(deletepoints):
                        cv2.circle(sure_fg, tuple([p[0]-left, p[1]-up]), int(p[2]), 0, -1)
                        cv2.circle(sure_bg, tuple([p[0]-left, p[1]-up]), int(p[2]), 0, -1)
    
                    if self.cancelcomputation:
                        return None, None
    
                    if return_step=="sure_fg":
                        preview_surefg = self.addToPreviewImage(sure_fg, up, left, preview_surefg)
                        preview_surebg = self.addToPreviewImage(sure_bg, up, left, preview_surebg)
                        continue
                    
                    unknown = cv2.subtract(sure_bg, sure_fg)
             
                    ret, markers = cv2.connectedComponents(sure_fg)
                    markers = markers+1
                    markers[unknown==255] = 0
    
                    markers = ndi.label(sure_fg)[0]
                    markers = watershed(-subdist, markers, mask=sure_bg, compactness = self.compactness, watershed_line = True)  #labels = 0 for background, 1... for particles
    
                    if self.cancelcomputation:
                        return None, None
                    
                    if return_step=="watershed":
                        previewImage = self.addToPreviewImage(markers, up, left, previewImage)
                        continue
         
                    if cv2.__version__ > '3.5':        
                        contours, hierarchy = cv2.findContours(markers, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
                    else:
                        temp, contours, hierarchy = cv2.findContours(markers, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)
                    if self.cancelcomputation:
                        return None, None
311
                        
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
                    tmpcontours = [contours[i] for i in range(len(contours)) if hierarchy[0,i,3]<0]
    
                    for cnt in tmpcontours:
                        if cv2.contourArea(cnt) >= self.minparticlearea:
                            label = markers[cnt[0,0,1],cnt[0,0,0]]
                            if label==0:
                                continue
                
                            x0, x1 = cnt[:,0,0].min(), cnt[:,0,0].max()
                            y0, y1 = cnt[:,0,1].min(), cnt[:,0,1].max()
                            subimg = (markers[y0:y1+1,x0:x1+1]).copy()
                            subimg[subimg!=label] = 0
                            y, x = self.getMeasurementPoints(subimg)
                            
                            for i in range(len(cnt)):
                                cnt[i][0][0] += left
                                cnt[i][0][1] += up
                            
                            finalcontours.append(cnt)
                            measurementPoints[particleIndex] = []
                            
                            for index in range(0, len(x)):
                                newMeasPoint = MeasurementPoint(particleIndex, x[index] + x0 + left, y[index] + y0 + up)
                                measurementPoints[particleIndex].append(newMeasPoint)
                            particleIndex += 1
337 338 339 340 341 342 343 344 345

        if return_step == 'sure_fg':
            img = np.zeros_like(preview_surefg)
            img[np.nonzero(preview_surefg)] |= 1
            img[np.nonzero(preview_surebg)] |= 2
            return img, 1        
        
        elif return_step == 'watershed':
            return np.uint8(255*(previewImage!=0)), 0
346
        
347 348 349 350
        elif return_step is not None:
            raise NotImplementedError(f"this particular return_step: {return_step} is not implemented yet")

        print("particle detection took:", time()-t0, "seconds")
351 352 353 354 355 356 357 358 359
        
        if self.measurefrac < 1.0:
            nMeasurementsDesired = int(np.round(self.measurefrac * len(measurementPoints)))
            print(f'selecting {nMeasurementsDesired} of {len(measurementPoints)} measuring spots')
            partIndicesToMeasure = random.sample(measurementPoints.keys(), nMeasurementsDesired)
            newMeasPoints = {}
            for index in partIndicesToMeasure:
                newMeasPoints[index] = measurementPoints[index]
            measurementPoints = newMeasPoints
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414

        total_time = time()-t0
        print('segmentation took', total_time, 'seconds')
        return measurementPoints, finalcontours
    
    
    def addToPreviewImage(self, subimg, up, left, previewImage):
        """
        Adds a subimage at given position to the previewimage
        :return:
        """
        height, width = subimg.shape[0], subimg.shape[1]
        previewImage[up:up+height, left:left+width] += subimg
        previewImage = np.array(previewImage, dtype = np.int32)
        return previewImage
    
    
    def setParameters(self, **kwargs):
        """
        Parameters that were set in the parameter are updated to the classes dictionary and can later be referenced to as self.key
        :return:
        """
        for key in kwargs:
            self.__dict__[key] = kwargs[key]
        
    def convert2Gray(self, img):
        gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
        return gray
        
    def calculateHist(self, gray):
        hist = cv2.calcHist([gray],[0],None,[256],[0,256])
        return hist
    
    def calculateHistFunction(self, points):
        """
        Calculates the curve to plot in the histogram widget
        :return:
        """
        t = np.linspace(0,1,800)
        x0 = np.concatenate(([-1.],points[:,0],[256.]))
        y0 = np.concatenate(([0.],points[:,1],[255.]))
        t0 = np.concatenate(([0.],np.cumsum(np.sqrt(np.diff(x0)**2+np.diff(y0)**2))))
        t0 /= t0[-1]
        fx = InterpolatedUnivariateSpline(t0, x0, k=3)
        fy = InterpolatedUnivariateSpline(t0, y0, k=3)
        x = fx(t)
        y = fy(t)
        arr = np.zeros(256, dtype=np.uint8)
        xi = np.arange(256)
        ind = np.searchsorted(xi, x)
        arr[ind[ind<256]] = y[ind<256]
        arr[xi>points[:,0].max()] = 255
        arr[xi<points[:,0].min()] = 0.
        arr[arr>255] = 255.
        arr[arr<0] = 0.
415
        
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
        return xi, arr      
    
    def closeHoles(self, thresh):
        """
        Closes holes in a binary image
        :return:
        """
        n, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, 8, cv2.CV_32S)
        newthresh = np.zeros_like(thresh)
    
        for label in range(1, n):
            up = stats[label, cv2.CC_STAT_TOP]
            left = stats[label, cv2.CC_STAT_LEFT]
            width = stats[label, cv2.CC_STAT_WIDTH]
            height = stats[label, cv2.CC_STAT_HEIGHT]
            subimg = np.uint8(255 * (labels[up:(up+height), left:(left+width)] == label))
            
            newthresh[up:(up+height), left:(left+width)] += closeHolesOfSubImage(subimg)

        return newthresh
    
    def closeBrightHoles(self, thresh, grayimage, minBrightness):
        """
        Only closes holes that are brighter than a given minimal Brightness
        :return:
        """
        n, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, 8, cv2.CV_32S)
        minBrightness = np.uint8(minBrightness * 255)
        print('num comps in brightHoles:', n)
        
        for label in range(1, n):
            up = stats[label, cv2.CC_STAT_TOP]
            left = stats[label, cv2.CC_STAT_LEFT]
            width = stats[label, cv2.CC_STAT_WIDTH]
            height = stats[label, cv2.CC_STAT_HEIGHT]
            subimg = np.uint8(255 * (labels[up:(up+height), left:(left+width)] == label))
            
            subimg = cv2.copyMakeBorder(subimg, 1, 1, 1, 1, 0)
            im_floodfill = subimg.copy()
            h, w = subimg.shape[:2]
            mask = np.zeros((h+2, w+2), np.uint8)
            cv2.floodFill(im_floodfill, mask, (0,0), 255);
            
            indices = np.where(im_floodfill == 0)[0]
            if len(indices) > 0:
                if np.mean(grayimage[indices[0]]) > minBrightness:
                    im_floodfill_inv = cv2.bitwise_not(im_floodfill)
                    im_out = subimg | im_floodfill_inv
                    thresh[up:(up+height), left:(left+width)] += im_out[1:-1, 1:-1]
                    
        return thresh

    
    def getSureForeground(self, thresh, disttransform, mindistance):
        """
        Calculates sure_fg (i.e, seedpoints) for the markerbased watershed
        Currently the function only takes a distance-transform and extracts their (local) maxima.
        If desired, a fuzzy Clustering is applied to these to reduce the number of considered seed points.
        :return:
        """
JosefBrandt's avatar
JosefBrandt committed
476 477 478 479 480
        def simplifyByFuzzyClustering(points, maxNumPoints=100, maxNumClusters=50):
            """
            Runs fuzzy-c-means clustering on the points to reduce the number of seed points
            :return:
            """
481
            newPoints = []
JosefBrandt's avatar
JosefBrandt committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
            numPeaks = len(points)
            if len(points) <= maxNumPoints:
                xpts = [peak[1] for peak in points]
                ypts = [peak[0] for peak in points]
                alldata = np.vstack((ypts, xpts))
                
                fpcs = []
                cntrs = []
                maxNumClusters = min([maxNumClusters, numPeaks])
                for ncenters in range(2, maxNumClusters):
                    cntr, u, u0, d, jm, p, fpc = fuzz.cluster.cmeans(alldata, ncenters, 2, error=0.005, maxiter=1000, init=None)
                    fpcs.append(fpc/(ncenters**0.3))   #makes larger cluster numbers less preferred
                    cntrs.append(cntr)
                
                bestMatchIndex = fpcs.index(max(fpcs))
                bestMatchCentres = cntrs[bestMatchIndex]
                for point in bestMatchCentres:
                    newPoints.append([int(round(point[0])), int(round(point[1]))])
                print(f'reduced {numPeaks} to {len(newPoints)} maxima')
            else:
                newPoints = points
503
            return newPoints
JosefBrandt's avatar
JosefBrandt committed
504 505 506 507 508 509 510 511 512 513 514 515 516 517
        
        def sortOutTooClosePoints(points, minDistance):
            """
            The points-array is taken point-by-point and each point is only taken if it is minDistance away from the last one.
            This removes directly adjacent points
            :return:
            """
            lastPoint = points[0]
            fewerPoints = [points[0]]
            for point in points[2:]:
                if np.linalg.norm(lastPoint-point) > minDistance:
                    fewerPoints.append(point)
                lastPoint = point    
            return fewerPoints
518
            
JosefBrandt's avatar
JosefBrandt committed
519
        sure_fg = np.zeros_like(thresh)
520
        
JosefBrandt's avatar
JosefBrandt committed
521 522 523 524 525 526 527
        localMax = np.uint8(peak_local_max(disttransform, mindistance, exclude_border=False, indices = False))
        localMax[disttransform == np.max(disttransform)] = 1
        
        maxPoints = np.where(localMax == np.max(localMax))
        maxPoints = np.transpose(np.array(maxPoints))
        if len(maxPoints) > 3:
            maxPoints = sortOutTooClosePoints(maxPoints, mindistance)
528

JosefBrandt's avatar
JosefBrandt committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
        if len(maxPoints) > 3 and self.fuzzycluster:
            clusteredPoints = simplifyByFuzzyClustering(maxPoints)
            atLeastOnePointAdded = False
            for point in clusteredPoints:
                if thresh[point[0], point[1]] != 0:
                    sure_fg[point[0], point[1]] = 1
                    atLeastOnePointAdded = True
                    
            if not atLeastOnePointAdded:
                point = maxPoints[0]
                sure_fg[point[0], point[1]] = 1    
        
        else:
            for point in maxPoints:
                sure_fg[point[0], point[1]] = 1
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 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 595
                
        sure_fg = cv2.dilate(sure_fg, np.ones((3, 3)))
        return sure_fg
    
    def getMeasurementPoints(self, binParticle, numPoints=1):
        """
        Sets coordinates for later measurement points.
        :return:
        """
        binParticle = cv2.copyMakeBorder(binParticle, 1, 1, 1, 1, 0)
        dist = cv2.distanceTransform(np.uint8(binParticle), cv2.DIST_L2,3)
        ind = np.argmax(dist)
        y = [ind//dist.shape[1]-1]
        x = [ind%dist.shape[1]-1]
        for i in range(numPoints-1):
            binParticle.flat[ind] = 0
            dist = cv2.distanceTransform(np.uint8(binParticle), cv2.DIST_L2,3)
            ind = np.argmax(dist)
            y.append(ind//dist.shape[1]-1)
            x.append(ind%dist.shape[1]-1)
        return y, x
    

if __name__ == '__main__':
    import matplotlib.pyplot as plt
#    img = cv2.imread('/home/brandt/Schreibtisch/Segmentation/fullimage_III.png')
    seg = Segmentation()
    
    kwargs = {}
    seedpoints, deletepoints = [], []
    for parameter in seg.parlist:
        kwargs[parameter.name] = parameter.value
    seg.setParameters(**kwargs)
    
    size = 25000
    stepSize = 2000
    maxSize = 40000
    
    sizes, times = [], []
    while size <= maxSize:
        try:
            print('newsize =', size)
            img = cv2.resize(img, (size, size))
            points, contours, tf = seg.apply2Image(img, np.array([]), np.array([]), 1, None)
            sizes.append(size)
            times.append(tf)
            size += stepSize
        except:
            print('segmentation failed at size', size)
            raise
    #    imgSegmented = cv2.drawContours(img, contours, -1, (255, 255, 0), thickness=2)
#    plt.imshow(imgSegmented)