Beispiel #1
0
def label_particles_edge(im, sigma=2, closing_size=0, **extra_args):
    """ Segment image using Canny edge-finding filter.

        parameters
        ----------
        im : image in which to find particles
        sigma : size of the Canny filter
        closing_size : size of the closing filter

        returns
        -------
        labels : an image array of uniquely labeled segments
    """
    from skimage.morphology import square, binary_closing, skeletonize
    if skimage_version < StrictVersion('0.11'):
        from skimage.filter import canny
    else:
        from skimage.filters import canny
    edges = canny(im, sigma=sigma)
    if closing_size > 0:
        edges = binary_closing(edges, square(closing_size))
    edges = skeletonize(edges)
    labels = sklabel(edges)
    print "found {} segments".format(labels.max())
    # in ma.array mask, False is True, and vice versa
    labels = np.ma.array(labels, mask=edges == 0)
    return labels
Beispiel #2
0
def label_particles_edge(im, sigma=2, closing_size=0, **extra_args):
    """ label_particles_edge(image, sigma=3, closing_size=3)
        Returns the labels for an image.
        Segments using Canny edge-finding filter.

        keyword arguments:
        image        -- The image in which to find particles
        sigma        -- The size of the Canny filter
        closing_size -- The size of the closing filter
    """
    from skimage.morphology import square, binary_closing, skeletonize
    if skversion < version('0.11'):
        from skimage.filter import canny
    else:
        from skimage.filters import canny
    edges = canny(im, sigma=sigma)
    if closing_size > 0:
        edges = binary_closing(edges, square(closing_size))
    edges = skeletonize(edges)
    labels = sklabel(edges)
    print "found {} segments".format(labels.max())
    labels = np.ma.array(
        labels,
        mask=edges == 0)  # in ma.array mask, False is True, and vice versa
    return labels
Beispiel #3
0
def label_particles_edge(im, sigma=2, closing_size=0, **extra_args):
    """ Segment image using Canny edge-finding filter.

        parameters
        ----------
        im : image in which to find particles
        sigma : size of the Canny filter
        closing_size : size of the closing filter

        returns
        -------
        labels : an image array of uniquely labeled segments
    """
    from skimage.morphology import square, binary_closing, skeletonize
    if skimage_version < StrictVersion('0.11'):
        from skimage.filter import canny
    else:
        from skimage.filters import canny
    edges = canny(im, sigma=sigma)
    if closing_size > 0:
        edges = binary_closing(edges, square(closing_size))
    edges = skeletonize(edges)
    labels = sklabel(edges)
    print "found {} segments".format(labels.max())
    # in ma.array mask, False is True, and vice versa
    labels = np.ma.array(labels, mask=edges == 0)
    return labels
def label_particles_convolve(im, thresh=3, rmv=None, kern=0, **extra_args):
    """ label_particles_convolve(im, thresh=2)
        Returns the labels for an image
        Segments using a threshold after convolution with proper gaussian kernel
        Uses center of mass from original image to find centroid of segments

        Input:
            image   the original image
            thresh  the threshold above which pixels are included
                        if integer, in units of intensity std dev
                        if float, in absolute units of intensity
            rmv     if given, the positions at which to remove large dots
            kern   kernel size
    """
    # Michael removed disks post-convolution
    if rmv is not None:
        im = remove_disks(im, *rmv)
    if kern == 0:
        raise ValueError('kernel size `kern` not set')
    kernel = np.sign(kern)*gdisk(abs(kern))
    convolved = convolve(im, kernel)

    convolved -= convolved.min()
    convolved /= convolved.max()

    if isinstance(thresh, int):
        if rmv is not None:
            thresh -= 1 # smaller threshold for corners
        thresh = convolved.mean() + thresh*convolved.std()

    labels = sklabel(convolved > thresh)
    #print "found {} segments above thresh".format(labels.max())
    return labels, convolved
Beispiel #5
0
def label_particles_convolve(im, kern, thresh=3, rmv=None, **extra_args):
    """ Segment image using convolution with gaussian kernel and threshold

        parameters
        ----------
        im : the original image to be labeled
        kern : kernel size
        thresh : the threshold above which pixels are included
            if thresh >= 1, in units of intensity std dev
            if thresh < 1, in absolute units of intensity
        rmv : if given, the positions at which to remove large dots

        returns
        -------
        labels : an image array of uniquely labeled segments
        convolved : the convolved image before thresholding and segementation
    """
    if rmv is not None:
        im = remove_disks(im, *rmv)
    kernel = np.sign(kern) * gdisk(abs(kern) / 4, abs(kern))
    convolved = ndimage.convolve(im, kernel)
    convolved -= convolved.min()
    convolved /= convolved.max()

    if args.plot > 2:
        snapshot('kern', kernel)
        snapshot('convolved', convolved, cmap='gray')

    if thresh >= 1:
        if rmv is not None:
            thresh -= 1  # smaller threshold for corners
        thresh = thresh * convolved.std() + convolved.mean()
    threshed = convolved > thresh

    labels = sklabel(threshed, connectivity=1)

    if args.plot > 2:
        snapshot('threshed', threshed)
        snapshot('labeled', np.where(labels, labels, np.nan), cmap='prism_r')

    return labels, convolved
