Example #1
0
    def run3(self):
        """ Cette fonction test des alternatives à SIFT et ORB. Ne fonctionne pas."""
        for x in xrange(len(self.stack)-1):
            print('Traitement image ' + str(x+1))
            im1,im2 = 255.*gaussian_filter(self.stack[x,...], sqrt(self.initial_sigma**2 - 0.25)), 255.*gaussian_filter(self.stack[x+1,...], sqrt(self.initial_sigma**2 - 0.25))
            im1,im2 = enhance_contrast(normaliser(im1), square(3)), enhance_contrast(normaliser(im2), square(3))
            im1, im2 = normaliser(im1), normaliser(im2)
            
            b = cv2.BRISK()
            #b.create("Feature2D.BRISK")
            
            k1,d1 = b.detectAndCompute(im1,None)
            k2,d2 = b.detectAndCompute(im2,None)
            
            bf = cv2.BFMatcher(cv2.NORM_HAMMING)
            matches = bf.match(d1,d2)
            
            g1,g2 = [],[]
            for i in matches:
                g1.append(k1[i.queryIdx].pt)
                g2.append(k2[i.trainIdx].pt)

            model, inliers = ransac((np.array(g1), np.array(g2)), AffineTransform, min_samples=3, residual_threshold=self.min_epsilon, max_trials=self.max_trials, stop_residuals_sum=self.min_inlier_ratio)
            
            self.stack[x+1,...] = warp(self.stack[x+1,...], AffineTransform(rotation=model.rotation, translation=model.translation), output_shape=self.stack[x+1].shape)

        self.stack = self.stack.astype(np.uint8)
Example #2
0
    def run4(self):
        """ Cette fonction recadre les images grâce à SURF et RANSAC, fonctionne bien."""
        for x in xrange(len(self.stack)-1):
            print('Traitement image ' + str(x+1))
            im1,im2 = 255.*gaussian_filter(self.stack[x,...], sqrt(self.initial_sigma**2 - 0.25)), 255.*gaussian_filter(self.stack[x+1,...], sqrt(self.initial_sigma**2 - 0.25))
            im1,im2 = enhance_contrast(normaliser(im1), square(5)), enhance_contrast(normaliser(im2), square(5))
            im1, im2 = normaliser(im1), normaliser(im2)
            
            b = cv2.SURF()
            #b.create("Feature2D.BRISK")
            
            k1,d1 = b.detectAndCompute(im1,None)
            k2,d2 = b.detectAndCompute(im2,None)
            
            bf = cv2.BFMatcher()
            matches = bf.knnMatch(d1,d2, k=2)

            # Apply ratio test
            good = []
            for m,n in matches:
                if m.distance < 0.75*n.distance:
                    good.append(m)
            
            g1,g2 = [],[]
            for i in good:
                g1.append(k1[i.queryIdx].pt)
                g2.append(k2[i.trainIdx].pt)

            model, inliers = ransac((np.array(g1), np.array(g2)), AffineTransform, min_samples=3, residual_threshold=self.min_epsilon, max_trials=self.max_trials, stop_residuals_sum=self.min_inlier_ratio)
            
            self.stack[x+1,...] = warp(self.stack[x+1,...], AffineTransform(rotation=model.rotation, translation=model.translation), output_shape=self.stack[x+1].shape)

        self.stack = self.stack.astype(np.uint8)
Example #3
0
def contrast(image_in, cont_size):
    if cont_size > 0:
        print('enhancing contrast, width', str(cont_size))
        cont = rank.enhance_contrast(np.copy(image_in), disk(cont_size))
        return cont
    if cont_size == 0:
        return image_in
