예제 #1
0
파일: tools.py 프로젝트: Trineon/lisa
def smoothing_tv(data, weight, pseudo_3D='True', multichannel=False, sliceId=2):
    if data.ndim == 3 and pseudo_3D:
        if sliceId == 2:
            for idx in range(data.shape[2]):
                temp = skifil.denoise_tv_chambolle(data[:, :, idx], weight=weight, multichannel=multichannel)
                data[:, :, idx] = (255 * temp).astype(np.uint8)
        elif sliceId == 0:
            for idx in range(data.shape[0]):
                temp = skifil.denoise_tv_chambolle(data[idx, :, :], weight=weight, multichannel=multichannel)
                data[idx, :, :] = (255 * temp).astype(np.uint8)
    else:
        data = skifil.denoise_tv_chambolle(data, weight=weight, multichannel=False)
        data = (255 * data).astype(np.uint8)
    return data
예제 #2
0
파일: Blob.py 프로젝트: theandygross/Luc
def getCenters(stack):
    '''
    Takes in a stack and finds the centers of all of the features.
    '''
    stackSum = 1.*np.sum(stack, axis=0)
    stackSum = filter.denoise_tv_chambolle(stackSum, weight=300, eps=1e-5)
    centers = detect_peaks_local_max(stackSum, radius=30)
    return centers
예제 #3
0
파일: Blob.py 프로젝트: hmhme/Luc
def getCenters(stack):
    '''
    Takes in a stack and finds the centers of all of the features.
    '''
    stackSum = 1. * np.sum(stack, axis=0)
    stackSum = filter.denoise_tv_chambolle(stackSum, weight=300, eps=1e-5)
    centers = detect_peaks_local_max(stackSum, radius=30)
    return centers
def skimage_filter_technique(image_path):

    img2 = data.imread(image_path, True)
    tv_filter = filter.denoise_tv_chambolle(img2, weight=0.1)

    cv2.imshow('Gray Scale', tv_filter)
    cv2.waitKey(Delay)

    return tv_filter
예제 #5
0
def skimage_filter_technique(image_path):

    img2 = data.imread(image_path, True)
    tv_filter = filter.denoise_tv_chambolle(img2, weight=0.1)

    cv2.imshow('Gray Scale', tv_filter)
    cv2.waitKey(DELAY_CAPTION)

    return tv_filter
예제 #6
0
def test_denoise_tv_chambolle_float_result_range():
    # lena image
    img = lena_gray
    int_lena = np.multiply(img, 255).astype(np.uint8)
    assert np.max(int_lena) > 1
    denoised_int_lena = filter.denoise_tv_chambolle(int_lena, weight=60.0)
    # test if the value range of output float data is within [0.0:1.0]
    assert denoised_int_lena.dtype == np.float
    assert np.max(denoised_int_lena) <= 1.0
    assert np.min(denoised_int_lena) >= 0.0
예제 #7
0
def test_denoise_tv_chambolle_float_result_range():
    # lena image
    img = lena_gray
    int_lena = np.multiply(img, 255).astype(np.uint8)
    assert np.max(int_lena) > 1
    denoised_int_lena = filter.denoise_tv_chambolle(int_lena, weight=60.0)
    # test if the value range of output float data is within [0.0:1.0]
    assert denoised_int_lena.dtype == np.float
    assert np.max(denoised_int_lena) <= 1.0
    assert np.min(denoised_int_lena) >= 0.0
예제 #8
0
파일: locator.py 프로젝트: sgallet/pychron
    def _denoise(self, img, weight):
        '''
            use TV-denoise to remove noise
            
            http://scipy-lectures.github.com/advanced/image_processing/
            http://en.wikipedia.org/wiki/Total_variation_denoising
        '''

        from skimage.filter import denoise_tv_chambolle

        img = denoise_tv_chambolle(img, weight=weight) * 255

        return img.astype('uint8')
예제 #9
0
    def _denoise(self, img, weight):
        '''
            use TV-denoise to remove noise
            
            http://scipy-lectures.github.com/advanced/image_processing/
            http://en.wikipedia.org/wiki/Total_variation_denoising
        '''

        from skimage.filter import denoise_tv_chambolle

        img = denoise_tv_chambolle(img, weight=weight) * 255

        return img.astype('uint8')
