Example #1
0
	def adaptive_none(self, grid_number):
		# First divide the image into number of grid.
		# Total, grid_number^2 number of grids.
		# 7, 5 are not working
		x, y = 0, 0
		img = deepcopy(self.img)
		while(True):
			# Find left upper corner only.
			if x + grid_number >= self.col and y + grid_number >= self.row:
				# at last grid.
				subimg = self.img[y: , x: ]
				opt = threshold_otsu(subimg)
				img[y:, x:] = self.img[y:, x:] > opt
				break
			elif x + grid_number >= self.col and y + grid_number < self.row:
				# at the right edge.
				subimg = self.img[y : y + grid_number, x :]
				opt = threshold_otsu(subimg)
				img[y : y + grid_number, x :] = self.img[y : y + grid_number, x :] > opt
				y = y+grid_number
				x = 0
			elif x + grid_number < self.col and y + grid_number >= self.row:
				subimg = self.img[y : , x : x + grid_number]
				opt = threshold_otsu(subimg)
				img[y : , x : x + grid_number] = self.img[y : , x : x + grid_number] > opt
				# print self.img[y : , x : x + width]
				x = x + grid_number
			else:
				subimg = self.img[y : y + grid_number, x : x + grid_number]
				opt = threshold_otsu(subimg)
				img[y : y + grid_number, x : x + grid_number] = self.img[y : y + grid_number, x : x + grid_number] > opt
				# print self.img[y : y + height, x : x + width]
				x = x+grid_number

		return img
Example #2
0
def main():
    parser = OptionParser()
    (options, args) = parser.parse_args()
    # reading input files 
    path = args[0] 

    # ref is the image that is used as a reference to subtract the background.
    roi = [125,125,1050,1250]
    roi_minx = roi[0]
    roi_miny = roi[1]
    roi_maxx = roi[2]
    roi_maxy = roi[3]
    
    template = io.imread(args[1])  
    template = template[:,:,0] 
    #ref = ref[roi_minx:roi_maxx, roi_miny:roi_maxy] 
    
    # otsu threshold the ref
    thresh = filter.threshold_otsu(template)
    template = template < thresh
    #plt.imshow(ref)
    #plt.show()    
    
    ref = io.imread(args[2])
    ref = ref[:,:,0]
    ref = ref[roi_minx:roi_maxx, roi_miny:roi_maxy] 
    thresh = filter.threshold_otsu(ref)
    ref= ref < thresh
    #plt.imshow(ref)
    #plt.show()
    
    output = []    
    
    for subdir, dirs, files in os.walk(path):
        for file in files:
            fn = os.path.join(subdir, file) 
            img = io.imread(fn)
            img = img[:,:,0]  
            img = img[roi_minx:roi_maxx, roi_miny:roi_maxy] 
            # do otsu thresholding
            thresh = filter.threshold_otsu(img)
            img = img < thresh
            #img = abs(img-ref) 
            #plt.imshow(img)
            #plt.show()
            centers = find_centers(img,template)
            # get the image number from the file 
            
            n = int(re.search(r'\d+', file).group())
            output.append((n, centers))
            
    output = sorted(output, key=lambda x:x[0])

    # now post process the output
    post_process(output,roi)
Example #3
0
def generate_template(digit_dir_path):
	template = zeros((42, 42))

	for filename in iglob(digit_dir_path + '/*.bmp'):
		img = imread(filename)
		img = resize(img, [44, 44])
		img = img[1:43,1:43]
		img = (img > (threshold_otsu(img, nbins=256)))
		template += img

	template = (template < (threshold_otsu(template, nbins=256)-5))
	return template
Example #4
0
def scikit_otsu(img):
	rows,cols,depth=img.shape
	from skimage.filter import threshold_otsu
	print "threshold using scikit" , np.floor(threshold_otsu(img))
	threshold=np.floor(threshold_otsu(img))
	imgO=np.zeros((rows,cols),int)
	for i in range(cols):
		for j in range(rows):
			if img[i,j,0]>=threshold: 
				imgO[i,j]=255
			elif img[i,j,0]<threshold:
				imgO[i,j]=0
	return imgO
def percent_vert_horiz_lines(FilledBlobImg, props_area):
    v = filter.vsobel(FilledBlobImg)
    v_floor = filter.threshold_otsu(v)
    ind_v = np.where(v > v_floor)
    h = filter.hsobel(FilledBlobImg)
    h_floor = filter.threshold_otsu(h)
    ind_h = np.where(h > h_floor)

    vert_and_horiz = np.zeros(v.shape).astype("bool")
    vert_and_horiz[ind_v] = True
    vert_and_horiz[ind_h] = True
    ind = np.where(vert_and_horiz)[0]
    return float(ind.size) / props_area
Example #6
0
def robertCross(A):
	robert_minus=np.array([[1,0],[0,-1]])
	robert_plus=np.array([[0,1],[-1,0]])
	result1=convolution(A,robert_minus);
	result1=np.abs(result1)
	thresh1=np.floor(threshold_otsu(result1))
	result1=np.logical_or(result1<0,result1>thresh1)
	result2=convolution(A,robert_plus);
	result2=np.abs(result2)
	thresh2=np.floor(threshold_otsu(result2))
	result2=np.logical_or(result2<0,result2>thresh2)
	result=np.logical_or(result1,result2);
	return result
Example #7
0
def ifcb_segment(img):
    Y = img_as_float(img)
    # step 1. local variance
    Yv = rescale_intensity(generic_filter(Y, np.var, footprint=disk(3)))
    # step 2. threshold local variance, aggressively
    Ye = Yv > (threshold_otsu(Yv) / 2.)
    # step 3. dark areas
    Yt = Y < threshold_otsu(Y)
    thin_blob = Ye | Yt
    # step 4. morphological reconstruction
    seed = np.copy(thin_blob)
    seed[1:-1,1:-1] = 1
    four=np.disk(1).astype(np.bool)
    return reconstruction(seed,thin_blob,method='erosion',selem=four)
