コード例 #1
0
ファイル: utils_image.py プロジェクト: codeaudit/pymooney
def threshold_img(img, method='global_otsu', radius=50):
    """ Given a gray scale image return a thresholded binary image using Otsu's thresholding method.
    img: A gray scale numpy array.
    method: 
      - 'global_otsu' computes a global threshold  value for the whole image and uses this to binarize the
      input image. (default)
      - 'local_otsu' computes a local threshols value for each pixel (threshold is computed within a neighborhood of a radius). 

    radius: The 2D neighborhood to compute local thresholds in local_otsu method

    Returns:
    
    img_binary: A binary image (same size as input img).
    threshold: Threshold value used to binarize the image.
    
    """
    if len(img.shape) > 2:
        img = rgb2gray(img)

    if method == 'global_otsu':
        threshold = threshold_otsu(img)
        img_binary = img >= threshold

    elif method == 'local_otsu':
        selem = disk(radius)
        threshold = rank.otsu(img, selem)
        img_binary = img >= threshold

    return img_binary, threshold
コード例 #2
0
ファイル: test_rank.py プロジェクト: acfyfe/scikit-image
def test_otsu():
    # test the local Otsu segmentation on a synthetic image
    # (left to right ramp * sinus)

    test = np.tile([128, 145, 103, 127, 165, 83, 127, 185, 63, 127, 205, 43,
                    127, 225, 23, 127],
                   (16, 1))
    test = test.astype(np.uint8)
    res = np.tile([1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1], (16, 1))
    selem = np.ones((6, 6), dtype=np.uint8)
    th = 1 * (test >= rank.otsu(test, selem))
    assert_array_equal(th, res)
コード例 #3
0
ファイル: test_rank.py プロジェクト: stbnps/scikit-image
def test_otsu():
    # test the local Otsu segmentation on a synthetic image
    # (left to right ramp * sinus)

    test = np.tile([128, 145, 103, 127, 165, 83, 127, 185, 63, 127, 205, 43,
                    127, 225, 23, 127],
                   (16, 1))
    test = test.astype(np.uint8)
    res = np.tile([1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1], (16, 1))
    selem = np.ones((6, 6), dtype=np.uint8)
    th = 1 * (test >= rank.otsu(test, selem))
    assert_array_equal(th, res)
コード例 #4
0
ファイル: improc.py プロジェクト: deercoder/ndsb2015
def gray_to_bw(image, method='mean', locality_radius=15):
    image = image.copy()
    # Create the thresholded image to eliminate some of the background
    # todo: consider the use of Otsu's method
    im_thresh = None
    if method == 'mean':
        im_thresh = np.where(image > np.mean(image), 0., 1.0)
    elif method == 'global_otsu':
        threshold_global_otsu = threshold_otsu(image)
        im_thresh = image >= threshold_global_otsu
    elif method == 'local_otsu':
        locality_radius = 15
        strel = morphology.disk(locality_radius)
        local_otsu = rank.otsu(image, strel)
        im_thresh = image >= local_otsu
    else:
        print 'Invalid threshold method'

    return im_thresh
コード例 #5
0
ファイル: improc.py プロジェクト: deercoder/ndsb2015
def gray_to_bw(image, method='mean', locality_radius=15):
    image = image.copy()
    # Create the thresholded image to eliminate some of the background
    # todo: consider the use of Otsu's method
    im_thresh = None
    if method == 'mean':
        im_thresh = np.where(image > np.mean(image), 0., 1.0)
    elif method == 'global_otsu':
        threshold_global_otsu = threshold_otsu(image)
        im_thresh = image >= threshold_global_otsu
    elif method == 'local_otsu':
        locality_radius = 15
        strel = morphology.disk(locality_radius)
        local_otsu = rank.otsu(image, strel)
        im_thresh = image >= local_otsu
    else:
        print 'Invalid threshold method'

    return im_thresh
コード例 #6
0
    for global Otsu thresholding: `skimage.filter.threshold_otsu`.

.. [4] http://en.wikipedia.org/wiki/Otsu's_method

