当前位置: 首页>>代码示例>>Python>>正文


Python filter.threshold_otsu函数代码示例

本文整理汇总了Python中skimage.filter.threshold_otsu函数的典型用法代码示例。如果您正苦于以下问题:Python threshold_otsu函数的具体用法?Python threshold_otsu怎么用?Python threshold_otsu使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了threshold_otsu函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: adaptive_none

	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
开发者ID:munjo5746,项目名称:algorithm,代码行数:35,代码来源:otsu.py

示例2: main

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)
开发者ID:schwarrx,项目名称:imsense,代码行数:55,代码来源:sandia_chiplet.py

示例3: generate_template

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
开发者ID:kir-dan,项目名称:cv_intro_2014,代码行数:12,代码来源:recognition.py

示例4: robertCross

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
开发者ID:arnaghosh,项目名称:python_IP,代码行数:13,代码来源:Chapter4_edge.py

示例5: scikit_otsu

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
开发者ID:arunpatro,项目名称:computer_vision,代码行数:13,代码来源:pointwise.py

示例6: percent_vert_horiz_lines

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
开发者ID:kaylanb,项目名称:FoodvSkin,代码行数:13,代码来源:K_Features_NBlobs_RegAbg.py

示例7: ifcb_segment

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)
开发者ID:LouisK130,项目名称:oii,代码行数:14,代码来源:mock_blob.py

示例8: plot_preprocessed_image

 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()       
开发者ID:DataFighter,项目名称:ImageTextRecognition,代码行数:29,代码来源:userimageski.py

示例9: one_file_features

    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
开发者ID:mjirik,项目名称:ZDO14nedvedj,代码行数:34,代码来源:zdo.py

示例10: __transform

    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]
开发者ID:glesio,项目名称:visaocomputacional,代码行数:26,代码来源:contorno.py

示例11: scikit_example_plot_label

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()
开发者ID:bchoatejr,项目名称:math,代码行数:32,代码来源:image_label.py

示例12: label_stack

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
开发者ID:glyg,项目名称:scikit-tracker,代码行数:34,代码来源:nuclei_detector.py

示例13: threshold_image

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
开发者ID:runstadler-lab,项目名称:Seal-H3N8-Image-Analysis,代码行数:32,代码来源:rgprocessing.py

示例14: variance_otsu

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
开发者ID:charlienewey,项目名称:penumbra-python,代码行数:25,代码来源:colour.py

示例15: watershed_3d

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
开发者ID:DiamondLightSource,项目名称:auto_tomo_calibration-experimental,代码行数:32,代码来源:Segmentation.py


注:本文中的skimage.filter.threshold_otsu函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。