Beispiel #6
0
def label_particles_convolve(im, kern, thresh=3, rmv=None, **extra_args):
    """ Segment image using convolution with gaussian kernel and threshold

        parameters
        ----------
        im : the original image to be labeled
        kern : kernel size
        thresh : the threshold above which pixels are included
            if thresh >= 1, in units of intensity std dev
            if thresh < 1, in absolute units of intensity
        rmv : if given, the positions at which to remove large dots

        returns
        -------
        labels : an image array of uniquely labeled segments
        convolved : the convolved image before thresholding and segementation
    """
    if rmv is not None:
        im = remove_disks(im, *rmv)
    kernel = np.sign(kern)*gdisk(abs(kern)/4, abs(kern))
    convolved = ndimage.convolve(im, kernel)
    convolved -= convolved.min()
    convolved /= convolved.max()

    if args.plot > 2:
        snapshot('kern', kernel)
        snapshot('convolved', convolved, cmap='gray')

    if thresh >= 1:
        if rmv is not None:
            thresh -= 1  # smaller threshold for corners
        thresh = thresh*convolved.std() + convolved.mean()
    threshed = convolved > thresh

    labels = sklabel(threshed, connectivity=1)

    if args.plot > 2:
        snapshot('threshed', threshed)
        snapshot('labeled', np.where(labels, labels, np.nan), cmap='prism_r')

    return labels, convolved
def label_particles_edge(im, sigma=2, closing_size=0, **extra_args):
    """ label_particles_edge(image, sigma=3, closing_size=3)
        Returns the labels for an image.
        Segments using Canny edge-finding filter.

        keyword arguments:
        image        -- The image in which to find particles
        sigma        -- The size of the Canny filter
        closing_size -- The size of the closing filter
    """
    from skimage.morphology import square, binary_closing, skeletonize
    if skversion < version('0.11'):
        from skimage.filter import canny
    else:
        from skimage.filters import canny
    edges = canny(im, sigma=sigma)
    if closing_size > 0:
        edges = binary_closing(edges, square(closing_size))
    edges = skeletonize(edges)
    labels = sklabel(edges)
    print "found {} segments".format(labels.max())
    labels = np.ma.array(labels, mask=edges==0) # in ma.array mask, False is True, and vice versa
    return labels
Beispiel #8
0
def label_particles_convolve(im, thresh=3, rmv=None, csize=0, **extra_args):
    """ label_particles_convolve(im, thresh=2)
        Returns the labels for an image
        Segments using a threshold after convolution with proper gaussian kernel
        Uses center of mass from original image to find centroid of segments

        Input:
            image   the original image
            thresh  the threshold above which pixels are included
                        if integer, in units of intensity std dev
                        if float, in absolute units of intensity
            rmv     if given, the positions at which to remove large dots
            csize   kernel size
    """
    # Michael removed disks post-convolution
    if rmv is not None:
        im = remove_disks(im, *rmv)
    if csize == 0:
        raise ValueError('kernel size `csize` not set')
    elif csize < 0:
        ckern = -gdisk(-csize)
    else:
        ckern = gdisk(csize)
    convolved = convolve(im, ckern)

    convolved -= convolved.min()
    convolved /= convolved.max()

    if isinstance(thresh, int):
        if rmv is not None:
            thresh -= 1  # smaller threshold for corners
        thresh = convolved.mean() + thresh * convolved.std()

    labels = sklabel(convolved > thresh)
    #print "found {} segments above thresh".format(labels.max())
    return labels, convolved