Example #4
0
def filter_test():
    in_dir = os.path.join(PROJECT_ROOT, 'Data', 'Step2', 'Validation')

    res_imgs = []
    for sub_dir in get_immediate_subfolders(in_dir):
        full_dir = os.path.join(in_dir, sub_dir)
        for sub_dir2 in get_immediate_subfolders(full_dir):
            full_dir2 = os.path.join(full_dir, sub_dir2)

            for img_file in os.listdir(full_dir2):
                full_path_name = os.path.join(full_dir2, img_file)
                if os.path.isfile(full_path_name) and img_file.lower().endswith(tuple(EXT_FILTER)):
                    ori_img = skio.imread(full_path_name)
                    gry_img = skcolor.rgb2gray(ori_img)
                    res_img = enhance_contrast(gry_img, disk(5))
                    # res_img = exps.adjust_gamma(gry_img)
                    # res2_img = exps.rescale_intensity(res_img)
                    # flt_img = np.array(res_img > flts.threshold_li(res_img))
                    res_imgs.append(res_img.reshape(-1))

    arr_imgs = np.asarray(res_imgs)
    img_cnt = arr_imgs.shape[0]
    n_col = math.ceil(math.sqrt(img_cnt))
    n_row = math.ceil(img_cnt / n_col)

    fig = plt.figure(figsize=(18, 12))
    for i in range(0, img_cnt):
        ax = fig.add_subplot(n_row, n_col, (i + 1))
        img = ax.imshow(arr_imgs[i].reshape(28, 96))

        img.axes.get_xaxis().set_visible(False)
        img.axes.get_yaxis().set_visible(False)

    plt.suptitle('All {} Samples'.format(img_cnt), size=12, x=0.518, y=0.935)
    plt.show()
Example #5
0
def contrast_nuclei(image_in, cont_size):
    if cont_size > 0:
        print('Enhancing contrast')
        return rank.enhance_contrast(np.copy(image_in), disk(cont_size))
    if cont_size == 0:
        print('Not enhancing contrast')
        return image_in
Example #6
0
def add_index_layer(img, append=False):
    img_rows = np.shape(img)[0]
    img_cols = np.shape(img)[1]
    # entropy 熵
    e = (
        (entropy(img[:, :, 0], disk(1)) + entropy(img[:, :, 1], disk(1)) + entropy(img[:, :, 2], disk(1))) / 3).reshape(
        [img_rows, img_cols, 1])
    # contrast 对比度
    c = ((enhance_contrast(img[:, :, 0], disk(1)) + enhance_contrast(img[:, :, 1], disk(1)) + enhance_contrast(
        img[:, :, 2], disk(1))) / 3).reshape([img_rows, img_cols, 1])
    # mean 均值
    m = ((mean(img[:, :, 0], disk(1)) + mean(img[:, :, 1], disk(1)) + mean(img[:, :, 2], disk(1))) / 3).reshape(
        [img_rows, img_cols, 1])
    if append:
        return np.concatenate([img, e, c, m], axis=2)
    else:
        return np.concatenate([e, c, m], axis=2)
        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))
def filter_images(path, filename):
    """
    Applies filters to image, that is located in folder
    :param path:        define path to temp folder
    :param filename:    name of image for processing
    :return:            filtered image
    """
    img_data = io.imread(path + filename, as_grey=True)
    # Set better contrast to raw data with disk r = 20
    img_data = enhance_contrast(img_data, disk(20))
    img_data_dil = dilation(img_data, disk(1))

    return img_data_dil
Example #9
0
def shanghai_chunk_code_processing(img, row_range, column_range):
    """对于上海分割验证码的处理

    :param img: 上海验证码分割后的图片
    :param row_range: 分割的横坐标范围
    :param column_range: 分割的纵坐标范围
    :return: 二值化后的分割验证码图片
    """
    img = img[column_range[0]:column_range[1], row_range[0]:row_range[1]]
    img = sfr.enhance_contrast(img, morphology.selem.disk(1))
    img = sfr.maximum(img, morphology.selem.rectangle(3, 2))
    img = morphology.dilation(img, morphology.selem.rectangle(2, 1))
    thresh = filters.threshold_otsu(img)
    img = (img >= thresh) * 1.0
    return img