예제 #10
0
def select_area_for_detector(np_image):
    
    import numpy as np
    import pylab as pl
    
    from skimage.filter import threshold_otsu, sobel
    from skimage.morphology import label
    from skimage.measure import regionprops
    from skimage.filter import denoise_tv_chambolle
    
    pl.close('all')
    
    # Find regions
    
    image_filtered = denoise_tv_chambolle(np_image, weight=0.002)
    edges = sobel(image_filtered)
    
    nbins = 50
    threshold = threshold_otsu(edges, nbins)
    edges_bin = edges >= threshold
    
    label_image = label(edges_bin)
    
    areas = []
    areas_full = []
    bord = []
    
    # Extract information from the regions
    
    for region in regionprops(label_image, ['Area', 'BoundingBox', 'Label']):
        
        # Skip wrong regions
        index = np.where(label_image==region['Label'])
        if index[0].size==0 & index[1].size==0:
            continue
        
        # Skip small regions
        if region['Area'] < 100:
            continue
        
        # Extract the coordinates of regions
        minr, minc, maxr, maxc = region['BoundingBox']
        margin = len(np_image) / 100
        bord.append((minr-margin, maxr+margin, minc-margin, maxc+margin))
        areas.append(edges_bin[minr-margin:maxr+margin,minc-margin:maxc+margin].copy())
        areas_full.append(np_image[minr-margin:maxr+margin,minc-margin:maxc+margin].copy())
    
    return areas, areas_full, bord
예제 #11
0
def test_denoise_tv_chambolle_3d():
    """Apply the TV denoising algorithm on a 3D image representing a sphere."""
    x, y, z = np.ogrid[0:40, 0:40, 0:40]
    mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2
    mask = 100 * mask.astype(np.float)
    mask += 60
    mask += 20 * np.random.random(mask.shape)
    mask[mask < 0] = 0
    mask[mask > 255] = 255
    res = filter.denoise_tv_chambolle(mask.astype(np.uint8), weight=100)
    assert res.dtype == np.float
    assert res.std() * 255 < mask.std()

    # test wrong number of dimensions
    assert_raises(ValueError, filter.denoise_tv_chambolle,
                  np.random.random((8, 8, 8, 8)))
예제 #12
0
def test_denoise_tv_chambolle_3d():
    """Apply the TV denoising algorithm on a 3D image representing a sphere."""
    x, y, z = np.ogrid[0:40, 0:40, 0:40]
    mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2
    mask = 100 * mask.astype(np.float)
    mask += 60
    mask += 20 * np.random.random(mask.shape)
    mask[mask < 0] = 0
    mask[mask > 255] = 255
    res = filter.denoise_tv_chambolle(mask.astype(np.uint8), weight=100)
    assert res.dtype == np.float
    assert res.std() * 255 < mask.std()

    # test wrong number of dimensions
    assert_raises(ValueError, filter.denoise_tv_chambolle,
                  np.random.random((8, 8, 8, 8)))
예제 #13
0
def test_denoise_tv_chambolle_2d():
    # lena image
    img = lena_gray
    # add noise to lena
    img += 0.5 * img.std() * np.random.random(img.shape)
    # clip noise so that it does not exceed allowed range for float images.
    img = np.clip(img, 0, 1)
    # denoise
    denoised_lena = filter.denoise_tv_chambolle(img, weight=60.0)
    # which dtype?
    assert denoised_lena.dtype in [np.float, np.float32, np.float64]
    from scipy import ndimage
    grad = ndimage.morphological_gradient(img, size=((3, 3)))
    grad_denoised = ndimage.morphological_gradient(denoised_lena,
                                                   size=((3, 3)))
    # test if the total variation has decreased
    assert grad_denoised.dtype == np.float
    assert (np.sqrt((grad_denoised**2).sum()) < np.sqrt((grad**2).sum()) / 2)
예제 #14
0
def test_denoise_tv_chambolle_2d():
    # lena image
    img = lena_gray
    # add noise to lena
    img += 0.5 * img.std() * np.random.random(img.shape)
    # clip noise so that it does not exceed allowed range for float images.
    img = np.clip(img, 0, 1)
    # denoise
    denoised_lena = filter.denoise_tv_chambolle(img, weight=60.0)
    # which dtype?
    assert denoised_lena.dtype in [np.float, np.float32, np.float64]
    from scipy import ndimage
    grad = ndimage.morphological_gradient(img, size=((3, 3)))
    grad_denoised = ndimage.morphological_gradient(
        denoised_lena, size=((3, 3)))
    # test if the total variation has decreased
    assert grad_denoised.dtype == np.float
    assert (np.sqrt((grad_denoised**2).sum())
            < np.sqrt((grad**2).sum()) / 2)
def skimage_filter_technique(image_path):
    img2 = data.imread(image_path, True)
    tv_filter = filter.denoise_tv_chambolle(img2, weight=0.1)
    return tv_filter
예제 #16
0

lena = img_as_float(data.lena())
lena = lena[220:300, 220:320]

