Esempio n. 1
0
def get_label(img,
              radius=20,
              selemSeg=npy.empty([1]),
              seg=False,
              max_size_th=1000,
              min_size_th=0,
              p0=0.7,
              sigma=None,
              iter=2,
              signal=None):
    '''
    Return the labeled image calculated from a radius disk
    :param img: input image
    :param radius: radius of the object to label
    :param seg: True if the segmented image is return
    :param max_size_th: Threshold on the maximum size
    :param p0: percentile for the segmentation
    :return: Labeled image
    '''
    #radius of the object to segment
    if npy.size(selemSeg) == 1:
        selemSeg = disk(radius)
    if sigma:
        img = filters.gaussian_filter(img, sigma)
    signal.emit({
        "msg": 'Segmentation:enhance constrast',
        "value": 0,
        "max": 100
    })
    img = rank.enhance_contrast_percentile(img, disk(3), p0=0.5, p1=1)
    signal.emit({"msg": 'Segmentation:threshold', "value": 16})
    Seg = rank.threshold_percentile(img, selemSeg, p0=p0)
    signal.emit({"msg": 'Segmentation:morphology', "value": 2 * 16})
    Seg = morphology.binary_fill_holes(Seg)
    Seg = morphology.binary_erosion(Seg, iterations=iter)
    Seg = morphology.binary_dilation(Seg, iterations=iter)
    Seg = morphology.binary_fill_holes(Seg)

    signal.emit({"msg": 'Segmentation:label', "value": 3 * 16})
    labels, nr_objects = mh.label(Seg)
    #too big
    signal.emit({"msg": 'Segmentation:delete big', "value": 4 * 16})
    sizes = mh.labeled.labeled_size(labels)
    too_big = npy.where(sizes > max_size_th)
    labels = mh.labeled.remove_regions(labels, too_big)

    #too small
    signal.emit({"msg": 'Segmentation:delete small', "value": 5 * 16})
    sizes = mh.labeled.labeled_size(labels)
    too_small = npy.where(sizes < min_size_th)
    labels = mh.labeled.remove_regions(labels, too_small)
    signal.emit({"msg": 'Segmentation finish', "value": 100})
    if seg:
        return labels, Seg
    return labels
Esempio n. 2
0
        def check_all():
            selem = morphology.disk(1)
            refs = np.load(
                os.path.join(skimage.data_dir, "rank_filter_tests.npz"))

            assert_equal(refs["autolevel"], rank.autolevel(self.image, selem))
            assert_equal(refs["autolevel_percentile"],
                         rank.autolevel_percentile(self.image, selem))
            assert_equal(refs["bottomhat"], rank.bottomhat(self.image, selem))
            assert_equal(refs["equalize"], rank.equalize(self.image, selem))
            assert_equal(refs["gradient"], rank.gradient(self.image, selem))
            assert_equal(refs["gradient_percentile"],
                         rank.gradient_percentile(self.image, selem))
            assert_equal(refs["maximum"], rank.maximum(self.image, selem))
            assert_equal(refs["mean"], rank.mean(self.image, selem))
            assert_equal(refs["geometric_mean"],
                         rank.geometric_mean(self.image, selem)),
            assert_equal(refs["mean_percentile"],
                         rank.mean_percentile(self.image, selem))
            assert_equal(refs["mean_bilateral"],
                         rank.mean_bilateral(self.image, selem))
            assert_equal(refs["subtract_mean"],
                         rank.subtract_mean(self.image, selem))
            assert_equal(refs["subtract_mean_percentile"],
                         rank.subtract_mean_percentile(self.image, selem))
            assert_equal(refs["median"], rank.median(self.image, selem))
            assert_equal(refs["minimum"], rank.minimum(self.image, selem))
            assert_equal(refs["modal"], rank.modal(self.image, selem))
            assert_equal(refs["enhance_contrast"],
                         rank.enhance_contrast(self.image, selem))
            assert_equal(refs["enhance_contrast_percentile"],
                         rank.enhance_contrast_percentile(self.image, selem))
            assert_equal(refs["pop"], rank.pop(self.image, selem))
            assert_equal(refs["pop_percentile"],
                         rank.pop_percentile(self.image, selem))
            assert_equal(refs["pop_bilateral"],
                         rank.pop_bilateral(self.image, selem))
            assert_equal(refs["sum"], rank.sum(self.image, selem))
            assert_equal(refs["sum_bilateral"],
                         rank.sum_bilateral(self.image, selem))
            assert_equal(refs["sum_percentile"],
                         rank.sum_percentile(self.image, selem))
            assert_equal(refs["threshold"], rank.threshold(self.image, selem))
            assert_equal(refs["threshold_percentile"],
                         rank.threshold_percentile(self.image, selem))
            assert_equal(refs["tophat"], rank.tophat(self.image, selem))
            assert_equal(refs["noise_filter"],
                         rank.noise_filter(self.image, selem))
            assert_equal(refs["entropy"], rank.entropy(self.image, selem))
            assert_equal(refs["otsu"], rank.otsu(self.image, selem))
            assert_equal(refs["percentile"],
                         rank.percentile(self.image, selem))
            assert_equal(refs["windowed_histogram"],
                         rank.windowed_histogram(self.image, selem))