Example #10
0
    def run2(self):
        """ Cette fonction recadre les images grâce à SIFT et RANSAC, fonctionne bien."""
        for x in xrange(len(self.stack)-1):
            print('Traitement image ' + str(x+1))
            im1,im2 = 255.*gaussian_filter(self.stack[x,...], sqrt(self.initial_sigma**2 - 0.25)), 255.*gaussian_filter(self.stack[x+1,...], sqrt(self.initial_sigma**2 - 0.25))
            im1,im2 = enhance_contrast(normaliser(im1), square(3)), enhance_contrast(normaliser(im2), square(3))
            im1, im2 = normaliser(im1), normaliser(im2)

            sift = cv2.SIFT()

            # find the keypoints and descriptors with SIFT
            kp1, des1 = sift.detectAndCompute(im1,None)
            kp2, des2 = sift.detectAndCompute(im2,None)

            # BFMatcher with default params
            bf = cv2.BFMatcher()
            matches = bf.knnMatch(des1,des2, k=2)

            # Apply ratio test
            good = []
            for m,n in matches:
                if m.distance < 0.75*n.distance:
                    good.append(m)


            # good est une liste de DMatch
            g1,g2 = [],[]
            for i in good:
                g1.append(kp1[i.queryIdx].pt)
                g2.append(kp2[i.trainIdx].pt)

            model, inliers = ransac((np.array(g1), np.array(g2)), AffineTransform, min_samples=3, residual_threshold=self.min_epsilon, max_trials=self.max_trials, stop_residuals_sum=self.min_inlier_ratio)
            
            self.stack[x+1,...] = warp(self.stack[x+1,...], AffineTransform(rotation=model.rotation, translation=model.translation), output_shape=self.stack[x+1].shape)

        self.stack = self.stack.astype(np.uint8)
Example #11
0
def contrast_booster(array):
    array = array.astype(float)
    array = standarize_brightness(array, 1, array.shape[1])
    array = standarize_brightness(array, array.shape[0], 1)
    array -= array.min()
    array = array / array.max() - 0.5
    array *= 2.0
    array = enhance_contrast(array, disk(2))
    '''
    array = standarize_brightness(array, 1, 128)
    #array = equalize_hist(array)
    array = array - array.min()
    array = array / array.max() * 255.0
    array = array.astype(np.uint8)
    '''
    return array
Example #12
0
def hebei_chunk_code_processing(img, row_range, column_range):
    """对于河北分割验证码的处理

    :param img: 河北验证码分割后的图片
    :param row_range: 分割的横坐标范围
    :param column_range: 分割的纵坐标范围
    :return: 二值化后的分割验证码图片
    """
    img = img[column_range[0]:column_range[1], row_range[0]:row_range[1]]
    img = sfr.enhance_contrast(img, morphology.selem.disk(1))
    img = sfr.maximum(img, morphology.selem.rectangle(3, 2))
    img = morphology.dilation(img, morphology.selem.rectangle(2, 1))
    # thresh = filters.threshold_otsu(img)
    # img = (img >= thresh) * 1.0
    img = morphology.remove_small_objects(img, 5)
    return img
Example #13
0
    def run(self, image):
        assert image.size > 0
        hed = cv2.split(rgb2hed(image))[1]
        hed = img_as_ubyte(1.0 - hed)
        # hed = 1.0 - hed
        hed = rescale_intensity(hed)
        im = hed
        # im = img_as_ubyte(hed)
        # com.debug_im(im)
        im[im >= 115] = 255
        im[im < 115] = 0
        im = rank.enhance_contrast(im, disk(5))
        im = morph.close(im, disk(3))

        can = cv2.adaptiveBilateralFilter(im,
                                          self.bilateral_kernel,
                                          self.sigma_color)
        return can
Example #14
0
def label_from_thresh(frame, thresh, parameters):

    smooth = parameters['smooth']
    min_distance = np.int(parameters['nuc_distance'])
    image = rank.median(frame, disk(smooth))
    image = rank.enhance_contrast(image, disk(smooth))
    im_max = image.max()
    if im_max < thresh:
        return np.zeros(image.shape, dtype=np.int32)
    else:
        image = image > thresh
        distance = ndimage.distance_transform_edt(image)
        local_maxi = peak_local_max(distance,
                                    footprint=disk(min_distance),
                                    #min_distance=min_distance,
                                    indices=False, labels=image)
        markers = ndimage.label(local_maxi)[0]
        return watershed(-distance, markers, mask=image)