Example #8
0
def variance_otsu(image, labels):
    """
    Read pixel intensities from 'image' for each class given in 'labels' (a corresponding cluster
    label array), and use Otsu's binarisation to threshold the image.

    :param image: Pre-processed input image
    :param labels: Array with same shape as input image, containing cluster labels
    """
    img = image.ravel()
    shadow_seg = img.copy()

    hist, _ = np.histogram(labels)
    n_clusters = hist.shape[0]
    for i in range(0, n_clusters):
        # set up mask of pixel indices matching cluster
        mask = np.nonzero((labels.ravel() == i) == True)[0]
        if len(mask) > 0:
            if img[mask].var() > 0.005:
                thresh = threshold_otsu(img[mask])
                shadow_seg[mask] = shadow_seg[mask] < thresh
            else:
                shadow_seg[mask] = 0

    shadow_seg = shadow_seg.reshape(*image.shape)
    return shadow_seg
Example #9
0
    def find_letters(self, image, show=True):
        image = restoration.denoise_tv_chambolle(image, weight=0.1)

        try:
            thresh = threshold_otsu(image)
        except Exception:
            print("Could not treshold")
            result = []
            return result

        bw = closing(image > thresh, square(2))
        cleared = bw.copy()

        label_image = measure.label(cleared)
        borders = np.logical_xor(bw, cleared)
        label_image[borders] = -1
        # image_label_overlay = label2rgb(label_image, image=image)

        # fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(12, 12))
        # ax.imshow(image_label_overlay)

        result = []
        for region in regionprops(label_image):
            minr, minc, maxr, maxc = region.bbox
            result.append(Letter(minc, minr, maxc, maxr))
            # rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr, fill=False, edgecolor='red', linewidth=2)
            # ax.add_patch(rect)

        # if show:
            # plt.show()

        return result
Example #10
0
def threshold(data):
    thresh1 = threshold_otsu(data)
    thresh2 = thresh1 * 2
    print "ndi thresh", thresh1, thresh2
    data[data < thresh2] = 0
    data[data >= thresh2] = 255
    return data
Example #11
0
def binarizeImage(RGBimage):

    image = rgb2gray(RGBimage)
    threshold = filter.threshold_otsu(image)
    binarizedImage = image < threshold

    return binarizedImage
Example #12
0
def max_mask_iter(fns, offset=0, close_radius=0, erode_radius=0):
    """Find masks for a set of images having brightness artifacts.

    Parameters
    ----------
    fns : list of string
        The images being examined.
    offset : int, optional
        Offset the threshold automatically found.
    close_radius : int, optional
        Perform a morphological closing of the mask of this radius.
    erode_radius : int, optional
        Perform a morphological erosion of the mask, after any closing,
        of this radius.

    Returns
    -------
    maxes : iterator of bool array
        The max mask image corresponding to each input image.
    """
    ms = maxes(fns)
    t = imfilter.threshold_otsu(ms)
    ims = it.imap(io.imread, fns)
    masks = ((im < t + offset) for im in ims)
    if close_radius > 0:
        masks = (morphop(mask, 'close', close_radius) for mask in masks)
    if erode_radius > 0:
        masks = (morphop(mask, 'erode', erode_radius) for mask in masks)
    return masks
Example #13
0
def max_mask_iter(fns, offset=0, close_radius=0, erode_radius=0):
    """Find masks for a set of images having brightness artifacts.

    Parameters
    ----------
    fns : list of string
        The images being examined.
    offset : int, optional
        Offset the threshold automatically found.
    close_radius : int, optional
        Perform a morphological closing of the mask of this radius.
    erode_radius : int, optional
        Perform a morphological erosion of the mask, after any closing,
        of this radius.

    Returns
    -------
    maxes : iterator of bool array
        The max mask image corresponding to each input image.
    """
    ms = maxes(fns)
    t = imfilter.threshold_otsu(ms)
    ims = it.imap(io.imread, fns)
    masks = ((im < t + offset) for im in ims)
    if close_radius > 0:
        masks = (morphop(mask, 'close', close_radius) for mask in masks)
    if erode_radius > 0:
        masks = (morphop(mask, 'erode', erode_radius) for mask in masks)
    return masks
Example #14
0
def getRegions():
    """Geocode address and retreive image centered
    around lat/long"""
    address = request.args.get('address')
    results = Geocoder.geocode(address)
    lat, lng = results[0].coordinates
    zip_code = results[0].postal_code

    map_url = 'https://maps.googleapis.com/maps/api/staticmap?center={0},{1}&size=640x640&zoom=19&sensor=false&maptype=roadmap&&style=visibility:simplified|gamma:0.1'
    request_url = map_url.format(lat, lng)
    req = urllib.urlopen(request_url)
    img = io.imread(req.geturl(),flatten=True)
    labels, numobjects = ndimage.label(img)
    image = filter.canny(img, sigma=3)
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(3))

    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)

    # label image regions
    label_image = label(cleared)
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    image_label_overlay = label2rgb(label_image, image=image)

    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
    ax.imshow(image_label_overlay)
Example #15
0
def getRegions():
    """Geocode address and retreive image centered
    around lat/long"""
    address = request.args.get('address')
    results = Geocoder.geocode(address)
    lat, lng = results[0].coordinates
    zip_code = results[0].postal_code

    map_url = 'https://maps.googleapis.com/maps/api/staticmap?center={0},{1}&size=640x640&zoom=19&sensor=false&maptype=roadmap&&style=visibility:simplified|gamma:0.1'
    request_url = map_url.format(lat, lng)
    req = urllib.urlopen(request_url)
    img = io.imread(req.geturl(), flatten=True)
    labels, numobjects = ndimage.label(img)
    image = filter.canny(img, sigma=3)
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(3))

    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)

    # label image regions
    label_image = label(cleared)
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    image_label_overlay = label2rgb(label_image, image=image)

    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
    ax.imshow(image_label_overlay)