"""

from skimage.filter.rank import otsu
from skimage.filter import threshold_otsu

p8 = data.page()

radius = 10
selem = disk(radius)

# t_loc_otsu is an image
t_loc_otsu = otsu(p8, selem)
loc_otsu = p8 >= t_loc_otsu

# t_glob_otsu is a scalar
t_glob_otsu = threshold_otsu(p8)
glob_otsu = p8 >= t_glob_otsu

plt.figure()
plt.subplot(2, 2, 1)
plt.imshow(p8, cmap=plt.cm.gray)
plt.xlabel('original')
plt.colorbar()
plt.subplot(2, 2, 2)
plt.imshow(t_loc_otsu, cmap=plt.cm.gray)
plt.xlabel('local Otsu ($radius=%d$)' % radius)
plt.colorbar()
コード例 #7
0
"""
import matplotlib.pyplot as plt

from skimage import data
from skimage.morphology.selem import disk
import skimage.filter.rank as rank
from skimage.filter import threshold_otsu


p8 = data.page()

radius = 10
selem = disk(radius)

loc_otsu = rank.otsu(p8, selem)
t_glob_otsu = threshold_otsu(p8)
glob_otsu = p8 >= t_glob_otsu


plt.figure()
plt.subplot(2, 2, 1)
plt.imshow(p8, cmap=plt.cm.gray)
plt.xlabel('original')
plt.colorbar()
plt.subplot(2, 2, 2)
plt.imshow(loc_otsu, cmap=plt.cm.gray)
plt.xlabel('local Otsu ($radius=%d$)' % radius)
plt.colorbar()
plt.subplot(2, 2, 3)
plt.imshow(p8 >= loc_otsu, cmap=plt.cm.gray)
コード例 #8
0
    roi_y2 = 0
    
image = image[roi_x2:roi_x1, roi_y2:roi_y1]
ground_truth = ground_truth[roi_x2:roi_x1, roi_y2:roi_y1]


if image.ndim == 3:
    print "Extract NIR channel"
    image = image[:,:,0] 
else:
    print "One dimension image"

print "OTSU Threshold with sliding window"

selem = rectangle(100,100)
local_otsu = rank.otsu(image, selem)


#
if soil_removed:
	soil_removed_image=io.imread(str(sys.argv[3]),as_grey=True)
	if (roi == True):
		soil_removed_image = soil_removed_image[roi_x2:roi_x1, roi_y2:roi_y1]
	ii, jj = np.where(soil_removed_image==0)
	image[ii, jj] = 0
 
binary_image = image > local_otsu


print "Distance Transform"
distance = ndimage.distance_transform_edt(binary_image)
コード例 #9
0
    for global Otsu thresholding: `skimage.filter.threshold_otsu`.

.. [1] http://en.wikipedia.org/wiki/Otsu's_method