def evaluate_nms_results_overlap(test_data,
                                 test_labels,
                                 test_predictions,
                                 print_steps=False,
                                 orig_only=False,
                                 mode="argmax",
                                 Pmin=0.5,
                                 padding=0,
                                 sliding_window_size=(48, 48),
                                 from_config=False,
                                 config={},
                                 min_ac=0.4,
                                 min_acc=0.6):
    """ Ohodnoti prekryti vyslednych bounding boxu s artefakty """

    # inicializace statistik
    TP, TN, FP, FN = 0, 0, 0, 0

    problematic = list()
    bounding_boxes = get_boxes(test_predictions,
                               test_labels,
                               padding=padding,
                               from_config=from_config,
                               config=config)
    #print(bounding_boxes)

    for index in range(test_labels.shape[0]):

        mask = test_labels[index].astype("uint8") * 255

        boxes = bounding_boxes[index]
        mask = np.argmax(mask, axis=2)  #*127

        TP0, TN0, FP0, FN0 = 0, 0, 0, 0

        # oriznuti obrazku a masky -> takhle se to dela u augmentovanych
        #img, mask = fe.cut_image(orig, mask)
        #mask /= 127.0
        # olabelovani artefaktu
        imlabel = sklabel(mask)
        # obarveni mist bez artefaktu na 0
        imlabel[(mask == 0) | (mask == 2)] = 0
        # vytvoreni prazdneho obrazku
        blank = np.zeros(mask.shape)
        # ziskani indexu artefaktu
        artefact_ids = np.unique(imlabel)[1:]
        # seznam boxu, ktere pokryvaji nejaky artefakt
        covered_box_ids = list()

        # prochazeni vsech artefaktu
        for i in artefact_ids:

            covered_by_bb = False

            for j, (y, h, x, w) in enumerate(boxes):
                # obarveni oblasti boxu
                blank[y:h, x:w] = 1
                # vypocet pixelu artefaktu celeho a v boxu
                na = np.sum((imlabel == i).astype(int))
                nab = np.sum((imlabel == i) & (blank == 1))
                # vypocet zastoupeni bb v artefaktu
                artefact_bb_coverage = float(nab) / na

                # pokud je artefakt alespon z poloviny pokryt boxem
                if artefact_bb_coverage >= 0.5:
                    #print artefact_bb_coverage

                    covered_box_ids.append(j)
                    # vytazeni frmau masky
                    mask_frame = mask[y:h, x:w]
                    # pokud jsou pokryty artefaktem -> TP, jinak FP
                    if covered_by_artefact(mask_frame,
                                           min_ac=min_ac,
                                           min_acc=min_acc):
                        TP += 1
                        TP0 += 1
                        covered_by_bb = True
                        break
                    elif artefact_bb_coverage == 1.0 and (np.sum(
                        (blank == 1).astype(int)) == sliding_window_size[0]**
                                                          2):
                        TP += 1
                        TP0 += 1
                        covered_by_bb = True
                        break
                    else:
                        FP += 1
                        FP0 += 1
                # znovu prebarveni pomocneho framu zpatky na 0
                blank[y:h, x:w] = 0

            # pokud neni pokryt zadnym boxem alespon z poloviny
            if not covered_by_bb:  # and na >= 300: # navic by mel byt dostatecne velky
                FN += 1
                FN0 += 1

        # prochazeni zatim neprohlendutych boxu
        for j in range(len(boxes)):
            if not j in covered_box_ids:
                FP += 1
                FP0 += 1
                """
                # vytazeni boxu
                y, h, x, w = boxes[j]
                mask_frame = mask[y:h, x:w]
                # pokud jsou pokryty artefaktem -> TP, jinak FP
                if covered_by_artefact(mask_frame):
                    TP += 1
                    TP0 += 1
                else:
                    FP += 1
                    FP0 += 1
                    """


#            if FN0 > TP0:
#                print imgname
#                problematic.append(imgname)

        if print_steps: print(TP0, TN0, FP0, FN0)

    # finalni vyhodnoceni
    recall = float(TP) / (TP + FN) if TP + FN > 0 else 0
    precision = float(TP) / (TP + FP) if TP + FP > 0 else 0
    FPC = float(FP) / test_data.shape[0] if test_data.shape[0] > 0 else 0
    #    if orig_only:
    #        FPC = float(FP) / len([k for k in test_results_nms.keys() if not "AFFINE" in k])

    print("[RESULT] Celkove vysledky pro " + str(test_data.shape[0]) +
          " obrazku:")
    print("         TP:", TP)
    print("         TN:", TN)
    print("         FP:", FP)
    print("         FN:", FN)
    print("        TPR:", recall)
    print("  precision:", precision)
    print("        FPC:", FPC)

    results_to_save = {
        "TP": TP,
        "TN": TN,
        "FP": FP,
        "FN": FN,
        "TPR": recall,
        "recall": recall,
        "precision": precision,
        "FPC": FPC,
        "problematic": problematic
    }

    return TN, FP, FN, TP, results_to_save