Example #15
0
def enhanceContrastIfRequired(imagePath, outputPath):
    warnings.filterwarnings("ignore")
    imagePath = "" + imagePath
    color = io.imread(imagePath)
    lowContrast = is_low_contrast(color, fraction_threshold=0.25)
    if (lowContrast):
        print('low contrast detected. enhancing image')
        image_to_enhance = img_as_ubyte(color)
        enhanced = enhance_contrast(image_to_enhance,
                                    determineSelem(image_to_enhance))
        p2, p98 = np.percentile(enhanced, (2, 98))
        output = rescale_intensity(enhanced, in_range=(p2, p98))

    else:
        print('contrast enhancing not needed')
        output = color

    imsave('' + outputPath, output)
    output
Example #16
0
def make_img_features(id_, train=True):
    path = 'train' if train else 'test'
    pred = cv2.imread(f'predicts/{path}/{id_}_proba.png')[..., 0]

    pred_bin = np.copy(enhance_contrast(np.copy(pred), disk(3)))
    pred_bin[pred_bin >= 128] = 255
    pred_bin[pred_bin < 128] = 0

    features_pred = [
        len(find_contours(pred, .9)),
        len(find_contours(pred_bin, .9)),
        count_contours_cv(pred),
        count_contours_cv(pred_bin),
        pred.mean(),
        pred.std(),
    ]

    features_pred = np.array(features_pred)
    return features_pred
Example #17
0
def enhance_contrast_image(image_array,
                           windows_size,
                           window_shape="square",
                           im_show=True,
                           return_img=False):
    """Enhance contrast of an image.
    This replaces each pixel by the local maximum if the pixel greyvalue is closer to the local maximum than the local minimum.
    Otherwise it is replaced by the local minimum.

    Parameters
    ----------
    image_array:numpy.array:
        input image

    windows_size:int
        the size of window

    window_shape: str
        str is element from dict:{square, disk}

    im_show : Bool
        if True show result

    return_img: Bool
        if True return img

    """
    from skimage.filters.rank import enhance_contrast

    #make kernel
    check_windows_size(windows_size)
    kernel = make_kernel(window_shape, windows_size)

    #enhance_contrast_image
    img = enhance_contrast(image_array, kernel)

    #show image
    if im_show:
        show_image(img)

    if return_img:
        return img
Example #18
0
def apply_preprocessing(img):
    # Intensity scaling
    img_intensity_scale = rescale_intensity(img, in_range="dtype")

    # Contrast enhancing
    img_enhanced_contrast = enhance_contrast(img_intensity_scale, disk(5))

    # Adaptive histogram equalizer
    img_equalized = equalize_adapthist(img_enhanced_contrast)

    # Gaussian smoothing
    img_smoothed = gaussian(img_equalized)

    # Binarization with adaptive thresholding
    thresh_local = threshold_local(img_smoothed, 125, 'mean')
    img_binarized = apply_thresh(img_smoothed, thresh_local)

    # Thinning
    img_thinned = thin(invert(img_binarized))

    return img_thinned