Example #16
0
def scikit_example_plot_label():
    image = data.coins()[50:-50, 50:-50]
    
    # apply threshold
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(3))
    
    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)
    
    # label image regions
    label_image = label(cleared)
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    
    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
    ax.imshow(label_image, cmap='jet')
    
    for region in regionprops(label_image, ['Area', 'BoundingBox']):
    
        # skip small images
        if region['Area'] < 100:
            continue
    
        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region['BoundingBox']
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2)
        ax.add_patch(rect)
    
    plt.show()
Example #17
0
def threshold(data):
	thresh1	= threshold_otsu(data)
	thresh2 = thresh1*2
	print "ndi thresh", thresh1, thresh2
	data[data<thresh2] 	= 0
	data[data>=thresh2]	= 255
	return data
Example #18
0
def intensity_object_features(im, adaptive_t_radius=51, sample_size=None):
    """Segment objects based on intensity threshold and compute properties.

    Parameters
    ----------
    im : 2D np.ndarray of float or uint8.
        The input image.
    adaptive_t_radius : int, optional
        The radius to calculate background with adaptive threshold.
    sample_size : int, optional
        Sample this many objects randomly, rather than measuring all
        objects.

    Returns
    -------
    f : 1D np.ndarray of float
        The feature vector.
    names : list of string
        The list of feature names.
    """
    tim1 = im > imfilter.threshold_otsu(im)
    f1, names1 = object_features(tim1, im, sample_size=sample_size)
    names1 = ['otsu-threshold-' + name for name in names1]
    tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius)
    f2, names2 = object_features(tim2, im, sample_size=sample_size)
    names2 = ['adaptive-threshold-' + name for name in names2]
    f = np.concatenate([f1, f2])
    return f, names1 + names2
Example #19
0
def get_cells(image):
    '''
    Get cellls from the polygon.
    '''
    # apply threshold    
    thresh = threshold_otsu(image)
    binary = image > thresh
    bw=binary
    plt.imshow(bw)

    # Remove connected to image border
    cleared = bw.copy()
    clear_border(cleared)

    # label image regions
    label_image = skimage.measure.label(cleared)
    #find_contours
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    image_label_overlay = label2rgb(label_image, image=image)

    #extract the regions and get a polygon per region
    polygons=[]
    for i,region in enumerate(regionprops(label_image)):
        # skip small images
        if region.area < 100:
            continue
        a=np.zeros([len(region.coords),2])
        #a=np.zeros(
        plt.imshow(bw)
        for i in range(len(region.coords)):
            a[i,:]=[region.coords[i][0],region.coords[i][1]]
        polygons.append(a)
    return polygons     
    def _test_binary_image(self): #binary does not rotate axis.
            # apply threshold
            img = self.phase_data.copy()
            print "min,max:",np.amin(img),np.amax(img)
            thresh = threshold_otsu(img)
            print "threshold",thresh
            binary = self.phase_data > thresh
            print "min,max:",np.amin(binary),np.amax(binary)
            bw=binary


            # Remove connected to image border
            cleared = bw.copy()
            skimage.segmentation.clear_border(cleared)
            #up to now nothing is rotated.

            # label image regions
            label_image = skimage.measure.label(cleared)
            skimage.io.imsave("phase_binary.tif",label_image*255)

            #find_contours
            borders = np.logical_xor(bw, cleared)
            label_image[borders] = -1
            image_label_overlay = skimage.color.label2rgb(label_image, image=img)
            skimage.io.imsave("phase_binary2.tif",image_label_overlay*255)
Example #21
0
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
Example #22
0
def watershed_slicing(image):
    """
    Does the watershed algorithm slice by slice.
    Then use the labeled image to calculate the centres of
    mass for each slice.
    """
    image = median_filter(image, 3)
    thresh = threshold_otsu(image)
    image = (image > thresh) * 1

    N = len(image)
    slice_centroids = []
    slice_radius = []

    for i in range(N):

        slice = image[:, :, i]

        labels_slice = watershed_segmentation(slice)
        centroids, areas, bords, radius = centres_of_mass_2D(labels_slice)

        slice_centroids.append(centroids)
        slice_radius.append(radius)
#         if i > 49:
#             print centroids
#             pl.imshow(labels_slice)
#             pl.show()

    return slice_centroids, slice_radius
Example #23
0
def intensity_object_features(im, adaptive_t_radius=51, sample_size=None):
    """Segment objects based on intensity threshold and compute properties.

    Parameters
    ----------
    im : 2D np.ndarray of float or uint8.
        The input image.
    adaptive_t_radius : int, optional
        The radius to calculate background with adaptive threshold.
    sample_size : int, optional
        Sample this many objects randomly, rather than measuring all
        objects.

    Returns
    -------
    f : 1D np.ndarray of float
        The feature vector.
    names : list of string
        The list of feature names.
    """
    tim1 = im > imfilter.threshold_otsu(im)
    f1, names1 = object_features(tim1, im, sample_size=sample_size)
    names1 = ['otsu-threshold-' + name for name in names1]
    tim2 = imfilter.threshold_adaptive(im, adaptive_t_radius)
    f2, names2 = object_features(tim2, im, sample_size=sample_size)
    names2 = ['adaptive-threshold-' + name for name in names2]
    f = np.concatenate([f1, f2])
    return f, names1 + names2