"""

from skimage.filter.rank import otsu
from skimage.filter import threshold_otsu

p8 = data.page()

radius = 10
selem = disk(radius)

# t_loc_otsu is an image
t_loc_otsu = otsu(p8, selem)
loc_otsu = p8 >= t_loc_otsu

# t_glob_otsu is a scalar
t_glob_otsu = threshold_otsu(p8)
glob_otsu = p8 >= t_glob_otsu

plt.figure()
plt.subplot(2, 2, 1)
plt.imshow(p8, cmap=plt.cm.gray)
plt.xlabel('original')
plt.colorbar()
plt.subplot(2, 2, 2)
plt.imshow(t_loc_otsu, cmap=plt.cm.gray)
plt.xlabel('local Otsu ($radius=%d$)' % radius)
plt.colorbar()
コード例 #10
0
ファイル: segmentation.py プロジェクト: mehdi1902/SarBeh
def segmentation(sample):
    samples = []
    cores = []
    images = []
    cf = .9
    entropy_ratio = .5
    core_ratio = .07 #around 10% of image is core
    eq_thresh = 10
    csize = 300 #change it later
#    for sample in samples:
    #    if image_number<5:
    #        image_number += 1
    #        continue
        
#    image_number += 1
    try:
        gray_images = np.array([i for i in open_image(sample)])
    except:
        print 'can\'t open'
#        continue
    m, n = gray_images[0].shape
    
    g_min = np.min(gray_images[1:], axis=0)
    g_max = np.max(gray_images[1:], axis=0)
    g_avg = np.average(gray_images[1:], axis=0)
    g_mean = rank.mean_bilateral(g_max, disk(40))
    images.append(g_max)
    
    
    selem = disk(5)
    
    diff = g_max-g_min
    diff1 = g_avg-g_min
    diff2 = g_max-g_avg
    h2 = histogram(diff2)
    
    '''
    equalize image -> cores are white or black
    '''
    equalized = img_as_ubyte(exposure.equalize_hist(diff))
    
    
    #equalized = img_as_ubyte(exposure.equalize_hist(g_min))#g_min
    equalized = exposure.adjust_gamma(g_max,2)
    ##eq_mask = []
    #equalized = img_as_ubyte(exposure.equalize_hist(mask))
    #eq_mask = equalized<eq_thresh
    
    
    '''
    local otsu
    '''
    radius = 20
    selem = disk(radius)
    local_otsu = rank.otsu(equalized, selem)
#    local_otsu = tmp<threshold_otsu(equalized)
    bg = diff<=local_otsu
    

    ent = rank.entropy(g_max*~bg, disk(35))
    grad = rank.gradient(g_mean, disk(50))
    tmp = ent*grad
    core_mask = tmp>(np.min(tmp)+(np.max(tmp)-np.min(tmp))*entropy_ratio)    
    
#    
#    h = histogram(local_otsu)
#    cdf = 0
#    t = g_min.shape[0]*g_min.shape[1]*core_ratio
#    
#    for i in range(len(h)):
#        cdf += h[i]
#        if cdf > t:
#            maxi = i
#            break
#        
#    core_mask = (local_otsu<maxi)
##    imshow(core_mask)
#    ##cores = np.logical_and(eq_mask, core_mask)
#    ##imshow(eq_mask)
#    #
#    #
    
    
    lbl, num_lbl = ndi.label(core_mask)
    
    
    for i in range(1,num_lbl+1):
        '''
        lbl==0 is background
        '''
        c = np.where(np.max(lbl==i, axis=0)==True)[0]
        left = c[0]
        right = c[-1]
        
        c = np.where(np.max(lbl==i, axis=1)==True)[0]
        up = c[0]
        down = c[-1]

#        '''
#        Don't consider edge cores
#        '''            
#        if left<csize/2 or right>n-csize/2:
#            continue
#        if up<csize/2 or down>m-csize/2:
#            continue
#        
        
    
        core = np.zeros((csize, csize))
        h = down-up
        w = right-left
        
        middle_x = min(max((up+down)/2, csize/2),m-csize/2)
        middle_y = min(max((left+right)/2, csize/2), n-csize/2)
        
#        core = (core_mask*gray_images[0])[middle_x-csize/2:middle_x+csize/2, middle_y-csize/2:middle_y+csize/2]
        core = gray_images[0][middle_x-csize/2:middle_x+csize/2, middle_y-csize/2:middle_y+csize/2]
        core = exposure.adjust_gamma(core,.5)
        
        
        cores.append(core)
    return cores
#    print 'image', image_number
#    
#if __name__=='__main__':
#    os.system('rm %s -R'%(output_dir))
#    os.system('mkdir %s'%(output_dir))
#    #os.system('mkdir %sres/021'%(input_dir))
#    #os.system('mkdir %sres/041'%(input_dir))
#    for i in range(len(cores)):
#        image_name = '%s/%i.png'%(output_dir, i)
#        imsave(image_name, cores[i])
        
        
        
        
        
コード例 #11
0
.. [1] http://en.wikipedia.org/wiki/Otsu's_method

"""
import matplotlib.pyplot as plt

from skimage import data
from skimage.morphology.selem import disk
import skimage.filter.rank as rank
from skimage.filter import threshold_otsu

p8 = data.page()

radius = 10
selem = disk(radius)

loc_otsu = rank.otsu(p8, selem)
t_glob_otsu = threshold_otsu(p8)
glob_otsu = p8 >= t_glob_otsu

plt.figure()
plt.subplot(2, 2, 1)
plt.imshow(p8, cmap=plt.cm.gray)
plt.xlabel('original')
plt.colorbar()
plt.subplot(2, 2, 2)
plt.imshow(loc_otsu, cmap=plt.cm.gray)
plt.xlabel('local Otsu ($radius=%d$)' % radius)
plt.colorbar()
plt.subplot(2, 2, 3)
plt.imshow(p8 >= loc_otsu, cmap=plt.cm.gray)
plt.xlabel('original>=local Otsu' % t_glob_otsu)
コード例 #12
0
    roi_y1 = image.shape[1]
    roi_y2 = 0