Example #19
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))
def otsu_local_method(img, op="disc", test=False):
    if op == "disc" or op == "cup":
        to_plot = []
        img_red = img[:, :, 0]

        img_red = skimage.util.img_as_ubyte(img_red)
        if test:
            to_plot.append(("red_chan", img_red))

        img_red = skimage.filters.gaussian(img_red, 4.2)

        if test:
            to_plot.append(("gaussian f", img_red))

        img_red = enhance_contrast(img_red, disk(3))

        if test:
            to_plot.append(("enhace_contrast", img_red))
        """ Local Otsu """
        t_loc_otsu = otsu(img_red, disk(20))
        mask = img_red >= t_loc_otsu

        if test:
            to_plot.append(("Otsu local", th.apply(img_red, mask)))

        mask = binary_opening(mask, disk(2))
        mask = binary_closing(mask, disk(4))

        if test:
            to_plot.append(("binary open-close", th.apply(img_red, mask)))
        """ Chusing brightest region """
        mask = msr.closest_prop(img_red, mask)

        if test:
            to_plot.append(("brightest region", th.apply(img_red, mask)))

        maskfinal = binary_closing(mask, disk(20))

        if test:
            to_plot.append(("binary closing", th.apply(img_red, maskfinal)))

        img_red = th.apply(img_red, maskfinal)

        props = msr.props(img_red, maskfinal)[0]

        minr, minc, maxr, maxc = props.bbox
        img_cut = img[minr:maxr, minc:maxc]

        if test:
            vi.plot_multy(to_plot, 3, 3, 'Otsu Local chain')

    if op == "cup":
        minr, minc, maxr, maxc = props.bbox
        img_green = img[minr:maxr, minc:maxc, 1]

        to_plot = []

        if test:
            to_plot.append(("green channel", img_green))

        v_mask, _ = segment_veins(img_green, test)

        img_aux = closing(img_green, disk(6))
        img_aux = dilation(img_aux, disk(6))
        img_aux2 = dilation(img_green, disk(3))

        if test:
            to_plot.append(("closed + dilated", img_aux))
            to_plot.append(("dilated", img_aux2))

        img_v_closed = th.apply(img_aux, v_mask)
        img_t_dilated = th.apply(img_aux2, v_mask == False)

        if test:
            to_plot.append(("veins part", img_v_closed))
            to_plot.append(("target part", img_t_dilated))

        img_green = img_v_closed + img_t_dilated

        if test:
            to_plot.append(("img_green", img_green))
        """ Local Otsu """
        t_loc_otsu = otsu(img_green, disk(20))
        mask = img_green >= t_loc_otsu
        mask = msr.closest_prop(img_green, mask)

        if test:
            to_plot.append(("Otsu local", th.apply(img_green, mask)))

        mask1 = mask
        mask = np.zeros(img[:, :, 1].shape)
        mask[minr:maxr, minc:maxc] = mask1

        if test:
            vi.plot_multy(to_plot, 2, 4, 'cup')

    return (mask, img_cut, props)
def sobel_watershed_method(img, op="disc", veins=False, test=False):
    if op == "disc" or op == "cup":
        to_plot = []
        img_red = img[:, :, 0]

        if test:
            to_plot.append(("Red Channel", img_red))

        img_red = skimage.util.img_as_ubyte(img_red)

        img_red = skimage.filters.gaussian(img_red, 0.1)

        if test:
            to_plot.append(("Gaussian Filter", img_red))

        img_red = enhance_contrast(img_red, disk(6))

        if test:
            to_plot.append(("Enhace Contrast", img_red))

        elevation_map = sobel(img_red)

        if test:
            to_plot.append(("gradientes", elevation_map))

        markers = np.zeros_like(img_red)

        s2 = f.target_set_mean(img_red, 8.5)

        markers[img_red < 150] = 1
        markers[img_red > s2] = 2

        seg_img = segmentation.watershed(elevation_map, markers)

        mask = (seg_img - 1) > 0

        if test:
            to_plot.append(("Sobel + WaterShed", seg_img))

        mask = binary_opening(mask, disk(2))
        mask = skimage.morphology.remove_small_objects(mask, 400)

        if test:
            to_plot.append(("Removing small objects", th.apply(img_red, mask)))

        mask = binary_closing(mask, disk(6))

        if test:
            to_plot.append(("Closing Region", th.apply(img[:, :, 0], mask)))

        mask = skimage.morphology.remove_small_objects(mask, 1700)

        if test:
            to_plot.append(
                ("Removing Big Objects", th.apply(img[:, :, 0], mask)))

        mask = binary_closing(mask, disk(6))
        mask = msr.closest_prop(img[:, :, 0], mask)

        if test:
            to_plot.append(
                ("Removing non brighter region", th.apply(img[:, :, 0], mask)))

        mask = binary_dilation(mask, disk(3))
        mask = binary_closing(mask, disk(12))

        if test:
            to_plot.append(
                ("Dilate result region", th.apply(img[:, :, 0], mask)))

        props = msr.props(img_red, mask)[0]

        minr, minc, maxr, maxc = props.bbox
        img_cut = img[minr:maxr, minc:maxc]

        if test:
            vi.plot_multy(to_plot, 3, 4, 'Sobel Watershed')

    if op == "cup":
        minr, minc, maxr, maxc = props.bbox
        img_green = img[minr:maxr, minc:maxc, 1]

        to_plot = []
        columns = 1

        if test:
            to_plot.append(("green channel", img_green))

        if not veins:
            columns = 4
            v_mask, _ = segment_veins(img_green, test)

            img_aux = closing(img_green, disk(6))
            img_aux = dilation(img_aux, disk(6))
            img_aux2 = dilation(img_green, disk(3))

            if test:
                to_plot.append(("closed + dilated", img_aux))
                to_plot.append(("dilated", img_aux2))

            img_v_closed = th.apply(img_aux, v_mask)
            img_t_dilated = th.apply(img_aux2, v_mask == False)

            if test:
                to_plot.append(("veins part", img_v_closed))
                to_plot.append(("target part", img_t_dilated))

            img_green = img_v_closed + img_t_dilated

            if test:
                to_plot.append(("without veins", img_green))

        img_green = dilation(img_green, disk(6))
        img_green = enhance_contrast(img_green, disk(10))

        elevation_map = sobel(img_green)
        markers = np.zeros_like(img_green)

        s2 = f.target_set_mean(img_green, 8.5)

        markers[img_green < 150] = 1
        markers[img_green > s2] = 2

        seg_img = segmentation.watershed(elevation_map, markers)

        mask = (seg_img - 1) > 0

        if test:
            to_plot.append(("P-tile", th.apply(img_green, mask)))

        mask1 = mask
        mask = np.zeros(img[:, :, 1].shape)
        mask[minr:maxr, minc:maxc] = mask1

        if test:
            vi.plot_multy(to_plot, 2, columns, 'cup')

    return (mask, img_cut, props)