Example #24
0
 def plot_preprocessed_image(self):
     """
     plots pre-processed image. The plotted image is the same as obtained at the end
     of the get_text_candidates method.
     """
     image = restoration.denoise_tv_chambolle(self.image, weight=0.1)
     thresh = threshold_otsu(image)
     bw = closing(image > thresh, square(2))
     cleared = bw.copy()
     
     label_image = measure.label(cleared)
     borders = np.logical_xor(bw, cleared)
    
     label_image[borders] = -1
     image_label_overlay = label2rgb(label_image, image=image)
     
     fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(12, 12))
     ax.imshow(image_label_overlay)
     
     for region in regionprops(label_image):
         if region.area < 10:
             continue
     
         minr, minc, maxr, maxc = region.bbox
         rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                   fill=False, edgecolor='red', linewidth=2)
         ax.add_patch(rect)
     
     plt.show()       
Example #25
0
def watershed_3d(sphere):
    """
    Markers should be int8
    Image should be uint8
    """

    sphere = median_filter(sphere, 3)
    thresh = threshold_otsu(sphere)
    sphere = (sphere >= thresh) * 1
    sphere = sobel(sphere)

    size = (sphere.shape[0], sphere.shape[1], sphere.shape[2])

    marker = np.zeros(size, dtype=np.int16)
    pl.imshow(sphere[:, :, 50])
    pl.show()
    # mark everything outside as background
    marker[5, :, :] = -1
    marker[size[0] - 5, :, :] = -1
    marker[:, :, 5] = -1
    marker[:, :, size[2] - 5] = -1
    marker[:, 5, :] = -1
    marker[:, size[1] - 5, :] = -1
    marker[:, 0, 0] = -1
    # mark everything inside as a sphere
    marker[size[0] / 2., size[1] / 2., size[2] / 2.] = 5

    result = measurements.watershed_ift(sphere.astype(dtype=np.uint16), marker)
    pl.imshow(result[:, :, 50])
    pl.show()

    return result
Example #26
0
    def one_file_features(self, im, demo=False):

        """
        Zde je kontruován vektor příznaků pro klasfikátor
        """
        fd = np.array([])

        import skimage.transform
        import skimage

        # Zmena velikosti obrazku
        image = skimage.transform.resize(im, [50, 50])

        #%% Vyriznuti objektu kolem stredu obrazu
        image = image[int(image.shape[0]/2)-20:int(image.shape[0]/2)+20, int(image.shape[1]/2)-20:int(image.shape[1]/2)+20]
        fd = np.append(fd, image.reshape(-1))

        # Vyuziti Otsuova filtru
        from skimage import filter

        threshold = filter.threshold_otsu(image)
        image =image < threshold

        fd = np.append(fd, image.reshape(-1))

        #%% Změna velikosti


        #fd.append(hsvft[:])
       # if self.colorFeatures:
       #     fd = np.append(fd, self.colorFeatures)
           # pass

        return fd
def watershed_slicing(image):
    """
    Does the watershed algorithm slice by slice.
    Then use the labeled image to calculate the centres of
    mass for each slice.
    """
    image = median_filter(image, 3)
    thresh = threshold_otsu(image)
    image = (image > thresh) * 1
    
    
    N = len(image)
    slice_centroids = []
    slice_radius = []
    
    for i in range(N):
        
        slice = image[:, :, i]
        
        labels_slice = watershed_segmentation(slice)
        centroids, areas, bords, radius = centres_of_mass_2D(labels_slice)
        
        slice_centroids.append(centroids)
        slice_radius.append(radius)
#         if i > 49:
#             print centroids
#             pl.imshow(labels_slice)
#             pl.show()
        
    return slice_centroids, slice_radius
Example #28
0
def label_stack(z_stack, parameters):
    '''
    Apply an automated threshold and a watershed algorithm to
    label cells in each planes of the stack

    Parameters:
    -----------
    z_stack: 3d array of shape (nz, nx, ny)

    Returns:
    --------
    labeled_stack: 3d array of the same shape as z_stack,
    with each detected region labeled
    '''
    segment_method = parameters['segment_method']
    correction = parameters['correction']
    labeled_stack = np.zeros(z_stack.shape, dtype=np.uint8)
    max_int_proj = z_stack.max(axis=0)
    thresh = None

    if segment_method == 'otsu':
        thresh = threshold_otsu(max_int_proj) * correction
    elif segment_method == 'naive':
        thresh = max_int_proj.max() * correction
    else:
        err_string = ('Segmentation method {}'
                      'is not implemented'.format(segment_method))
        raise NotImplementedError(err_string)
    while thresh > z_stack.max():
        log.warning('''Reducing threshold''')
        thresh *= 0.9
    for n, frame in enumerate(z_stack):
        labeled_stack[n] = label_from_thresh(frame, thresh, parameters)
    return labeled_stack
Example #29
0
    def one_file_features(self, im, demo=False):
        """
        Zde je kontruován vektor příznaků pro klasfikátor
        """
        fd = np.array([])

        import skimage.transform
        import skimage

        # Zmena velikosti obrazku
        image = skimage.transform.resize(im, [50, 50])

        #%% Vyriznuti objektu kolem stredu obrazu
        image = image[int(image.shape[0] / 2) - 20:int(image.shape[0] / 2) +
                      20,
                      int(image.shape[1] / 2) - 20:int(image.shape[1] / 2) +
                      20]
        fd = np.append(fd, image.reshape(-1))

        # Vyuziti Otsuova filtru
        from skimage import filter

        threshold = filter.threshold_otsu(image)
        image = image < threshold

        fd = np.append(fd, image.reshape(-1))

        #%% Změna velikosti

        #fd.append(hsvft[:])
        # if self.colorFeatures:
        #     fd = np.append(fd, self.colorFeatures)
        # pass

        return fd