noisy = lena + 0.6 * lena.std() * np.random.random(lena.shape)
noisy = np.clip(noisy, 0, 1)

fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(8, 5))

plt.gray()

ax[0, 0].imshow(noisy)
ax[0, 0].axis('off')
ax[0, 0].set_title('noisy')
ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
ax[0, 1].axis('off')
ax[0, 1].set_title('TV')
ax[0, 2].imshow(denoise_bilateral(noisy, sigma_range=0.05, sigma_spatial=15))
ax[0, 2].axis('off')
ax[0, 2].set_title('Bilateral')

ax[1, 0].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True))
ax[1, 0].axis('off')
ax[1, 0].set_title('(more) TV')
ax[1, 1].imshow(denoise_bilateral(noisy, sigma_range=0.1, sigma_spatial=15))
ax[1, 1].axis('off')
ax[1, 1].set_title('(more) Bilateral')
ax[1, 2].imshow(lena)
ax[1, 2].axis('off')
ax[1, 2].set_title('original')
예제 #17
0
===========================

This example demoes Total-Variation (TV) denoising on Lena.
"""

import numpy as np
import scipy
import matplotlib.pyplot as plt
from skimage.filter import denoise_tv_chambolle

l = scipy.misc.lena()
l = l[230:290, 220:320]

noisy = l + 0.4 * l.std() * np.random.random(l.shape)

tv_denoised = denoise_tv_chambolle(noisy, weight=10)

plt.figure(figsize=(12, 2.8))

plt.subplot(131)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('noisy', fontsize=20)
plt.subplot(132)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('TV denoising', fontsize=20)

tv_denoised = denoise_tv_chambolle(noisy, weight=50)
plt.subplot(133)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
    input_filename = args[5]
    results_path = args[6]
     
    # load image
    R = int(r*1.1)
    area = np.zeros((2*R + 1, 2*R + 1, 2*R + 1), dtype=np.float32)
     
    for i in range(z - R, z + R + 1):
         
        input_file = input_filename % i
        print("Loading image %s" % input_file)
         
        img = io.imread(input_file)[x - R:x + R + 1, y - R:y + R + 1]
         
        # Denoise and increase contrat of every image
        image_filtered = denoise_tv_chambolle(img, weight=0.005)
     
        float_img = rescale_intensity(image_filtered,
                                      in_range=(image_filtered.min(),
                                                image_filtered.max()),
                                      out_range='float32')
         
        p2, p98 = np.percentile(float_img, (2, 99))
        equalize = exposure.rescale_intensity(float_img,
                                              in_range=(p2, p98),
                                              out_range='float32')
         
        # Stack the normalised and de-noised spheres
        binary = (equalize > threshold_otsu(equalize)) * 1
#         filled = ndimage.morphology.binary_closing(binary, iterations=5)
        area[:, :, i - (z - R)] = binary
예제 #19
0
def test_denoise_tv_chambolle_multichannel():
    denoised0 = filter.denoise_tv_chambolle(lena[..., 0], weight=60.0)
    denoised = filter.denoise_tv_chambolle(lena,
                                           weight=60.0,
                                           multichannel=True)
    assert_equal(denoised[..., 0], denoised0)
예제 #20
0
import os, sys
from skimage import io
from skimage import filter

kidney_image = io.imread("color_img.bmp")
print kidney_image.shape

# estimate the noise in the image


# io.imshow (kidney_image) #have to set display to make this work


# do a test denosing using a total variation filter
kidney_image_denoised_tv = filter.denoise_tv_chambolle(kidney_image, weight=0.1)
io.imsave("kidney_image_denoised_tv.bmp", test_image_denoised_tv)

# do a test denosing using a lateral filter to preserve edges
kidney_image_denoised_lateral = filter.denoise_bilateral(kidney_image, sigma_range=0.05, sigma_spatial=15)

# save the denoised image
io.imsave("kidney_image_denoised_lateral.bmp", test_image_denoised_lateral)
def select_area_for_detector(np_image):
    float_img = rescale_intensity(np_image.copy(),
                                  in_range=(np_image.min(), np_image.max()),
                                  out_range='float')

    p2, p98 = np.percentile(float_img, (2, 99))
    for_show = exposure.rescale_intensity(float_img,
                                          in_range=(p2, p98),
                                          out_range='float')

    pl.close('all')
    image_filtered = denoise_tv_chambolle(np_image, weight=0.005)
    #     image_filtered = denoise_tv_bregman(np_image, weight=50)
    #     image_filtered = gaussian_filter(np_image, 3)
    float_img = rescale_intensity(image_filtered.copy(),
                                  in_range=(image_filtered.min(),
                                            image_filtered.max()),
                                  out_range='float')

    p2, p98 = np.percentile(float_img, (2, 99))
    normalize = exposure.rescale_intensity(float_img,
                                           in_range=(p2, p98),
                                           out_range='float')

    binary = normalize > threshold_otsu(normalize)
    #     binary = image_filtered.copy()
    #     mask1 = 18 > image_filtered
    #     mask2 = 47 < image_filtered
    #
    #     binary[mask1] = 0
    #
    #     binary[mask2] = 0
    #
    #     binary[binary > 0] = 1

    distance = ndimage.distance_transform_edt(binary)
    local_maxi = peak_local_max(distance, indices=False, labels=binary)

    markers = ndimage.label(local_maxi)[0]

    labeled = watershed(-distance, markers, mask=binary)
    pl.imshow(np_image)
    pl.gray()
    pl.axis('off')
    pl.show()
    pl.imshow(image_filtered)
    pl.gray()
    pl.axis('off')
    pl.show()
    #     pl.subplot(1, 3, 1)
    #     pl.title("Filtered Image")
    #     pl.subplot(1, 3, 2)
    #     pl.title("Binary Image")
    pl.imshow(normalize)
    pl.axis('off')
    pl.show()
    pl.imshow(binary)
    pl.axis('off')
    pl.show()
    #     pl.subplot(1, 3, 3)
    #     pl.title("Watershed segmentation")
    pl.imshow(labeled)
    pl.axis('off')
    pl.show()
    #     pl.close('all')

    areas = []
    centroids_fit = []
    radius_fit = []
    edge_coords = []
    bords = []

    # Extract information from the regions

    for region in measure.regionprops(labeled,
                                      ['Area', 'BoundingBox', 'Label']):

        # Skip wrong regions
        index = np.where(labeled == region['Label'])
        if index[0].size == 0 & index[1].size == 0:
            continue

        # Skip small regions
        if region['Area'] < 100:
            continue

        # Extract the coordinates of regions
        minr, minc, maxr, maxc = region.bbox
        bx = [minc - 10, maxc + 10, maxc + 10, minc - 10, minc - 10]
        by = [minr - 10, minr - 10, maxr + 10, maxr + 10, minr - 10]
        pl.plot(bx, by, '-b', linewidth=2.5)
        pl.axis('off')
        margin = 10

        crop = normalize[minr - margin:maxr + margin,
                         minc - margin:maxc + margin].copy()
        binary = crop > threshold_otsu(crop)
        crop = sobel(binary)

        coords = np.column_stack(np.nonzero(crop))
        X = np.array(coords[:, 0]) + minr - margin
        Y = np.array(coords[:, 1]) + minc - margin

        try:
            XC, YC, RAD, RESID = leastsq_circle(X, Y)
            if region.area * 1.3 > np.pi * (RAD)**2:

                centroids_fit.append((round(XC, 4), round(YC, 4)))
                radius_fit.append(round(RAD, 2))
                #                 edge_coords.append((X, Y))
                bords.append((minr - margin, minc - margin, maxr + margin,
                              maxc + margin))
                areas.append(crop)
        except:
            continue

    pl.imshow(np_image)
    pl.gray()
    pl.show()
    return [centroids_fit, radius_fit, bords, areas, np_image]
def skimage_filter_technique(image_path):
    img2 = data.imread(image_path, True)
    tv_filter = filter.denoise_tv_chambolle(img2, weight=0.1)
    return tv_filter
def select_area_for_detector(np_image):
    """
    Takes image as an input and processes it:
    1. TV DENOISING FILTER
    2. RESCALE THE INTENSITY TO FLOAT (SOME FN'S NEED IT)
    3. ENCHANCE CONTRAST USING PERCENTILES 2 TO 99
    4. OTSU THRESHOLD
    5. EUCLIDEAN DISTANCE MAP
    6. GET MAXIMA FROM THE EDM - FOR MARKERS
    7. APPLY WATERSHED ALGORITHM
    
    THEN EXTRACT INFORMATION FROM THE SEGMENTED OBJECTS.
    FOR EVERY CROPPED OBJECT USE LEAST SQUARES, TO
    FIND A RADIUS ESTIMATE FOR THE HOUGH (FASTER) AND USE
    THE APPROXIMATE AREA FOR OUTLIER ELIMINATION.
    
    
    """
    pl.close('all')
    
    image_filtered = denoise_tv_chambolle(np_image, weight=0.005)
    
    float_img = rescale_intensity(image_filtered,
                                  in_range=(image_filtered.min(),
                                            image_filtered.max()),
                                  out_range='float')
    
    p2, p98 = np.percentile(float_img, (2, 99))
    equalize = exposure.rescale_intensity(float_img,
                                          in_range=(p2, p98),
                                          out_range='float')
    
    binary = equalize > threshold_otsu(equalize)
    
    distance = ndimage.distance_transform_edt(binary)
    local_maxi = peak_local_max(distance,
                                indices=False, labels=binary)
     
    markers = ndimage.label(local_maxi)[0]
     
    labeled = watershed(-distance, markers, mask=binary)
    
    areas = []
    radius_fit = []
    bords = []
    
    # Extract information from the regions
    for region in measure.regionprops(labeled, ['Area', 'BoundingBox']):
        
        # Extract the coordinates of regions
        # Margin used to go beyond the region if it
        # might be too tight on the object
        minr, minc, maxr, maxc = region.bbox
        margin = 10
        
        # Crop out the Watershed segments and obtain circle edges
        crop = equalize[minr-margin:maxr+margin,minc-margin:maxc+margin].copy()
        binary = crop > threshold_otsu(crop)
        crop = sobel(binary)
        
        # Get the coordinates of the circle edges
        coords = np.column_stack(np.nonzero(crop))
        X = np.array(coords[:, 0]) + minr - margin 
        Y = np.array(coords[:, 1]) + minc - margin

        # Fit a circle and compare measured circle area with
        # area from the amount of pixels to remove trash
        try:
            XC, YC, RAD, RESID = leastsq_circle(X, Y)
            if region.area * 1.3 > np.pi * RAD**2:

                radius_fit.append(round(RAD, 2))
                bords.append((minr - margin, minc - margin,
                              maxr + margin, maxc + margin))
                areas.append(crop)
        except:
            continue
    
    return [radius_fit, bords, areas, equalize]
예제 #24
0
def select_area_for_detector(np_image, min_t, max_t):

    pl.close('all')
    image_filtered = denoise_tv_chambolle(np_image, weight=0.005)
    float_img = rescale_intensity(image_filtered,
                                  in_range=(image_filtered.min(),
                                            image_filtered.max()),
                                  out_range='float')

    p2, p98 = np.percentile(float_img, (2, 99))
    normalize = exposure.rescale_intensity(float_img,
                                           in_range=(p2, p98),
                                           out_range='float')

    binary = normalize > threshold_otsu(normalize)
    #     image_filtered = denoise_tv_chambolle(np_image, weight=0.005)
    #     binary = image_filtered.copy()
    #     mask1 = max_t < image_filtered
    #     mask2 = min_t > image_filtered
    #
    #     binary[mask1] = 0
    #
    #     binary[mask2] = 0
    #
    #     binary[binary > 0] = 1

    distance = ndimage.distance_transform_edt(binary)
    local_maxi = peak_local_max(distance, indices=False, labels=binary)

    markers = ndimage.label(local_maxi)[0]

    labeled = watershed(-distance, markers, mask=binary)

    #     pl.subplot(2, 3, 2)
    #     pl.title("equalize")
    #     pl.imshow(equalize)
    #     pl.gray()
    #     pl.subplot(2, 3, 1)
    #     pl.title("np_image")
    #     pl.imshow(np_image)
    #     pl.subplot(2, 3, 4)
    #     pl.title("binary")
    #     pl.imshow(binary)
    #     pl.subplot(2, 3, 5)
    #     pl.title("distance")
    #     pl.imshow(distance)
    #     pl.subplot(2, 3, 6)
    #     pl.title("label")
    #     pl.imshow(labeled)
    #     pl.show()
    #     pl.close('all')

    areas = []
    centroids_fit = []
    radius_fit = []
    edge_coords = []
    bords = []

    # Extract information from the regions

    for region in measure.regionprops(labeled,
                                      ['Area', 'BoundingBox', 'Label']):

        # Skip wrong regions
        index = np.where(labeled == region['Label'])
        if index[0].size == 0 & index[1].size == 0:
            continue

        # Skip small regions
        if region['Area'] < 100:
            continue

        # Extract the coordinates of regions
        minr, minc, maxr, maxc = region.bbox
        margin = 10

        crop = normalize[minr - margin:maxr + margin,
                         minc - margin:maxc + margin].copy()

        #         binary = crop.copy()
        #
        #         mask1 = max_t < binary
        #         mask2 = min_t > binary
        #         binary[mask1] = 0
        #         binary[mask2] = 0
        #         binary[binary > 0] = 1
        binary = crop > threshold_otsu(crop)
        crop = sobel(binary)

        coords = np.column_stack(np.nonzero(crop))
        X = np.array(coords[:, 0]) + minr - margin
        Y = np.array(coords[:, 1]) + minc - margin

        try:
            XC, YC, RAD, RESID = leastsq_circle(X, Y)
            if region.area * 1.3 > np.pi * RAD**2:

                centroids_fit.append((round(XC, 4), round(YC, 4)))
                radius_fit.append(round(RAD, 2))
                bords.append((minr - margin, minc - margin, maxr + margin,
                              maxc + margin))
                areas.append(crop)
        except:
            continue

    return [centroids_fit, radius_fit, bords, areas, normalize]
예제 #25
0
def select_area_for_detector(np_image):
    """
    Takes image as an input and processes it:
    1. TV DENOISING FILTER
    2. RESCALE THE INTENSITY TO FLOAT (SOME FN'S NEED IT)
    3. ENCHANCE CONTRAST USING PERCENTILES 2 TO 99
    4. OTSU THRESHOLD
    5. EUCLIDEAN DISTANCE MAP
    6. GET MAXIMA FROM THE EDM - FOR MARKERS
    7. APPLY WATERSHED ALGORITHM
    
    THEN EXTRACT INFORMATION FROM THE SEGMENTED OBJECTS.
    FOR EVERY CROPPED OBJECT USE LEAST SQUARES, TO
    FIND A RADIUS ESTIMATE FOR THE HOUGH (FASTER) AND USE
    THE APPROXIMATE AREA FOR OUTLIER ELIMINATION.
    
    
    """
    pl.close('all')

    image_filtered = denoise_tv_chambolle(np_image, weight=0.005)

    float_img = rescale_intensity(image_filtered,
                                  in_range=(image_filtered.min(),
                                            image_filtered.max()),
                                  out_range='float')

    p2, p98 = np.percentile(float_img, (2, 99))
    equalize = exposure.rescale_intensity(float_img,
                                          in_range=(p2, p98),
                                          out_range='float')

    binary = equalize > threshold_otsu(equalize)

    distance = ndimage.distance_transform_edt(binary)
    local_maxi = peak_local_max(distance, indices=False, labels=binary)

    markers = ndimage.label(local_maxi)[0]

    labeled = watershed(-distance, markers, mask=binary)

    areas = []
    radius_fit = []
    bords = []

    # Extract information from the regions
    for region in measure.regionprops(labeled, ['Area', 'BoundingBox']):

        # Extract the coordinates of regions
        # Margin used to go beyond the region if it
        # might be too tight on the object
        minr, minc, maxr, maxc = region.bbox
        margin = 10

        # Crop out the Watershed segments and obtain circle edges
        crop = equalize[minr - margin:maxr + margin,
                        minc - margin:maxc + margin].copy()
        binary = crop > threshold_otsu(crop)
        crop = sobel(binary)

        # Get the coordinates of the circle edges
        coords = np.column_stack(np.nonzero(crop))
        X = np.array(coords[:, 0]) + minr - margin
        Y = np.array(coords[:, 1]) + minc - margin

        # Fit a circle and compare measured circle area with
        # area from the amount of pixels to remove trash
        try:
            XC, YC, RAD, RESID = leastsq_circle(X, Y)
            if region.area * 1.3 > np.pi * RAD**2:

                radius_fit.append(round(RAD, 2))
                bords.append((minr - margin, minc - margin, maxr + margin,
                              maxc + margin))
                areas.append(crop)
        except:
            continue

    return [radius_fit, bords, areas, equalize]
y_train=[]
x_test=[]
y_verify=[]
for classNum in class_set:
    path='./Bmp/Sample0%.2d/*' % classNum
    class_files=glob.glob(path)
    file_num=len(class_files)
    all_file=range(file_num)
    train_file=random.sample(all_file,train_size)
    test_file=list(set(all_file)-set(train_file))
#    train_num=int(file_num*split_ratio)
#    test_num=file_num-train_num
    for i in train_file:
        img=imread(class_files[i],as_grey=True)
        img_resize=resize(img,[20,20])
        img_denoise = filter.denoise_tv_chambolle(img_resize, weight=0.01)
        thresh=threshold_otsu(img_denoise)
#        img_otsu=closing(img_denoise > thresh, square(2))
        img_otsu=img_denoise>thresh
        img_feature,img_hog=hog(img_denoise, orientations=8,
                pixels_per_cell=(5, 5),
                cells_per_block=(1, 1), visualise=True)
        x_train.append(img_feature)
#        x_train.append(np.reshape(img_otsu,[1,400])[0])
        if classNum==24:
            y_train.append(0)
        elif classNum==50:
            y_train.append(0)
        else:
            y_train.append(classNum)
        
This example demoes Total-Variation (TV) denoising on a Racoon face.
"""

import numpy as np
import scipy
import scipy.misc
import matplotlib.pyplot as plt
from skimage.filter import denoise_tv_chambolle

f = scipy.misc.face(gray=True)
f = f[230:290, 220:320]

noisy = f + 0.4*f.std()*np.random.random(f.shape)

tv_denoised = denoise_tv_chambolle(noisy, weight=10)


plt.figure(figsize=(12, 2.8))

plt.subplot(131)
plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('noisy', fontsize=20)
plt.subplot(132)
plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220)
plt.axis('off')
plt.title('TV denoising', fontsize=20)

tv_denoised = denoise_tv_chambolle(noisy, weight=50)
plt.subplot(133)
예제 #28
0
def test_denoise_tv_chambolle_multichannel():
    denoised0 = filter.denoise_tv_chambolle(lena[..., 0], weight=60.0)
    denoised = filter.denoise_tv_chambolle(lena, weight=60.0, multichannel=True)
    assert_equal(denoised[..., 0], denoised0)
예제 #29
0
"""
This example compares several denoising filters available in scikit-image:
a Gaussian filter, a median filter, and total variation denoising.
"""

import matplotlib.pyplot as plt
from skimage import data
from skimage import filter
from scipy import ndimage

coins = data.coins()
gaussian_filter_coins = ndimage.gaussian_filter(coins, sigma=2)
med_filter_coins = filter.median_filter(coins)
tv_filter_coins = filter.denoise_tv_chambolle(coins, weight=0.1)

plt.figure(figsize=(16, 4))
plt.subplot(141)
plt.imshow(coins[10:80, 300:370], cmap='gray', interpolation='nearest')
plt.axis('off')
plt.title('Image')
plt.subplot(142)
plt.imshow(gaussian_filter_coins[10:80, 300:370], cmap='gray',
           interpolation='nearest')
plt.axis('off')
plt.title('Gaussian filter')
plt.subplot(143)
plt.imshow(med_filter_coins[10:80, 300:370], cmap='gray',
           interpolation='nearest')
plt.axis('off')
plt.title('Median filter')
plt.subplot(144)
예제 #30
0
def readData(data_set, kernel):
    #    print( "{0},{1}",(data_set,kernel))
    print data_set, kernel

    class_set1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    class_set2 = range(11, 36)
    class_set3 = range(36, 62)
    class_set4 = range(1, 62)
    if data_set == 1:
        class_set = class_set1
    elif data_set == 2:
        class_set = class_set2
    elif data_set == 3:
        class_set = class_set3
    elif data_set == 4:
        class_set = class_set4
    elif data_set == 5:
        class_set = [7, 7]
    else:
        data_set = 1

    split_ratio = 0.5
    x_train = []
    y_train = []
    x_test = []
    y_verify = []
    for classNum in class_set:
        path = "./Bmp/Sample0%.2d/*" % classNum
        class_files = glob.glob(path)
        file_num = len(class_files)
        train_num = int(file_num * split_ratio)
        test_num = file_num - train_num
        for i in range(train_num):
            img = imread(class_files[i], as_grey=True)
            img_resize = resize(img, [20, 20])
            img_denoise = filter.denoise_tv_chambolle(img_resize, weight=0.01)
            thresh = threshold_otsu(img_denoise)
            #        img_otsu=closing(img_denoise > thresh, square(2))
            img_otsu = img_denoise > thresh
            img_feature, img_hog = hog(
                img_denoise, orientations=8, pixels_per_cell=(5, 5), cells_per_block=(1, 1), visualise=True
            )
            x_train.append(img_feature)
            #        x_train.append(np.reshape(img_otsu,[1,400])[0])
            y_train.append(classNum)

        for i in range(train_num, file_num, 1):
            img = imread(class_files[i], as_grey=True)
            img_resize = resize(img, [20, 20])
            img_denoise = filter.denoise_tv_chambolle(img_resize, weight=0.01)
            thresh = threshold_otsu(img_denoise)
            #        img_otsu=closing(img_denoise > thresh, square(2))
            img_otsu = img_denoise > thresh
            img_feature, img_hog = hog(
                img_denoise, orientations=8, pixels_per_cell=(5, 5), cells_per_block=(1, 1), visualise=True
            )
            x_test.append(img_feature)
            #        x_test.append(np.reshape(img_otsu,[1,400])[0])
            y_verify.append(classNum)

        print "class %.2d done" % classNum

        #        print class_files[i]
        img = imread(class_files[8], as_grey=True)
        plt.subplot(2, 3, 2)
        plt.imshow(img, cmap="Greys")
        plt.title("greyscale")

        plt.subplot(2, 3, 1)
        plt.imshow(img)
        plt.title("original")

        img_resize = resize(img, [20, 20])
        plt.subplot(2, 3, 3)
        plt.imshow(img_resize, cmap="Greys")
        plt.title("resized")

        img_denoise = filter.denoise_tv_chambolle(img_resize, weight=0.01)
        plt.subplot(2, 3, 4)
        plt.imshow(img_denoise, cmap="Greys")
        plt.title("denoised")

        thresh = threshold_otsu(img_denoise)
        #    img_otsu=closing(img_denoise > thresh, square(2))
        img_otsu = img_denoise > thresh
        plt.subplot(2, 3, 5)
        plt.imshow(img_otsu, cmap="Greys")
        plt.title("highContrast")

        img_feature, img_hog = hog(
            img_denoise, orientations=8, pixels_per_cell=(5, 5), cells_per_block=(1, 1), visualise=True
        )
        plt.subplot(2, 3, 6)
        plt.imshow(img_hog, cmap="Greys")
        plt.title("HOG")

    #    print train_num,test_num,file_num

    #    clf = svm.SVC(kernel='sigmoid',gamma=0.01, C=100)
    clf = svm.SVC(kernel="poly", degree=2)
    # clf = svm.SVC(kernel='rbf',gamma=0.3)
    # clf = svm.SVC(kernel='linear')
    # clf=svm.LinearSVC(C=1)
    if kernel == "sig":
        clf = svm.SVC(kernel="sigmoid", gamma=0.01, C=100, coef0=0)
    elif kernel == "poly":
        clf = svm.SVC(kernel="poly", gamma=0.01, degree=2, coef0=1)
    elif kernel == "rbf":
        clf = svm.SVC(kernel="rbf", gamma=0.35, C=1000)
    elif kernel == "linear":
        clf = svm.SVC(kernel="linear")
    else:
        clf = svm.SVC(kernel="sigmoid", gamma=0.01, coef0=0)

    clf.fit(x_train, y_train)
    joblib.dump(clf, "svmClassifier.pkl")
    #    clf = joblib.load('svmClassifier.pkl')
    y_test = clf.predict(x_test)
    y_diff = y_test - y_verify
    y_nonzero = np.count_nonzero(y_diff)
    accuracy = 1.0 - float(y_nonzero) / len(y_verify)
    return accuracy
예제 #31
0

lena = img_as_float(data.lena())
lena = lena[220:300, 220:320]

noisy = lena + 0.6 * lena.std() * np.random.random(lena.shape)
noisy = np.clip(noisy, 0, 1)

fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(8, 5))