Example #22
0
from skimage import data, color
import matplotlib.pyplot as plt
from skimage.morphology import disk
import skimage.filters.rank as sfr

original_image = color.rgb2gray(data.camera())
plt.imshow(original_image, cmap=plt.cm.gray)

filtered_images = []
filtered_images.append(sfr.autolevel(original_image, disk(5)))
filtered_images.append(sfr.bottomhat(original_image, disk(5)))
filtered_images.append(sfr.tophat(original_image, disk(5)))
filtered_images.append(sfr.enhance_contrast(original_image, disk(5)))
filtered_images.append(sfr.entropy(original_image, disk(5)))
filtered_images.append(sfr.equalize(original_image, disk(5)))
filtered_images.append(sfr.gradient(original_image, disk(5)))
filtered_images.append(sfr.maximum(original_image, disk(5)))
filtered_images.append(sfr.minimum(original_image, disk(5)))
filtered_images.append(sfr.mean(original_image, disk(5)))
filtered_images.append(sfr.median(original_image, disk(5)))
filtered_images.append(sfr.modal(original_image, disk(5)))
filtered_images.append(sfr.otsu(original_image, disk(5)))
filtered_images.append(sfr.threshold(original_image, disk(5)))
filtered_images.append(sfr.subtract_mean(original_image, disk(5)))
filtered_images.append(sfr.sum(original_image, disk(5)))

name_list = [
    'autolevel', 'bottomhat', 'tophat', 'enhance_contrast', 'entropy',
    'equalize', 'gradient', 'maximum', 'minimum', 'mean', 'median', 'modal',
    'otsu', 'threshold', 'subtract_mean', 'sum'
]
Example #23
0
plt.subplot(122)
plt.title('filted image:autolevel')
plt.imshow(auto,plt.cm.gray)
plt.show()
'''2、bottomhat 与 tophat'''
auto =rank.bottomhat(img, disk(5))  #半径为5的圆形滤波器
plt.figure('filters2',figsize=(8,8))
plt.subplot(121)
plt.title('origin image')
plt.imshow(img,plt.cm.gray)
plt.subplot(122)
plt.title('filted image:bottomhat && tophat')
plt.imshow(auto,plt.cm.gray)
plt.show()
'''3、enhance_contrast'''
auto =rank.enhance_contrast(img, disk(5))  #半径为5的圆形滤波器
plt.figure('filters3',figsize=(8,8))
plt.subplot(121)
plt.title('origin image')
plt.imshow(img,plt.cm.gray)
plt.subplot(122)
plt.title('filted image:enhance_contrast')
plt.imshow(auto,plt.cm.gray)
plt.show()
'''4、entropy'''
dst =rank.entropy(img, disk(5))  #半径为5的圆形滤波器
plt.figure('filters4',figsize=(8,8))
plt.subplot(121)
plt.title('origin image')
plt.imshow(img,plt.cm.gray)
plt.subplot(122)
 def contrast_enhancement(self, local_mtx=disk(5)):
     self.img_over = enhance_contrast(uint16(self.img),
                                      local_mtx,
                                      mask=self.img > self.img.mean())