Example #30
0
def roofRegion(edge):
    """Estimate region based on edges of roofRegion
    """
    # apply threshold
    thresh = threshold_otsu(image)
    bw = closing(image > thresh, square(3))

    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)

    # label image regions
    label_image = label(cleared)
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    image_label_overlay = label2rgb(label_image, image=image)

    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))
    ax.imshow(image_label_overlay)

    for region in regionprops(label_image):

        # skip small images
        if region.area < 100:
            continue

        # draw rectangle around segmented coins
        minr, minc, maxr, maxc = region.bbox
        rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                  fill=False, edgecolor='red', linewidth=2)
        ax.add_patch(rect)

    plt.show()
Example #31
0
def count_cell(img, edge_pixels, erosion_iterations):
    img_no_edge = remove_edge(img, edge_pixels)
    threshold = threshold_otsu(img_no_edge)
    img_thr = threshold_image(img_no_edge, threshold)
    eroded_img = ndimage.morphology.binary_erosion(img_thr, iterations = erosion_iterations)
    labels, number_labels = ndimage.label(eroded_img)
    return number_labels
def threshold_image(image, threshold=0):
	"""
	This function takes out any values in an image's RGB matrix that are
	below the threshold value.

	Inputs:
	- image: a matrix describing an image with only one channel represented.
	- threshold: a value, between 0 and 1, for which if an image matrix's
				 value is below, will be set to 0, and if above, will be 
				 set to 1.

				 If the threshold is set to 0, then an Otsu thresholding will
				 be returned.

	Outputs:
	- thresholded_image: a matrix representation of the thresholded image.
						 this is essentially a black and white image.
	- thresh: the threshold value

	To screen: the black-and-white image representation.
	- 
	"""
	if threshold == 0:
		thresh = threshold_otsu(image)

	if threshold != 0:
		thresh = threshold

	thresholded_image = closing(image > thresh, square(3), out=None)
	imshow(thresholded_image)

	return thresholded_image, thresh
Example #33
0
def test():
    from skimage.filter import threshold_otsu
    img = imread('lena.bmp')
    grey = greyscale(img)
    sk_thres = np.floor(threshold_otsu(grey))
    my_thres = otsu_thresh(grey)
    assert sk_thres == my_thres
    def demoOtsuThresholding(self):
        img = data.camera()
        thresh = filter.threshold_otsu(img)
        mask = img > thresh

        fig, (ax1, ax2, ax3) = plt.subplots(1,
                                            3,
                                            figsize=(8, 2.5),
                                            facecolor='w')
        ax1.imshow(img, cmap='gray')
        ax1.set_title('Original')
        ax1.axis('off')

        ax2.hist(img)
        ax2.set_title('Histogram')
        ax2.axvline(thresh, color='r')

        ax3.imshow(mask, cmap='gray')
        ax3.set_title('Thresholded')
        ax3.axis('off')

        fname = '/Users/mangotee/Dropbox/Teaching/CDTM ARdrones Lecture/imgDemoOtsuThresholding.png'
        plt.savefig(fname)

        plt.show()
 def plot_preprocessed_image(self):
     """
     plots pre-processed image. The plotted image is the same as obtained at the end
     of the get_text_candidates method.
     """
     image = restoration.denoise_tv_chambolle(self.image, weight=0.1)
     thresh = threshold_otsu(image)
     bw = closing(image > thresh, square(2))
     cleared = bw.copy()
     
     label_image = measure.label(cleared)
     borders = np.logical_xor(bw, cleared)
    
     label_image[borders] = -1
     image_label_overlay = label2rgb(label_image, image=image)
     
     fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(12, 12))
     ax.imshow(image_label_overlay)
     
     for region in regionprops(label_image):
         if region.area < 10:
             continue
     
         minr, minc, maxr, maxc = region.bbox
         rect = mpatches.Rectangle((minc, minr), maxc - minc, maxr - minr,
                                   fill=False, edgecolor='red', linewidth=2)
         ax.add_patch(rect)
     
     plt.show()       
Example #36
0
    def __transform(self):
        self.__img_gray = io.imread(self.__img_path, True)

        self.__otsu = filter.threshold_otsu(self.__img_gray) #Aplicar otsu para binarizar a imagem
        self.__img_gray = self.__img_gray < self.__otsu

        # Find contours at a constant value of 0.5
        self.__contours = measure.find_contours(self.__img_gray, 0.5)

        self.__arclen = 0.0
        for n, contour in enumerate(self.__contours):
            arclenTemp=0.0
            for indice, valor in enumerate(contour):
               if indice > 0:
                    d1 = math.fabs(round(valor[0]) - round(contour[indice-1,0]))
                    d2 = math.fabs(round(valor[1]) - round(contour[indice-1,1]))
                    if d1+d2>1.0:
                        arclenTemp+=math.sqrt(2)
                    elif d1+d2 == 1:
                        arclenTemp+=1

            if arclenTemp > self.__arclen:
                self.__arclen = arclenTemp
                self.__bestn = n
        #self.__bestn = 0
        print self.__contours[0]
def watershed_3d(sphere):
    """
    Markers should be int8
    Image should be uint8
    """
   
    sphere = median_filter(sphere, 3)
    thresh = threshold_otsu(sphere)
    sphere = (sphere >= thresh) * 1
    sphere = sobel(sphere)
    
    size = (sphere.shape[0], sphere.shape[1], sphere.shape[2])
    
    marker = np.zeros(size, dtype=np.int16)
    pl.imshow(sphere[:,:,50])
    pl.show()
    # mark everything outside as background
    marker[5, :, :] = -1
    marker[size[0] - 5, :, :] = -1
    marker[:, :, 5] = -1
    marker[:, :, size[2] - 5] = -1
    marker[:, 5, :] = -1
    marker[:, size[1] - 5, :] = -1
    marker[:,0,0] = -1
    # mark everything inside as a sphere
    marker[size[0] / 2., size[1] / 2., size[2] / 2.] = 5

    result = measurements.watershed_ift(sphere.astype(dtype=np.uint16), marker)
    pl.imshow(result[:,:,50])
    pl.show()
    
    return result