plt.gray()

ax[0, 0].imshow(noisy)
ax[0, 0].axis('off')
ax[0, 0].set_title('noisy')
ax[0, 1].imshow(denoise_tv_chambolle(noisy, weight=0.1, multichannel=True))
ax[0, 1].axis('off')
ax[0, 1].set_title('TV')
ax[0, 2].imshow(denoise_bilateral(noisy, sigma_range=0.05, sigma_spatial=15))
ax[0, 2].axis('off')
ax[0, 2].set_title('Bilateral')

ax[1, 0].imshow(denoise_tv_chambolle(noisy, weight=0.2, multichannel=True))
ax[1, 0].axis('off')
ax[1, 0].set_title('(more) TV')
ax[1, 1].imshow(denoise_bilateral(noisy, sigma_range=0.1, sigma_spatial=15))
ax[1, 1].axis('off')
ax[1, 1].set_title('(more) Bilateral')
ax[1, 2].imshow(lena)
ax[1, 2].axis('off')
ax[1, 2].set_title('original')
    input_filename = args[5]
    results_path = args[6]

    # load image
    R = int(r * 1.1)
    area = np.zeros((2 * R + 1, 2 * R + 1, 2 * R + 1), dtype=np.float32)

    for i in range(z - R, z + R + 1):

        input_file = input_filename % i
        print("Loading image %s" % input_file)

        img = io.imread(input_file)[x - R:x + R + 1, y - R:y + R + 1]

        # Denoise and increase contrat of every image
        image_filtered = denoise_tv_chambolle(img, weight=0.005)

        float_img = rescale_intensity(image_filtered,
                                      in_range=(image_filtered.min(),
                                                image_filtered.max()),
                                      out_range='float32')

        p2, p98 = np.percentile(float_img, (2, 99))
        equalize = exposure.rescale_intensity(float_img,
                                              in_range=(p2, p98),
                                              out_range='float32')

        # Stack the normalised and de-noised spheres
        binary = (equalize > threshold_otsu(equalize)) * 1
        #         filled = ndimage.morphology.binary_closing(binary, iterations=5)
        area[:, :, i - (z - R)] = binary