Example #25
0
#img.show()

# edge detector from PIL ImageFilter
img_edges = img.filter(ImageFilter.FIND_EDGES)
img_edges.show()

# sobel filter from skimage.filters
array = np.array(img)
array = sobel(array)
array -= array.min()
array *= 255.0
array *= 30
array = np.clip(array, 0.0, 255.0)
array = array / array.max() - 0.5
array *= 2.0
array = enhance_contrast(array, disk(1))
array = array - array.min()
array = array / array.max() * 255.0
img_sobel = Image.fromarray(array)
img_sobel.show()

# canny filter from skimage.feature
array = np.array(img)
array = canny(array, sigma=1.2)  # sigma decides what information to delete
img_canny = Image.fromarray(array)
img_canny.show()

# canny filter after morphology dilation
for i in range(3):
    array = morphology.binary_dilation(array)
img_canny_dilated = Image.fromarray(array)
Example #26
0
 def func(frame):
     smoothed = rank.median(frame,disk(smooth_size))
     smoothed = rank.enhance_contrast(smoothed, disk(smooth_size))
     return smoothed
Example #27
0
 def apply(self, img, param=None):
     """
     see Filter.apply()
     """
     return rank.enhance_contrast(img, disk(param['size']))
def snakes(img, op="disc", test=False):

    if op == "disc":
        img_red = img[:, :, 0]
        img_red = enhance_contrast(img_red, disk(10))
        img_red = gaussian(img_red, 5)

        mask = f.hand_made(img_red, 10, 2)
        mask = binary_opening(mask, disk(7))
        mask = skimage.morphology.remove_small_objects(mask, 1700)
        mask = msr.closest_prop(img_red, mask)

        if msr.props(img_red, mask):
            props = msr.props(img_red, mask)[0]
            y0, x0 = props.centroid
            x02 = x0 - props.minor_axis_length / 4
            y_axis = x_axis = props.major_axis_length / 2

        else:
            (x_axis, y_axis) = img_red.shape
            x0 = x02 = x_axis / 2 - 1
            y0 = y_axis / 2 - 1

        s = np.linspace(0, 2 * np.pi, 400)
        r = y0 + y_axis * np.sin(s)
        c = x02 + x_axis * np.cos(s)
        init = np.array([r, c]).T

        snake = active_contour(img_red,
                               init,
                               boundary_condition='fixed',
                               alpha=0.1,
                               beta=5,
                               gamma=0.001)

    if op == "cup":
        img_red = img[:, :, 1]
        img_red = enhance_contrast(img_red, disk(4))
        img_red = gaussian(img_red, 1)

        mask = f.hand_made(img_red, 10, 2)
        mask = binary_opening(mask, disk(7))
        mask = skimage.morphology.remove_small_objects(mask, 1700)
        mask = msr.closest_prop(img_red, mask)

        if msr.props(img_red, mask):
            props = msr.props(img_red, mask)[0]
            y0, x0 = props.centroid
            x02 = x0 - props.minor_axis_length / 4
            y_axis = x_axis = props.major_axis_length / 2

        else:
            (y_axis, x_axis) = img_red.shape
            x0 = x02 = x_axis / 2
            y0 = y_axis / 2
            x_axis = x_axis / 3 - 1
            y_axis = y_axis / 2 - 10

        s = np.linspace(0, 2 * np.pi, 400)
        r = y0 + y_axis * np.sin(s)
        c = x02 + x_axis * np.cos(s)
        init = np.array([r, c]).T

        snake = active_contour(img_red,
                               init,
                               boundary_condition='fixed',
                               alpha=0.4,
                               beta=10,
                               gamma=0.001)

    fig, ax = plt.subplots(figsize=(9, 5))
    ax.imshow(img_red, cmap="gray")
    ax.plot(init[:, 1], init[:, 0], '--r', lw=3)
    ax.plot(snake[:, 1], snake[:, 0], '-b', lw=3)
    ax.set_xticks([]), ax.set_yticks([])
    ax.axis([0, img.shape[1], img.shape[0], 0])

    plt.show()