def run_cmd(method, block_size=40):
    stdin = sys.stdin.read()
    if stdin == '\n':
        exit()

    img = Image.open(StringIO.StringIO(stdin)).convert('L')
    imgc = np.array(img)

    imggray = rgb2gray(imgc)

    if method is None or method == '':
        imgthresh = threshold_adaptive(imggray, block_size, 'gaussian', offset=10)
    elif method == 'gaussian':
        imgthresh = threshold_adaptive(imggray, block_size, 'gaussian', offset=10)
    elif method == 'median':
        imgthresh = threshold_adaptive(imggray, block_size, 'median', offset=10)
    elif method == 'mean':
        imgthresh = threshold_adaptive(imggray, block_size, 'mean', offset=10)
    elif method == 'otsu':
        thresh = threshold_otsu(imggray)
        imgthresh = imggray > thresh
    elif method == 'yen':
        thresh = threshold_yen(imggray)
        imgthresh = imggray > thresh
    elif method == 'iso':
        thresh = threshold_isodata(imggray)
        imgthresh = imggray > thresh


    rescaled = (255.0 / imgthresh.max() * (imgthresh - imgthresh.min())).astype(np.uint8)

    out = Image.fromarray(rescaled)
    out.save(sys.stdout, format='PNG')
Example #39
0
def test_3d():
    import h5py
    from skimage.filter import threshold_otsu
    from imseg.image_tools import imclip, normalize
    # from imseg.imtools.imclip import imclip as imclip2


    f = h5py.File('/Users/yue/data/obj.hdf5', 'r')
    im = f['object'][:, 350:900, 350:900]
    f.close()

    # im = anisodiff(im, niter=10)

    im = imclip(im, verbose=False)
    im = normalize(im, mode='median')
    thresholds = threshold_otsu(im)
    print('Threshold = {}'.format(thresholds))

    im_seg = ImSeg(im)
    im_seg.init(thresholds=thresholds,
                diff_sdf_kwargs=kwarg(it=5, dt=0.1),
                diff_error_kwargs=kwarg(it=20, dt=0.25),
                diff_ave_kwargs=kwarg(it=5, dt=0.1),
                reinit_sdf_kwargs=kwarg(niter=5, dt=0.1),
                init_reinit_sdf_kwargs=kwarg(niter=50, dt=0.1),
                im_slice=(slice(None), slice(None), 512 - 350),
                out_path='/Users/yue/data/segment/sdf_diff_3d_1/', debug=True, verbose=True)
    im_seg.initialize()

    for i in xrange(10):
        im_seg.iterate(10)
        im_seg.save()
def get_cells(image):
    '''
    Get cellls from the polygon.
    '''
    new_image=np.ones([3,image.shape[0],image.shape[1]],dtype=float)
    # apply threshold
    thresh = threshold_otsu(image)
    bw=image

    # remove artifacts connected to image border
    cleared = bw.copy()
    clear_border(cleared)

    # label image regions
    label_image = label(cleared)
    #skimage.measure.label
    #find_contours
    borders = np.logical_xor(bw, cleared)
    label_image[borders] = -1
    image_label_overlay = label2rgb(label_image, image=image)

    #extract the regions and get a polygon per region
    polygons=[]
    for i,region in enumerate(regionprops(label_image)):
        # skip small images
        if region.area < 100:
            continue
        #polygons.append(matplotlib.path.Path(region.coords))
        print (region.coords.shape)
        a=np.zeros(region.coords.shape)
        a[:,0]=region.coords[:,1]
        a[:,1]=region.coords[:,0]
        polygons.append(a)   
    return polygons
Example #41
0
def get_background_markers(image_gray):
    '''
    Finds the pixels that definitely belong in background regions.
    
    Parameters
    -----------
    image_gray : 2-D numpy array
        A grayscale image.
        
    Returns
    -----------
    markers_background : 2-D Boolean numpy array
        An array with the same shape as image_gray, where the seeds of
        the background regions are True. 
    '''
    dark_threshold = threshold_by_blocks(image_gray, 20, background_intensity)
    dark_pixels = image_gray <= dark_threshold
    image_smooth = gaussian_filter(image_gray, 1)
    otsu = image_gray > threshold_otsu(image_gray)
    #minima = local_min(image_smooth) & np.logical_not(otsu)
    #minima = local_min(image_gray) & (~ otsu)
    minima = local_min(image_gray)

    markers_background = dark_pixels | minima
    return markers_background
Example #42
0
def detect_edges(image):
    # 1. convert to grayscale image
    image_gray = rgb2gray(image)
    # 2. convolve with Sobel filter
    image_sobel = sobel(image_gray)
    # 3. compute binary edge image with threshold from Otsu's method
    image_edges = image_sobel > threshold_otsu(image_sobel)
    return image_sobel, image_edges
def detect_edges(image):
    # 1. convert to grayscale image
    image_gray = rgb2gray(image)
    # 2. convolve with Sobel filter
    image_sobel = sobel(image_gray)
    # 3. compute binary edge image with threshold from Otsu's method
    image_edges = image_sobel > threshold_otsu(image_sobel)
    return image_sobel, image_edges
 def binary_from_thresh(img):
     """ Base function for converting to binary using a threshold 
     args:
         img: m x n ndarray
     """
     thresh = threshold_otsu(img)
     binary = img < thresh
     return binary
Example #45
0
 def preprocess_image(self):
     """
     Denoises and increases contrast. 
     """
     image = restoration.denoise_tv_chambolle(self.image, weight=0.1)
     thresh = threshold_otsu(image)
     self.bw = closing(image > thresh, square(2))
     self.cleared = self.bw.copy()
     return self.cleared 
