def foreground_separation(img_thre):
    contour_ref = img_thre.copy()
    img_thre = closing(img_thre, disk(1))

    img_thre = -img_thre + 1
    img_thre = closing(img_thre, disk(2))
    img_thre = -img_thre + 1

    img_thre = closing(img_thre, disk(20))

    img_thre = -img_thre + 1
    img_thre = closing(img_thre, disk(10))
    img_thre = -img_thre + 1

    img_thre = area_closing(img_thre, 20000, connectivity=2)
    contour_ref = contour_ref.astype(float)
    img_thre = img_thre.astype(float)
    img_binary = MorphGAC(-contour_ref + 1,
                          5,
                          -img_thre + 1,
                          smoothing=1,
                          balloon=0.8,
                          threshold=0.5)
    img_binary = area_closing(img_binary, 1000, connectivity=2)

    return -img_binary + 1
Example #2
0
def method_3(mask_img: "Image", down_factor=4) -> "NDArray[np.uint8]":
    """Downsample =>
    Area_opening followed by area_closing (Remove local maxima and minima) =>
    Upsample"""

    width, height = mask_img.width, mask_img.height

    # Downsample the image
    mask_arr = np.array(
        mask_img.resize((width // down_factor, height // down_factor), Image.NEAREST))
    del mask_img
    print('Finish downsampling')

    # Apply area_opening to remove local maxima with area < 200000 px
    mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2)
    print('Finish area_opening')

    # Apply area_closing to remove local minima with area < 200000 px
    mask_arr = morphology.area_closing(mask_arr, area_threshold=320000 // down_factor**2)
    print('Finish area_closing')

    # Upsample the output
    mask_arr = np.array(Image.fromarray(mask_arr).resize((width, height), Image.NEAREST))
    print('Finish upsampling')

    return mask_arr
Example #3
0
def removeSmallComponents(image: np.ndarray, component_min_area: int = 100):
    ''' Remove the components smaller than a defined area.
    Input(s):
        image: segmented map image
        component_min_area: threshold below which the components should be removed
    Output(s):
        image: grayscale cleaned segmented map image
    '''
    
    def labelsToGray(orig_gray: np.ndarray, orig_labels: np.ndarray, labeled: np.ndarray):
    
        new_gray = np.zeros(orig_gray.shape)

        for shade in np.unique(orig_gray):
            shade_labels = np.unique(orig_labels[orig_gray == shade])
            shade_labels = shade_labels[shade_labels != 0]

            for shade_label in shade_labels:
                new_gray[labeled == shade_label] = shade

        return new_gray
    
    if len(image.shape) > 2:
        gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    else:
        gray = image
    
    labels = findAllComponents(gray)
    cleared = remove_small_objects(labels, 100)
    closed = area_closing(dilation(dilation(cleared)))
    labels[cleared == 0] = closed[cleared == 0]
    
    new_gray = labelsToGray(gray, cleared, labels)
    
    return new_gray
Example #4
0
def method_6(mask_img: "Image", down_factor=4) -> "NDArray[np.uint8]":
    """Downsample => Area_opening (Remove local maxima) =>
    Swap index of GM and WM => Area_opening => Swap index back =>
    Area_closing => Morphological opening => Upsample"""
    # pylint: disable=invalid-name
    def swap_GM_WM(arr):
        """Swap GM and WM in arr (swaps index 1 and index 2)"""
        arr_1 = (arr == 1)
        arr[arr == 2] = 1
        arr[arr_1] = 2
        del arr_1
        return arr
    # pylint: enable=invalid-name

    width, height = mask_img.width, mask_img.height
    area_threshold_prop = 0.05
    area_threshold = int(area_threshold_prop * width * height // down_factor**2)

    # Downsample the image
    mask_arr = np.array(
        mask_img.resize((width // down_factor, height // down_factor), Image.NEAREST))
    del mask_img
    print('Finish downsampling')

    # Apply area_opening to remove local maxima with area < 20000 px
    mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2)
    print('Finish area_opening #1')

    # Swap index of GM and WM
    mask_arr = swap_GM_WM(mask_arr)
    print('Finish swapping index')

    # Apply area_opening to remove local maxima with area < 20000 px
    mask_arr = morphology.area_opening(mask_arr, area_threshold=320000 // down_factor**2)
    print('Finish area_opening #2')

    # Swap index back
    mask_arr = swap_GM_WM(mask_arr)
    print('Finish swapping index back')

    # Apply area_closing to remove local minima with area < 12500 px
    mask_arr = morphology.area_closing(mask_arr, area_threshold=200000 // down_factor**2)
    print('Finish area_closing')

    # Apply remove_small_objects to remove tissue residue with area < 0.05 * width * height
    tissue_arr = morphology.remove_small_objects(mask_arr > 0, min_size=area_threshold,
                                                 connectivity=2)
    mask_arr[np.invert(tissue_arr)] = 0
    del tissue_arr
    print('Finish remove_small_objects')

    # Apply opening with disk-shaped kernel (r=8) to smooth boundary
    mask_arr = morphology.opening(mask_arr, selem=morphology.disk(radius=32 // down_factor))
    print('Finish morphological opening')

    # Upsample the output
    mask_arr = np.array(Image.fromarray(mask_arr).resize((width, height), Image.NEAREST))
    print('Finish upsampling')

    return mask_arr
def NuclSegmentation(frames, channel, file_name):
    """
    NuclSegmentation function
    Segments cell nuclei
    """
    if not os.path.exists("output/" + str(file_name) + "/segmentation/nucl"):
        os.makedirs("output/" + str(file_name) + "/segmentation/nucl")

    frame_shape = frames[0].shape
    model = unet.get_unet(frame_shape[0], frame_shape[1], channel)
    model.compile(optimizer=optimizer, loss=loss, metrics=[metrics])

    model.load_weights(nucl_model)

    #    if contrast.lower()=="yes" :
    #
    #        bright_frames = []
    #
    #        for frame in frames :
    #
    #            frame = ContrastNormalized(frame, percentile)
    #
    #            bright_frames.append(frame)
    #
    #        bright_frames=np_.asanyarray(bright_frames)
    #        bright_frames = np_.expand_dims(bright_frames, axis=3)
    #        prediction = model.predict(bright_frames)

    #elif contrast.lower()=="no":

    frames = np_.asanyarray(frames)
    frames = np_.expand_dims(frames, axis=3)
    prediction = model.predict(frames)

    segmentation_org = []
    segmentation_dil = []
    segmentation_ero = []
    thr = 0.9

    for idx, pred in enumerate(prediction):

        pred = (pred.reshape(512, 512) > thr).astype(np_.uint8)
        pred_org = mp_.area_closing(pred)
        segmentation_org.append(pred_org)

        pred_dil = mp_.binary_dilation(pred_org, mp_.disk(2))
        segmentation_dil.append(pred_dil)

        pred_ero = mp_.binary_dilation(pred_org, mp_.disk(2))
        segmentation_ero.append(pred_ero)
        #    pl_.figure()
        #    pl_.imshow(pred,cmap="gray")
        labeled_sgm = mp_.label(pred_org, connectivity=1)
        pl_.imsave("output/" + str(file_name) + "/segmentation/nucl/frame" +
                   str(idx) + ".jpg",
                   labeled_sgm,
                   cmap="gray")

    return segmentation_org, segmentation_dil, segmentation_ero
def eliminarPontosPretos(
        img):  #função para eliminar os pontos pretos da imagem
    axs[1].set_title('Imagem com pontos pretos retirados')
    axs[1].set_axis_off()  #tira o eixo x e y das imagem que fica na coluna 1
    fechamento = morphology.area_closing(
        img, 64, 1
    )  #faz o fechamento(kernel/vizinhança=[4,4]) apenas com fig de tamanho <= 64(número de pixels) com conectividade 1
    axs[1].imshow(greyToRGB(fechamento), cmap='gray')
def main():
    name = sys.argv[1].split('/')[-1].split('.')[0]
    print("Segmenting image: {}".format(name))
    image_og = color.rgb2gray(plt.imread(data_path))
    image_og = plt.imread(data_path)
    seg = regiongrow(data_path)

    counter = 0
    for i in seg:
        for j in i:
            if (j == True):
                counter += 1
    print("Segmented area dimension: {}".format(counter))

    print("Processing...")
    seg = 255 * seg
    seg = morphology.dilation(seg, selem=morphology.disk(6))
    seg = morphology.area_closing(seg, area_threshold=3000)
    seg = morphology.dilation(seg, selem=morphology.disk(4))
    seg = morphology.area_closing(seg, area_threshold=400)
    seg = morphology.opening(seg, selem=morphology.disk(16))
    seg = morphology.binary_erosion(seg, selem=morphology.disk(4))

    seg = (1 / 255) * seg
    res = np.copy(image_og)
    res[seg == False] = 255

    res = filters.gaussian(res, sigma=1.5)
    thresh = filters.threshold_sauvola(res)
    res = (res > thresh) * 1
    res = morphology.area_closing(res, area_threshold=100)  #64
    res = morphology.binary_erosion(res)

    # Apply eroded mask again to delete borders from Sauvola
    seg = morphology.binary_erosion(seg, selem=morphology.disk(24))
    res[seg == False] = 255

    # show_comparison(image, seg)
    # save_comparison(image_og, res, name)
    # save_image(res, name)

    # print("Done.\n")
    return res
def areaclosing():
    global filterimage
    tree = morphology.area_closing(img,
                                   area_threshold=64,
                                   connectivity=1,
                                   parent=None,
                                   tree_traverser=None)
    filterimage = tree
    io.imshow(tree)
    io.show()
Example #9
0
def method_2(mask_arr: "NDArray[np.uint8]") -> "NDArray[np.uint8]":
    """Area_opening followed by area_closing (Remove local maxima and minima)"""

    # Apply area_opening to remove local maxima with area < 200000 px
    mask_arr = morphology.area_opening(mask_arr, area_threshold=200000)
    print('Finish area_opening')

    # Apply area_closing to remove local minima with area < 200000 px
    mask_arr = morphology.area_closing(mask_arr, area_threshold=200000)
    print('Finish area_closing')

    return mask_arr
Example #10
0
def area_closing():
    image = read_image_return_scikit()
    closed = morphology.area_closing(image,area_threshold=1, connectivity=1)
    
    fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(8, 3),
                                   sharex=True, sharey=True)

    ax0.imshow(image, cmap=plt.cm.gray)
    ax0.axis('off')
    ax1.imshow(closed, cmap=plt.cm.gray)
    ax1.axis('off')

    plt.show()
def hitOrMissMagenta(img):
    axs[0][1].set_title('Imagem original binária com inversão dos pixels')
    axs[1][0].set_title('Elemento Estruturante de cor magenta')
    axs[1][1].set_title(
        'Localização do Hit or Miss para objeto de cor magenta')
    axs[0][1].set_axis_off(
    )  #tira o eixo x e y das imagem que fica na linha 0 coluna 1
    axs[1][0].set_axis_off(
    )  #tira o eixo x e y das imagem que fica na linha 1 coluna 0
    axs[1][1].set_axis_off(
    )  #tira o eixo x e y das imagem que fica na linha 1 coluna 1
    fechamento = morphology.area_closing(img, 64, 1)  #retira todos os pontos
    linha, coluna = fechamento.shape
    for i in range(linha):
        for j in range(coluna):
            if (
                    fechamento[i][j] != 88
            ):  #seta os pixels da fig de cor não magenta(na escala de cinza) para branco
                fechamento[i][j] = 255
    thresh = threshold_otsu(
        img
    )  #auxilia na transformação da img na escola de cinza para binária// threshold automatico
    binary = invert(img > thresh).astype(
        np.int
    )  #tranforma a imagem que tem a figura magenta em binaria(true/false)
    axs[0][1].imshow(
        binary,
        cmap='gray')  #mostra a imagem original binaria(com pixels invertidos)
    thresh2 = threshold_otsu(
        fechamento
    )  #auxilia na transformação da img na escala de cinza para binária
    binary2 = invert(fechamento > thresh2).astype(
        np.int
    )  #tranforma a imagem que tem a figura magenta em binaria(true/false)
    binary2 = binary2[~np.all(binary2 == 0,
                              axis=1)]  #deleta as linhas que tem somente zero
    idx = np.argwhere(
        np.all(binary2[..., :] == 0,
               axis=0))  #procura por tds colunas que tem somente zero
    binary2 = np.delete(binary2, idx,
                        axis=1)  #deleta tds colunas que tem somente zero
    axs[1][0].imshow(
        binary2,
        cmap='gray')  #mostra o elementro estruturante na forma binária
    binary2[
        binary2 ==
        0] = 2  #pixels de n° zero sao setados para 2(dont care) não precisa ser comparado
    hitOrMiss = mh.hitmiss(
        binary, binary2
    )  #operação hit or miss para objeto de cor magenta (retorna o ponto central do objeto localizado)
    axs[1][1].imshow(hitOrMiss, cmap='gray')
def CellSegmentation(frames, channel, file_name):

    if not os.path.exists("output/" + str(file_name) + "/segmentation/cell"):
        os.makedirs("output/" + str(file_name) + "/segmentation/cell")

    frame_shape = frames[0].shape

    model = unet.get_unet(frame_shape[0], frame_shape[1], channel)
    model.compile(optimizer=optimizer, loss=loss, metrics=[metrics])
    model.load_weights(cell_model)

    if contrast.lower() == "yes":

        bright_frames = []

        for frame in frames:

            frame = ContrastNormalized(frame, percentile)
            pl_.imshow(frame)
            bright_frames.append(frame)

        bright_frames = np_.asanyarray(bright_frames)
        bright_frames = np_.expand_dims(bright_frames, axis=3)
        prediction = model.predict(bright_frames)

    elif contrast.lower() == "no":

        frames = np_.asanyarray(frames)
        frames = np_.expand_dims(frames, axis=3)
        prediction = model.predict(frames)

    segmentation = []
    thr = 0.9

    for idx, pred in enumerate(prediction):

        pred = (pred.reshape(frame_shape[0], frame_shape[1]) > thr).astype(
            np_.uint8)
        pred = mp_.area_closing(pred)
        #pred=mp_.binary_dilation(pred, mp_.disk(2))
        segmentation.append(pred)
        labeled_sgm = mp_.label(pred, connectivity=1)
        #    pl_.figure()
        #    pl_.imshow(pred,cmap="gray")
        pl_.imsave("output/" + str(file_name) + "/segmentation/cell/frame" +
                   str(idx) + ".jpg",
                   labeled_sgm,
                   cmap="gray")

    return segmentation
Example #13
0
    def pre_process(self):
        """
        Pre-processing algorithm to reduce noise of images

        :return: 2d-array of pixels
        """
        # translate to gray scale the rgb image
        self.to_gray_scale()
        # median filtering
        self.img = median(self.img)
        # otsu threshold
        thresh = threshold_otsu(self.img)
        self.img = self.img > thresh
        # closing
        self.img = area_closing(self.img, area_threshold=64)
        # the image pixel are considered as unsigned integer, not float
        self.img = self.img.astype(np.uint8)
def esqueletoVermelho(img):
    axs[1].set_title('Esqueleto da imagem de cor vermelha')
    axs[1].set_axis_off()  #tira o eixo x e y das imagem que fica na coluna 1
    fechamento = morphology.area_closing(img, 64, 1)  #retira todos os pontos
    linha, coluna = fechamento.shape
    for i in range(linha):
        for j in range(coluna):
            if (
                    fechamento[i][j] != 72
            ):  #seta os pixels da fig de cor não vermelha(na escala de cinza) para branco
                fechamento[i][j] = 255
    thresh = threshold_otsu(
        fechamento
    )  #auxilia na transformação da img na escola de cinza para binária// threshold automatico
    binary = invert(fechamento > thresh).astype(
        np.int
    )  #tranforma a imagem que tem a figura magenta em binaria(true/false)
    esqueleto = morphology.skeletonize(binary)
    axs[1].imshow(esqueleto, cmap='gray')
def esqueletoFechoConvexoVermelho(img):
    axs[1].set_title('Esqueleto do fecho convexo da imagem de cor vermelha')
    axs[1].set_axis_off()  #tira o eixo x e y das imagem que fica na coluna 1
    fechamento = morphology.area_closing(img, 64, 1)  #retira todos os pontos
    linha, coluna = fechamento.shape
    for i in range(linha):
        for j in range(coluna):
            if (
                    fechamento[i][j] != 72
            ):  #seta os pixels da fig de cor não vermelha(na escala de cinza) para branco
                fechamento[i][j] = 255
    thresh = threshold_otsu(
        fechamento
    )  #auxilia na transformação da img na escola de cinza para binária(0-ausencia de cor 1-presença de cor)
    binary = invert(
        fechamento > thresh
    )  #tranforma a imagem em binaria em seguida faz a troca das cor dos pixels
    fechoConvexo = morphology.convex_hull_object(
        binary)  #retorna o fecho convexo de cada objeto
    esqueleto = morphology.skeletonize(fechoConvexo)
    axs[1].imshow(esqueleto, cmap='gray')
def fechoConvexo(img):
    axs[1].set_title('Imagem com fecho convexo dos objetos')
    axs[1].set_axis_off()  #tira o eixo x e y das imagem que fica na coluna 1
    fechamento = morphology.area_closing(
        img, 64,
        1)  #retira os pontos para fazer o fecho apenas das figuras restantes
    linha, coluna = fechamento.shape
    for i in range(linha):
        for j in range(coluna):
            if (
                    fechamento[i][j] == 88
            ):  #seta os pixels da fig de cor magenta(na escala de cinza) para branco
                fechamento[i][j] = 255
    thresh = threshold_otsu(
        fechamento
    )  #auxilia na transformação da img na escola de cinza para binária(0-ausencia de cor 1-presença de cor)
    binary = invert(
        fechamento > thresh
    )  #tranforma a imagem em binaria em seguida faz a troca das cor dos pixels
    fechoConvexo = morphology.convex_hull_object(
        binary)  #retorna o fecho convexo de cada objeto
    axs[1].imshow(fechoConvexo, cmap='gray')
Example #17
0
    def _erode_dilate(self, image, file_name, folder_name):
        #get a cross kernel
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))
        horiz_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1))

        #area closing removes all dark structures of an image
        opening = area_closing(image, 50000)

        erode = binary_erosion(opening)
        #erode 2 times with horizontal kernel
        for i in range(2):
            erode = binary_erosion(erode, horiz_kernel)

        #dilate 2 times with elliptical kernel
        dilate = binary_dilation(erode, kernel)
        for i in range(2):
            dilate = binary_dilation(dilate, kernel)

        output_path = folder_name + "\\" + file_name

        matplotlib.image.imsave(output_path, dilate)

        return dilate
Example #18
0
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
# Press the green button in the gutter to run the script.
from collections import deque

if __name__ == '__main__':
    img = cv2.imread("im1.jpg")
    """Part1"""
    image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    figure_size = 9  # the dimension of the x and y axis of the kernel.
    kernel = np.ones((3, 3), np.uint8)
    new_image = cv2.GaussianBlur(image, (15, 19), 0)
    edges = cv2.Canny(new_image, 0, 20)
    kernel = np.ones((3, 3), np.uint8)
    dilate = cv2.dilate(edges, kernel, iterations=4)
    foreground = area_closing(dilate, 1024, connectivity=1)
    plt.imshow(foreground, cmap=plt.cm.gray)
    plt.show()
    gold = np.loadtxt("im3_gold_mask.txt")
    gold1 = np.loadtxt("im3_gold_cells.txt")

    gold_int = gold.astype(int)
    gold1_int = gold1.astype(int)

    foreground[foreground == 255] = 1
    reshaped_gold = gold_int.reshape(-1)
    reshaped1_gold = gold1_int.reshape(-1)
    print(reshaped_gold)
    print(reshaped1_gold)
    foreground_final = foreground.reshape(-1)
    """print(classification_report(reshaped_gold, foreground_final))"""
Example #19
0
    def buttonSave(arg):

        copy = arg[1]
        imageTemp = arg[2]
        filterTry = filterVar.get()
        if (filterTry == 1):
            copy = cv2.GaussianBlur(copy, (5, 5), 0)
        elif (filterTry == 2):
            copy = cv2.Canny(copy, 100, 150)
        elif (filterTry == 3):
            copy = filters.roberts(imageTemp)
        elif (filterTry == 4):
            copy = filters.sato(imageTemp)
        elif (filterTry == 5):
            copy = filters.scharr(imageTemp)
        elif (filterTry == 6):
            copy = filters.sobel(imageTemp)
        elif (filterTry == 7):
            copy = filters.unsharp_mask(copy, radius=30, amount=3)
        elif (filterTry == 8):
            #copy = filters.median(imageTemp, disk(5))
            b, g, r = cv2.split(copy)
            b = filters.median(b, disk(5))
            g = filters.median(g, disk(5))
            r = filters.median(r, disk(5))
            copy = cv2.merge((b, g, r))
        elif (filterTry == 9):
            copy = filters.prewitt(imageTemp)
        elif (filterTry == 10):
            copy = filters.rank.modal(imageTemp, disk(5))
        flag = 0
        if (np.ndim(copy) == 2):
            flag = 0
        else:
            flag = 1

        if (hEsitleme.get() or hGrafik.get()):
            if (flag):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)
            if (hGrafik.get()):
                plt.hist(copy.ravel(), 256, [0, 256])
                plt.show()
            if (hEsitleme.get()):
                copy = cv2.equalizeHist(copy)

        if (uzaysalVars[0].get()):
            reScaleRatio = float(uzaysalVarsInputs[0].get())
            if (np.ndim(copy) == 3):
                b, g, r = cv2.split(copy)
                b = transform.rescale(b, reScaleRatio)
                g = transform.rescale(g, reScaleRatio)
                r = transform.rescale(r, reScaleRatio)
                copy = cv2.merge((b, g, r))
            else:
                copy = transform.rescale(copy, reScaleRatio)

        if (uzaysalVars[1].get()):
            resizeY = float(uzaysalVarsInputs[1].get())
            resizeX = float(uzaysalVarsInputs[2].get())
            if (np.ndim(copy) == 3):
                b, g, r = cv2.split(copy)
                b = transform.resize(
                    b, (b.shape[0] // resizeX, b.shape[1] // resizeY),
                    anti_aliasing=True)
                g = transform.resize(
                    g, (g.shape[0] // resizeX, g.shape[1] // resizeY),
                    anti_aliasing=True)
                r = transform.resize(
                    r, (r.shape[0] // resizeX, r.shape[1] // resizeY),
                    anti_aliasing=True)
                copy = cv2.merge((b, g, r))
            else:
                copy = transform.resize(
                    copy, (copy.shape[0] // resizeX, copy.shape[1] // resizeY),
                    anti_aliasing=True)
        if (uzaysalVars[2].get()):
            copy = transform.swirl(copy, rotation=0, strength=10, radius=120)
        if (uzaysalVars[3].get()):
            copy = transform.rotate(copy,
                                    int(uzaysalVarsInputs[3].get()),
                                    resize=True)
        if (uzaysalVars[4].get()):
            copy = copy[:, ::-1]

        if (yogunlukVars[0].get() or yogunlukVars[1].get()):
            if (yogunlukVars[0].get()):
                startINX = int(yogunlukVars[2].get())
                finishINX = int(yogunlukVars[3].get())
                copy = exposure.rescale_intensity(copy,
                                                  in_range=(startINX,
                                                            finishINX))
            if (yogunlukVars[1].get()):
                startOUTX = int(yogunlukVars[4].get())
                finishOUTX = int(yogunlukVars[5].get())
                copy = exposure.rescale_intensity(copy,
                                                  out_range=(startOUTX,
                                                             finishOUTX))

        morfoTry = morfVar.get()
        morfoGirisN = 0
        if (np.ndim(copy) == 3):
            morfoGirisN = 1

        if (morfoTry == 1):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.area_closing(b, 128, 9)
                g = morphology.area_closing(g, 128, 9)
                r = morphology.area_closing(r, 128, 9)
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.area_closing(copy)
        elif (morfoTry == 2):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.area_opening(b, 128, 9)
                g = morphology.area_opening(g, 128, 9)
                r = morphology.area_opening(r, 128, 9)
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.area_opening(copy)
        elif (morfoTry == 3):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.erosion(b, disk(6))
                g = morphology.erosion(g, disk(6))
                r = morphology.erosion(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.erosion(copy, disk(6))
        elif (morfoTry == 4):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.dilation(b, disk(6))
                g = morphology.dilation(g, disk(6))
                r = morphology.dilation(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.dilation(copy, disk(6))
        elif (morfoTry == 5):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.opening(b, disk(6))
                g = morphology.opening(g, disk(6))
                r = morphology.opening(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.opening(copy, disk(6))
        elif (morfoTry == 6):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.closing(b, disk(6))
                g = morphology.opening(g, disk(6))
                r = morphology.opening(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.opening(copy, disk(6))
        elif (morfoTry == 7):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.white_tophat(b, disk(6))
                g = morphology.white_tophat(g, disk(6))
                r = morphology.white_tophat(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.white_tophat(copy, disk(6))
        elif (morfoTry == 8):
            if (morfoGirisN):
                b, g, r = cv2.split(copy)
                b = morphology.black_tophat(b, disk(6))
                g = morphology.black_tophat(g, disk(6))
                r = morphology.black_tophat(r, disk(6))
                copy = cv2.merge((b, g, r))
            else:
                copy = morphology.black_tophat(copy, disk(6))
        elif (morfoTry == 10):
            if (morfoGirisN):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)

            copy = exposure.rescale_intensity(copy)
            local_maxima = extrema.local_maxima(copy)
            label_maxima = measure.label(local_maxima)
            copy = color.label2rgb(label_maxima,
                                   copy,
                                   alpha=0.7,
                                   bg_label=0,
                                   bg_color=None,
                                   colors=[(1, 0, 0)])
        elif (morfoTry == 9):
            if (morfoGirisN):
                copy = cv2.cvtColor(copy, cv2.COLOR_BGR2GRAY)
            copy = exposure.rescale_intensity(copy)
            h = 0.05
            h_maxima = extrema.h_maxima(copy, h)
            label_h_maxima = measure.label(h_maxima)
            copy = color.label2rgb(label_h_maxima,
                                   copy,
                                   alpha=0.7,
                                   bg_label=0,
                                   bg_color=None,
                                   colors=[(1, 0, 0)])
        arg[1] = copy
        arg[2] = imageTemp
        cv2.imshow("org", copy)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        """
Example #20
0
th_2 = filters.threshold_sauvola(img_hsv, window_size=7)
img_th2 = img_hsv < th_2
plt.imshow(img_th2)

# combine results of both filters
img_bin = np.logical_or(img_th1, img_th2)
plt.imshow(img_bin)


# Use erosion to filter out noise (dots) then apply median filter to smooth and isolate regions
from skimage.morphology import area_closing, disk
from skimage.filters import median
from scipy import ndimage as ndi

img_bin = area_closing(img_bin, area_threshold=128)
img_bin = median(img_bin, disk(5))
# img_bin = ndi.binary_fill_holes(img_bin)
plt.imshow(img_bin)



# ============================================================================ #

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

from skimage import data
from skimage.filters import threshold_otsu
from skimage.segmentation import clear_border
from skimage.measure import label, regionprops
Example #21
0
 def fill_holes(image: np.ndarray, filling_range=400):
     print("Hole Filling...", end='', flush=True)
     result = morphology.area_closing(image, area_threshold=filling_range)
     print('[DONE]')
     return result
Example #22
0
import skimage.morphology as mp
import cv2 as cv

img = cv.imread("bw.jpg")
closed = mp.area_closing(img, 135, connectivity=1)
cv.imshow('closed', closed)
cv.waitKey(0)
Example #23
0
def inpaint(label_img):
    return morphology.area_closing(label_img, area_threshold=2000)
Example #24
0
def img_to_nodes(img, mask):
    def weight_boundary(graph, src, dst, n):
        """
        Handle merging of nodes of a region boundary region adjacency graph.

        This function computes the `"weight"` and the count `"count"`
        attributes of the edge between `n` and the node formed after
        merging `src` and `dst`.


        Parameters
        ----------
        graph : RAG
            The graph under consideration.
        src, dst : int
            The vertices in `graph` to be merged.
        n : int
            A neighbor of `src` or `dst` or both.

        Returns
        -------
        data : dict
            A dictionary with the "weight" and "count" attributes to be
            assigned for the merged node.

        """
        default = {'weight': 0.0, 'count': 0}

        count_src = graph[src].get(n, default)['count']
        count_dst = graph[dst].get(n, default)['count']

        weight_src = graph[src].get(n, default)['weight']
        weight_dst = graph[dst].get(n, default)['weight']

        count = count_src + count_dst
        return {
            'count': count,
            'weight': (count_src * weight_src + count_dst * weight_dst) / count
        }

    def merge_boundary(graph, src, dst):
        """Call back called before merging 2 nodes.

        In this case we don't need to do any computation here.
        """
        pass

    def separate_regions(labels, graph):
        indices = {}
        for x in range(labels.shape[0]):
            for y in range(labels.shape[1]):
                id = labels[x][y]
                if id not in indices:
                    indices[id] = []
                indices[id].append((x, y))
        nodes = {}
        for key, value in indices.items():
            nodes[key] = Node(key, graph, np.array(value))
        for n in nodes.values():
            n.update_neighbours(nodes, labels.size)
        return nodes

    def relabel(labels):
        idx, counts = np.unique(labels, return_counts=True)
        idx = idx[counts.argsort()]
        idx = idx[::-1]
        ch = np.zeros_like(idx)
        ch[idx] = np.arange(idx.size)
        labels = ch[labels]
        return labels

    edges = edg(img)
    labels = me.label(mask)
    g = graph.rag_boundary(labels, edges)
    labels = graph.merge_hierarchical(labels,
                                      g,
                                      thresh=0.2,
                                      rag_copy=False,
                                      in_place_merge=True,
                                      merge_func=merge_boundary,
                                      weight_func=weight_boundary)
    labels = relabel(labels)
    labels = mp.dilation(labels)
    labels = mp.area_closing(labels, 10)
    labels = mp.erosion(labels)
    g = graph.rag_boundary(labels, edges)
    nodes = separate_regions(labels, g)

    return labels, nodes
Example #25
0
    cangurus.append(
        imread("C:/Users/Windows/Desktop/RP/RP-2019.2/Projeto2/kangaroo/" + k,
               True))

from skimage.transform import rescale, resize, downscale_local_mean
from skimage import filters, util
from skimage import feature
from skimage import morphology
for j in range(len(flamingos)):

    flamingos[j] = resize(flamingos[j], (250, 200))
    flamingos[j] = filters.median(flamingos[j])
    flamingos[j] = filters.roberts(flamingos[j])

    flamingos[j] = morphology.area_closing(flamingos[j])
    flamingos[j] = feature.canny(flamingos[j], sigma=1)
    flamingos[j] = util.img_as_float32(flamingos[j])
    #imshow(flamingos[j])
    #plt.show()

for j in range(len(cangurus)):

    cangurus[j] = resize(cangurus[j], (250, 200))
    cangurus[j] = filters.median(cangurus[j])
    cangurus[j] = filters.roberts(cangurus[j])
    cangurus[j] = morphology.area_closing(cangurus[j])
    cangurus[j] = feature.canny(cangurus[j], sigma=1)
    cangurus[j] = util.img_as_float32(cangurus[j])
    #imshow(cangurus[j])
    #plt.show()
    out = roi

    #roi = img

    # segmentation
    # Saliency
    (success, saliencyMap) = saliency.computeSaliency(roi)
    saliencyMap = (saliencyMap * 255).astype("uint8")

    binout = cv2.threshold(saliencyMap, 0, 255,
                           cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

    binout = morphology.binary_dilation(binout, selem11)
    binout = morphology.binary_erosion(binout, selem5)
    binout = morphology.area_closing(binout.astype('uint8'), 128)
    '''
    #out = saliencyMap
    # level set
    
    print('segmenting by level set')
    #salinecyMap = cv2.equalizeHist(saliencyMap)
    #im1 = (saliencyMap/np.max(saliencyMap)) ** 0.5 * np.max(saliencyMap)
    #im1 = morphology.area_opening(cv2.threshold(saliencyMap, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1])
    #im1 = morphology.area_closing(cv2.threshold(saliencyMap, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1], 1024)
    
    phi0 = levelset.default_phi(roi)
    phi = levelset.levelset(roi, phi0, 200, prior, dt=1, v=0.1, mu=500, lamb1=1, lamb2=1, tau=0.05)

    binout = np.heaviside(phi, 1)
    
io.imshow(test)
io.show()
ch = Node(1,1,test,None)
ch.find_branch_ends()
print(ch.longest_end.count)
ch.print_longest()
'''
#####################################

img = conv(img).astype(int)
#save('convolved.jpg',img)

thresh = threshold_otsu(img)
binary_img = binary_closing(img > thresh)

binary_img = area_closing(binary_img * 255)
binary_img = binary_img > 200

#save('binary.jpg',binary_img*255)

#peak_img = peak_local_max(gaussian(binary_img*255,3),indices = False)
#save('peak.jpg',peak_img*255)

skele_img = skeletonize(binary_img)
#save('skele_img.jpg',skele_img*255)

label_img = label(skele_img)
props = regionprops(label_img)

msk_img = np.zeros(skele_img.shape)