Example #29
0
from skimage.filters.rank import enhance_contrast

contr = np.empty_like(img)
for i, aslice in enumerate(img):
    contr[i] = enhance_contrast(aslice.astype(np.uint16), disk(3))
slicing(contr, 'gray')
for i in range(0,len(image_list)):
    axes_list[i].imshow(image_list[i], cmap=plt.cm.gray, vmin=0, vmax=255)
    axes_list[i].set_title(title_list[i])
    axes_list[i].axis('off')
    axes_list[i].set_adjustable('box-forced')

######################################################################
# The morphological contrast enhancement filter replaces the central pixel by
# the local maximum if the original pixel value is closest to local maximum,
# otherwise by the minimum local.

from skimage.filters.rank import enhance_contrast

noisy_image = img_as_ubyte(data.camera())

enh = enhance_contrast(noisy_image, disk(5))

fig, ax = plt.subplots(2, 2, figsize=[10, 7], sharex='row', sharey='row')
ax1, ax2, ax3, ax4 = ax.ravel()

ax1.imshow(noisy_image, cmap=plt.cm.gray)
ax1.set_title('Original')
ax1.axis('off')
ax1.set_adjustable('box-forced')

ax2.imshow(enh, cmap=plt.cm.gray)
ax2.set_title('Local morphological contrast enhancement')
ax2.axis('off')
ax2.set_adjustable('box-forced')

ax3.imshow(noisy_image[200:350, 350:450], cmap=plt.cm.gray)
def handmade_p_tile_method(img, op="disc", test=False):
    if op == "disc" or op == "cup":
        to_plot = []
        img_red = img[:, :, 0]

        if test:
            to_plot.append(("Red Channel", img_red))

        img_red = dilation(img_red, disk(3))

        if test:
            to_plot.append(("Gaussing", img_red))

        img_red = enhance_contrast(img_red, disk(10))

        if test:
            to_plot.append(("Enhace_contrast", img_red))

        mask = f.hand_made(img_red, 10, 2)

        if test:
            to_plot.append(("P-tile", th.apply(img_red, mask)))

        mask = binary_opening(mask, disk(7))
        mask = skimage.morphology.remove_small_objects(mask, 1700)

        if test:
            to_plot.append(
                ("Opening and remove small objects", th.apply(img_red, mask)))

        props = msr.props(img_red, mask)[0]

        minr, minc, maxr, maxc = props.bbox
        img_cut = img[minr:maxr, minc:maxc]

        if test:
            to_plot.append(("Binary opening", th.apply(img_red, mask)))
        if test:
            vi.plot_multy(to_plot, 2, 3, 'P-tile')

    if op == "cup":
        minr, minc, maxr, maxc = props.bbox
        img_green = img[minr:maxr, minc:maxc, 1]

        to_plot = []

        if test:
            to_plot.append(("green channel", img_green))

        v_mask, _ = segment_veins(img_green, test)

        img_aux = closing(img_green, disk(6))
        img_aux = dilation(img_aux, disk(6))
        img_aux2 = dilation(img_green, disk(3))

        if test:
            to_plot.append(("closed + dilated", img_aux))
            to_plot.append(("dilated", img_aux2))

        img_v_closed = th.apply(img_aux, v_mask)
        img_t_dilated = th.apply(img_aux2, v_mask == False)

        if test:
            to_plot.append(("veins part", img_v_closed))
            to_plot.append(("target part", img_t_dilated))

        img_green = img_v_closed + img_t_dilated

        if test:
            to_plot.append(("without veins", img_green))

        img_green = dilation(img_green, disk(6))

        img_green = enhance_contrast(img_green, disk(10))

        if test:
            to_plot.append(("dilation + contrast", img_green))

        mask = f.hand_made(img_green, 10, 2, smallest=0)

        if test:
            to_plot.append(("P-tile", th.apply(img_green, mask)))

        mask1 = mask
        mask = np.zeros(img[:, :, 1].shape)
        mask[minr:maxr, minc:maxc] = mask1

        if test:
            vi.plot_multy(to_plot, 4, 4, 'Otsu Local chain')

    return (mask, img_cut, props)