Esempio n. 3
0
def check_all():
    np.random.seed(0)
    image = np.random.rand(25, 25)
    selem = morphology.disk(1)
    refs = np.load(os.path.join(skimage.data_dir, "rank_filter_tests.npz"))

    assert_equal(refs["autolevel"], rank.autolevel(image, selem))
    assert_equal(refs["autolevel_percentile"], rank.autolevel_percentile(image, selem))
    assert_equal(refs["bottomhat"], rank.bottomhat(image, selem))
    assert_equal(refs["equalize"], rank.equalize(image, selem))
    assert_equal(refs["gradient"], rank.gradient(image, selem))
    assert_equal(refs["gradient_percentile"], rank.gradient_percentile(image, selem))
    assert_equal(refs["maximum"], rank.maximum(image, selem))
    assert_equal(refs["mean"], rank.mean(image, selem))
    assert_equal(refs["mean_percentile"], rank.mean_percentile(image, selem))
    assert_equal(refs["mean_bilateral"], rank.mean_bilateral(image, selem))
    assert_equal(refs["subtract_mean"], rank.subtract_mean(image, selem))
    assert_equal(refs["subtract_mean_percentile"], rank.subtract_mean_percentile(image, selem))
    assert_equal(refs["median"], rank.median(image, selem))
    assert_equal(refs["minimum"], rank.minimum(image, selem))
    assert_equal(refs["modal"], rank.modal(image, selem))
    assert_equal(refs["enhance_contrast"], rank.enhance_contrast(image, selem))
    assert_equal(refs["enhance_contrast_percentile"], rank.enhance_contrast_percentile(image, selem))
    assert_equal(refs["pop"], rank.pop(image, selem))
    assert_equal(refs["pop_percentile"], rank.pop_percentile(image, selem))
    assert_equal(refs["pop_bilateral"], rank.pop_bilateral(image, selem))
    assert_equal(refs["sum"], rank.sum(image, selem))
    assert_equal(refs["sum_bilateral"], rank.sum_bilateral(image, selem))
    assert_equal(refs["sum_percentile"], rank.sum_percentile(image, selem))
    assert_equal(refs["threshold"], rank.threshold(image, selem))
    assert_equal(refs["threshold_percentile"], rank.threshold_percentile(image, selem))
    assert_equal(refs["tophat"], rank.tophat(image, selem))
    assert_equal(refs["noise_filter"], rank.noise_filter(image, selem))
    assert_equal(refs["entropy"], rank.entropy(image, selem))
    assert_equal(refs["otsu"], rank.otsu(image, selem))
    assert_equal(refs["percentile"], rank.percentile(image, selem))
    assert_equal(refs["windowed_histogram"], rank.windowed_histogram(image, selem))