Example #46
0
def image_features_hog3(img, num_features,orientation,maxcell,maxPixel):

     image=denoise_bilateral(img, win_size=5, sigma_range=None, sigma_spatial=1, bins=10000, mode='constant', cval=0)
     thresh = threshold_otsu(image)
     binary = image > thresh
     im = resize(binary, (maxPixel, maxPixel))
     ##hog scikit transform
     

     return image_features_hog_fd(im)
Example #47
0
 def AddContour2(self):
     val = filter.threshold_otsu(self)
     mask = self < val
     
     # Morphological ACWE. Initialization of the level-set.
     macwe = ms.MorphACWE(self, smoothing=1, lambda1=1, lambda2=1)
     macwe.levelset = ms.circle_levelset(self.shape, (20, 20), 25)
     
     for i in range(20):
         macwe.step()
     print 'hey'
Example #48
0
def signal_to_noise_ratio(im1, im2, mask=None, thresh=None):
    ''' Compute SNR of two images (see Dietrich et al. 2007, 
        JMRI, 26, 375) '''
    print 'computing signal-to-noise ratio'
    from skimage.filter import threshold_otsu 
    if mask is None:
        if thresh is None:
            thresh = threshold_otsu(im1)
        mask = im1 > thresh
    return ((im1[mask] + im2[mask]).mean() / \
        (im1[mask] - im2[mask]).std() / sqrt(2), mask)
Example #49
0
def automatedfilter(imageFile):
    import matplotlib.pyplot as plt
    import numpy as np
    from skimage import data, io, color, exposure, filter, transform
    from skimage.filter import threshold_otsu

    imageThresh = io.imread(imageFile)
    image = Image.open(imageFile)
    thresh = threshold_otsu(imageThresh)
    resizeImg = resizeImage(image)
    imageArray = imageToBinaryArray(resizeImg, thresh)
    return imageArray
Example #50
0
def brain_mask(mat4d, size=2, numpass=2):
    from skimage.filter import threshold_otsu
    from scipy.ndimage import median_filter
    bm = np.array(mat4d)
    if bm.shape[3] > 1:
        bm = np.mean(bm, axis=3)
    for i in range(numpass):
        bm = median_filter(bm, size=size)
    t = threshold_otsu(bm)
    bm[bm < t] = 0
    bm[bm >= t] = 1
    return bm.astype(int)
Example #51
0
def feature_vector_from_rgb(image, sample_size=None):
    """Compute a feature vector from the composite images.

    The channels are assumed to be in the following order:
     - Red: MCF-7
     - Green: cytoplasm GFP
     - Blue: DAPI/Hoechst

    Parameters
    ----------
    im : array, shape (M, N, 3)
        The input image.
    sample_size : int, optional
        For features based on quantiles, sample this many objects
        rather than computing full distribution. This can considerably
        speed up computation with little cost to feature accuracy.

    Returns
    -------
    fs : 1D array of float
        The features of the image.
    names : list of string
        The feature names.
    """
    all_fs, all_names = [], []
    ims = np.rollaxis(image[..., :3], -1, 0) # toss out alpha chan if present
    mcf, cells, nuclei = ims
    prefixes = ['mcf', 'cells', 'nuclei']
    for im, prefix in zip(ims, prefixes):
        fs, names = features.intensity_object_features(im,
                                                       sample_size=sample_size)
        names = [prefix + '-' + name for name in names]
        all_fs.append(fs)
        all_names.extend(names)
    nuclei_mean = nd.label(nuclei > np.mean(nuclei))[0]
    fs, names = features.nearest_neighbors(nuclei_mean)
    all_fs.append(fs)
    all_names.extend(['nuclei-' + name for name in names])
    mcf_mean = nd.label(mcf)[0]
    fs, names = features.fraction_positive(nuclei_mean, mcf_mean,
                                           positive_name='mcf')
    all_fs.append(fs)
    all_names.extend(names)
    cells_t_otsu = cells > threshold_otsu(cells)
    cells_t_adapt = threshold_adaptive(cells, 51)
    fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_otsu)
    all_fs.append(fs)
    all_names.extend(['otsu-' + name for name in names])
    fs, names = features.nuclei_per_cell_histogram(nuclei_mean, cells_t_adapt)
    all_fs.append(fs)
    all_names.extend(['adapt-' + name for name in names])
    return np.concatenate(all_fs), all_names