image = image[roi_x2:roi_x1, roi_y2:roi_y1]
ground_truth = ground_truth[roi_x2:roi_x1, roi_y2:roi_y1]

if image.ndim == 3:
    print "Extract NIR channel"
    image = image[:, :, 0]
else:
    print "One dimension image"

print "OTSU Threshold with sliding window"

selem = rectangle(100, 100)
local_otsu = rank.otsu(image, selem)

#
if soil_removed:
    soil_removed_image = io.imread(str(sys.argv[3]), as_grey=True)
    if (roi == True):
        soil_removed_image = soil_removed_image[roi_x2:roi_x1, roi_y2:roi_y1]
    ii, jj = np.where(soil_removed_image == 0)
    image[ii, jj] = 0

binary_image = image > local_otsu

print "Distance Transform"
distance = ndimage.distance_transform_edt(binary_image)

print "Extract local maxima"
コード例 #13
0
import matplotlib
import matplotlib.pyplot as plt

from skimage import data
from skimage.morphology import disk
from skimage.filter import threshold_otsu, rank
from skimage.util import img_as_ubyte

matplotlib.rcParams['font.size'] = 9

img = img_as_ubyte(data.page())

radius = 15
selem = disk(radius)

local_otsu = rank.otsu(img, selem)
threshold_global_otsu = threshold_otsu(img)
global_otsu = img >= threshold_global_otsu

plt.figure(figsize=(8, 5))

plt.subplot(2, 2, 1)
plt.imshow(img, cmap=plt.cm.gray)
plt.title('Original')
plt.colorbar(orientation='horizontal')
plt.axis('off')

plt.subplot(2, 2, 2)
plt.imshow(local_otsu, cmap=plt.cm.gray)
plt.title('Local Otsu (radius=%d)' % radius)
plt.colorbar(orientation='horizontal')
コード例 #14
0
from skimage.filter.rank import otsu
from skimage.filter import threshold_otsu
import matplotlib.pyplot as plt
import skimage
from skimage import data
from skimage.filter import threshold_otsu, threshold_adaptive
from skimage.morphology import disk

p8 = skimage.io.imread("Cartilagini.png")

radius = 10
selem = disk(radius)

# t_loc_otsu is an image
t_loc_otsu = otsu(p8, selem)
loc_otsu = p8 >= t_loc_otsu

# t_glob_otsu is a scalar
t_glob_otsu = threshold_otsu(p8)
glob_otsu = p8 >= t_glob_otsu

plt.figure()
plt.subplot(2, 2, 1)
plt.imshow(p8, cmap=plt.cm.gray)
plt.xlabel('original')
plt.colorbar()
plt.subplot(2, 2, 2)
plt.imshow(t_loc_otsu, cmap=plt.cm.gray)
plt.xlabel('local Otsu ($radius=%d$)' % radius)
plt.colorbar()
plt.subplot(2, 2, 3)
コード例 #15
0
ファイル: plot_local_otsu.py プロジェクト: A-0-/scikit-image
from skimage import data
from skimage.morphology import disk
from skimage.filter import threshold_otsu, rank
from skimage.util import img_as_ubyte


matplotlib.rcParams['font.size'] = 9


img = img_as_ubyte(data.page())

radius = 15
selem = disk(radius)

local_otsu = rank.otsu(img, selem)
threshold_global_otsu = threshold_otsu(img)
global_otsu = img >= threshold_global_otsu


fig, ax = plt.subplots(2, 2, figsize=(8, 5))
ax1, ax2, ax3, ax4 = ax.ravel()

fig.colorbar(ax1.imshow(img, cmap=plt.cm.gray),
           ax=ax1, orientation='horizontal')
ax1.set_title('Original')
ax1.axis('off')

fig.colorbar(ax2.imshow(local_otsu, cmap=plt.cm.gray),
           ax=ax2, orientation='horizontal')
ax2.set_title('Local Otsu (radius=%d)' % radius)