Esempio n. 4
0
    def processAlgorithm(self, parameters, context, feedback):

        try:
            import networkx as nx
            from osgeo import gdal as osgdal
            from skimage.io import imread
            from skimage.color import rgb2gray
            from skimage.filters import threshold_local, threshold_otsu
            from skimage.util import invert
            from skimage.morphology import disk
            from skimage.filters.rank import modal, threshold_percentile, otsu
            from skimage.util import img_as_ubyte

        except Exception as e:
            feedback.reportError(
                QCoreApplication.translate('Error', '%s' % (e)))
            feedback.reportError(QCoreApplication.translate('Error', ' '))
            feedback.reportError(
                QCoreApplication.translate(
                    'Error',
                    'Error loading modules - please install the necessary dependencies'
                ))
            return {}

        rlayer = self.parameterAsRasterLayer(parameters, self.Raster, context)
        inv = parameters[self.inv]
        block_size = parameters[self.blocks]
        adaptMethod = parameters[self.adaptMethod]
        mode = parameters[self.blur]
        method = parameters[self.Method]
        p = parameters[self.percent]

        aMethod = {0: "gaussian", 1: "mean", 2: "median"}

        outputRaster = self.parameterAsOutputLayer(parameters, self.outRaster,
                                                   context)

        fname = ''.join(
            random.choice(string.ascii_lowercase) for i in range(10))

        outFname = os.path.join(tempfile.gettempdir(), '%s.tif' % (fname))
        rect = rlayer.extent()
        dp = rlayer.dataProvider()
        raster = dp.dataSourceUri()

        img = imread(raster)

        if dp.bandCount() == 1:
            grayscale = img
        else:
            try:
                grayscale = rgb2gray(img)
            except Exception as e:
                feedback.reportError(
                    QCoreApplication.translate('Error', str(e)))
                feedback.reportError(QCoreApplication.translate('Error', ' '))
                feedback.reportError(
                    QCoreApplication.translate(
                        'Error',
                        'Failed to convert image from RGB to grayscale'))
                return {}

        if inv:
            grayscale = invert(grayscale)

        if block_size > 0 and block_size % 2 == 0:
            block_size += 1
            feedback.reportError(
                QCoreApplication.translate(
                    'Info',
                    'Warning: Algorithm requires an odd value for the block size parameter - selecting a value of %s'
                    % (block_size)))

        nrows, ncols = grayscale.shape
        if method == 0:
            if block_size > 0:
                grayscale = img_as_ubyte(grayscale)
                thresh = otsu(grayscale, disk(block_size))
                binary = (grayscale < thresh).astype(float)
            else:
                thresh = threshold_otsu(grayscale)
                binary = (grayscale < thresh).astype(float)
        else:
            if block_size == 0.0:
                block_size = int((nrows * 0.01) * (ncols * 0.01))
                if block_size % 2 == 0:
                    block_size += 1
                feedback.pushInfo(
                    QCoreApplication.translate(
                        'Info', 'Automatically selecting a block size of %s' %
                        (block_size)))

            if method == 1:
                local_thresh = threshold_local(image=grayscale,
                                               block_size=block_size,
                                               method=aMethod[adaptMethod])
                binary = (grayscale < local_thresh).astype(float)
            else:
                thresh = threshold_percentile(grayscale,
                                              disk(block_size),
                                              p0=p)
                binary = (grayscale > thresh).astype(float)

        if mode > 0:
            binary = modal(binary, disk(mode))
            binary = (binary > 1).astype(float)

        xres = rlayer.rasterUnitsPerPixelX()
        yres = rlayer.rasterUnitsPerPixelY()

        driver = osgdal.GetDriverByName('GTiff')
        dataset = driver.Create(
            outputRaster,
            ncols,
            nrows,
            1,
            osgdal.GDT_Float32,
        )

        dataset.SetGeoTransform(
            (rect.xMinimum(), xres, 0, rect.yMaximum(), 0, -yres))

        wkt_prj = rlayer.crs().toWkt()
        dataset.SetProjection(wkt_prj)
        band = dataset.GetRasterBand(1)
        band.SetNoDataValue(0)
        band.WriteArray(binary)
        dataset, band = None, None

        return {self.outRaster: outputRaster}