Example #52
0
def task_1_3():
    I_1 = imread('images/coins.png')
    I_2 = imread('images/overlapping_euros1.png')

    # Get the otsu value via the 'Otsu Threshold' (where the histogram is to be split/segmented)
    otsu1 = filter.threshold_otsu(I_1)
    otsu2 = filter.threshold_otsu(I_2)

    # Extracting Histograms
    hist1, bins_center1 = exposure.histogram(I_1)
    hist2, bins_center2 = exposure.histogram(I_2)

    # Printing the images, segmenting inside 'imshow'
    plt.figure(figsize=(9, 4))
    plt.subplot(131)
    plt.imshow(I_1, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.subplot(132)
    plt.imshow(I_1 < otsu1, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.subplot(133)
    plt.plot(bins_center1, hist1, lw=2)
    plt.axvline(otsu1, color='k', ls='--')
    plt.tight_layout()
    plt.show()

    # Printing the images, segmenting inside 'imshow'
    plt.figure(figsize=(9, 4))
    plt.subplot(131)
    plt.imshow(I_2, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.subplot(132)
    plt.imshow(I_2 < otsu2, cmap='gray', interpolation='nearest')
    plt.axis('off')
    plt.subplot(133)
    plt.plot(bins_center2, hist2, lw=2)
    plt.axvline(otsu2, color='k', ls='--')
    plt.tight_layout()
    plt.show()
Example #53
0
def image_features_resize_thres(img, maxPixel, num_features,imageSize):
     # X is the feature vector with one row of features per image
     #  consisting of the pixel values a, num_featuresnd our metric

     X=np.zeros(num_features, dtype=float)
     image=denoise_bilateral(img, win_size=5, sigma_range=None, sigma_spatial=1, bins=10000, mode='constant', cval=0)
     thresh = threshold_otsu(image)
     binary = image > thresh
     im = resize(binary, (maxPixel, maxPixel))

     # Store the rescaled image pixels
     X[0:imageSize] = np.reshape(im,(1, imageSize))

     return X
Example #54
0
def local_threshold(img_arr):
    """
    For each pixel, an optimal threshold is determined by maximizing
    the variance between two classes of pixels of the local neighborhood
    defined by a structuring element.

    Input: 	3D image tensor or 2D grayscaled image or
           filtered/transformed image array.
    Output: binary img_array where pixels are >= global threshold
    """

    threshold_global_otsu = threshold_otsu(img_arr)
    global_otsu = img_arr >= threshold_global_otsu

    return np.ravel(global_otsu.astype(int))
def segment_shadow(image, labels, n_clusters=8):
    img = image.ravel()
    shadow_seg = img.copy()
    for i in range(0, n_clusters):
        # set up array of pixel indices matching cluster
        mask = np.nonzero((labels.ravel() == i) == True)[0]
        if len(mask) > 0:
            if img[mask].var() > 0.005:
                thresh = threshold_otsu(img[mask])
                shadow_seg[mask] = shadow_seg[mask] < thresh
            else:
                shadow_seg[mask] = 0

    shadow_seg = shadow_seg.reshape(*image.shape)
    return shadow_seg
Example #56
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
Example #57
0
    def _segment_edge_areas(edges, disk_size=9, mean_threshold=200, min_object_size=500):
        """
        Takes a greyscale image (with brighter colors corresponding to edges) and returns a binary image where white
        indicates an area with high edge density and black indicates low density.

        """
        # Convert the greyscale edge information into black and white (ie binary) image
        threshold = threshold_otsu(edges)
        # Filter out the edge data below the threshold, effectively removing some noise
        raw_channel_areas = edges <= threshold
        # Smooth out the data
        channel_areas = rank.mean(raw_channel_areas, disk(disk_size)) < mean_threshold
        # Remove specks and blobs that are the result of artifacts
        clean_channel_areas = remove_small_objects(channel_areas, min_size=min_object_size)
        # Fill in any areas that are completely surrounded by the areas (hopefully) covering the channels
        return ndimage.binary_fill_holes(clean_channel_areas)
Example #58
0
def get_d(image):
    '''
    Extracting etalons from image
    '''
    print 'Extracting...'
    max_cost = 0.2
    max_et = 100
    max_area = 30
    max_transform = 3

    image = rgb2gray(image)
    tresh = threshold_otsu(image)
    dt = []

    for it in xrange(max_transform):
        bi = image < tresh
        li = label(bi)
        print it
        for region in regionprops(li, ['Area', 'BoundingBox']):
            if region['Area'] < max_area:
                continue
            minr, minc, maxr, maxc = region['BoundingBox']
            imr = bi[minr:maxr, minc:maxc]
            imr = resize(imr, (30, 30))
            h = False
            for t in dt:
                if cost(imr, t) < max_cost:
                    h = True
                    break
            if h:
                continue
            else:
                dt.append(imr)
            if len(dt) >= max_et:
                return dt
        if it % 2:
            sx = 0.9 - (it + 0.0) / 10
            sy = 1.0 + (it + 0.0) / 11
            rt = 0.02 + (it + 0.0) * 0.01
        else:
            sx = 0.9 + (it + 0.0) / 10
            sy = 1.0 - (it + 0.0) / 11
            rt = -0.03 - (it + 0.0) * 0.015
        tform = AffineTransform(scale=(sx, sy), rotation=rt)
        image = warp(image, tform)
        print len(dt)
    return dt
Example #59
0
def otsu(img):
	rows,cols,depth=img.shape
	pixels=np.array([0 for x in range(256)])
	for i in range(0,rows):
		for j in range(0,cols):
			bright=img[i,j]
			pixels[bright]=pixels[bright]+1

	def w(k,pixels):
		sum=0
		for i in range(0,k):
			sum=pixels[i]
		return sum*1.0/(rows*cols)

	def u(k,pixels):
		sum=0
		for i in range(0,k):
			sum=i*pixels[i]
		return sum*1.0/(rows*cols)

	histoT, bin_edges=np.histogram(img,bins=range(256))
	histo=np.array(histoT)
	values_pixels=np.array([0 for i in range(256)])
	values_histo=np.array([0 for i in range(256)])


	for j in range(256):
		if w(j,pixels)==0: continue
		values_pixels[j]=(((u(255,pixels)*w(j,pixels))-u(j,pixels))**2)/((w(j,pixels))*(1-w(j,pixels)))
		if w(j,histo)==0: continue
		values_histo[j]=(((u(255,histo)*w(j,histo))-u(j,histo))**2)/((w(j,histo))*(1-w(j,histo)))

	threshold=np.argmax(values_pixels)
	print "threshold using pixels",threshold
	print "threshold using np.histogram",np.argmax(values_histo)

	from skimage.filter import threshold_otsu
	print "threshold using scikit" , np.floor(threshold_otsu(img))
	
	imgO=np.zeros((rows,cols),int)
	for i in range(cols):
		for j in range(rows):
			if img[i,j,0]>=threshold: 
				imgO[i,j]=255
			elif img[i,j,0]<threshold:
				imgO[i,j]=0
	return imgO