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


Python measure.label方法代码示例

本文整理汇总了Python中skimage.measure.label方法的典型用法代码示例。如果您正苦于以下问题:Python measure.label方法的具体用法?Python measure.label怎么用?Python measure.label使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在skimage.measure的用法示例。


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

示例1: debug_img

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def debug_img(img, bitmap, logistic_output):
  # create a debug image with three columns; 1) original RGB. 2) black/white
  # bitmap of labels 3) black/white bitmap of predictions (with centroids coloured
  # red.
  h, w, _channels = bitmap.shape
  canvas = Image.new('RGB', (w*3, h), (50, 50, 50))
  # original input image on left
  img = zero_centered_array_to_pil_image(img)
  img = img.resize((w, h))
  canvas.paste(img, (0, 0))
  # label bitmap in center
  canvas.paste(bitmap_to_pil_image(bitmap), (w, 0))
  # logistic output on right
  canvas.paste(bitmap_to_pil_image(logistic_output), (w*2, 0))
  # draw red dots on right hand side image corresponding to
  # final thresholded prediction
  draw = ImageDraw.Draw(canvas)
  for y, x in centroids_of_connected_components(logistic_output):
    draw.rectangle((w*2+x,y,w*2+x,y), fill='red')
  # finally draw blue lines between the three to delimit boundaries
  draw.line([w,0,w,h], fill='blue')
  draw.line([2*w,0,2*w,h], fill='blue')
  draw.line([3*w,0,3*w,h], fill='blue')
  # done
  return canvas 
开发者ID:matpalm,项目名称:bnn,代码行数:27,代码来源:util.py

示例2: centroids_of_connected_components

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def centroids_of_connected_components(bitmap, threshold=0.05, rescale=1.0):
  # TODO: don't do raw (binary) threshold; instead use P(y) as weighting for centroid
  #       e.g. https://arxiv.org/abs/1806.03413 sec 3.D
  #       update: this didn't help much :/ centroid weighted by intensities moved only up
  #       to a single pixel (guess centroids are already quite evenly dispersed)
  #       see https://gist.github.com/matpalm/20a3974ceb7f632f935285262fac4e98
  # TODO: hunt down the x/y swap between PIL and label db :/

  # threshold
  mask = bitmap > threshold
  bitmap = np.zeros_like(bitmap)
  bitmap[mask] = 1.0
  # calc connected components
  all_labels = measure.label(bitmap)
  # return centroids
  centroids = []
  for region in measure.regionprops(label_image=all_labels):
    cx, cy = map(lambda p: int(p*rescale), (region.centroid[0], region.centroid[1]))
    centroids.append((cx, cy))
  return centroids 
开发者ID:matpalm,项目名称:bnn,代码行数:22,代码来源:util.py

示例3: filter_cloudmask

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def filter_cloudmask(cloudmask, threshold=1, connectivity=1):
    """Filter a given cloudmask for small cloud objects defined by their pixel
    number. 
    
    Parameters:
        cloudmask (ndarray): 2d binary cloud mask (optional with NaNs).
        threshold (int): minimum pixel number of objects remaining in cloudmask.
        connectivity (int):  Maximum number of orthogonal hops to consider
            a pixel/voxel as a neighbor (see :func:`skimage.measure.label`).
    
    Return:
        ndarray: filtered cloudmask without NaNs.
    """
    cloudmask[np.isnan(cloudmask)] = 0
    labels = measure.label(cloudmask, connectivity=connectivity)
    props = measure.regionprops(labels)
    area = [prop.area for prop in props]

    # Find objects < threshold pixle number, get their labels, set them to 0-clear.
    smallclouds = [t[0] for t in filter(lambda a: a[1] < threshold, enumerate(area, 1))]
    for label in smallclouds:
        cloudmask[labels == label] = 0

    return cloudmask 
开发者ID:atmtools,项目名称:typhon,代码行数:26,代码来源:cloudstatistics.py

示例4: extend_nonforest

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def extend_nonforest(config, buffered_array, full_array):

   """ 
   After buffering forest, get changes that are spatially connected 
   to previous change or non-forest
   """

   # convert full array into connected labels
   ones_array = np.copy(full_array[0,:,:])
   ones_array[ones_array > 0] = 1
   ones_array[ones_array != 1] = 0

   label_image = label(ones_array, neighbors=8)
   labels = np.unique(label_image)

   for _label in labels:
	indices = np.where(label_image == _label)
        if ones_array[indices][0] > 0:
	    connected_parts = buffered_array[0,:,:][indices].sum()
	    if connected_parts > 0:
	        for i in range(full_array.shape[0]):
	            buffered_array[i,:,:][indices] = full_array[i,:,:][indices]

   return buffered_array 
开发者ID:bullocke,项目名称:coded,代码行数:26,代码来源:postprocess_utils.py

示例5: GetCC

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def GetCC(match1, match2, mask1, mask2, score) : 
	match1_arr = np.array(match1).astype(int)
	mask1[match1_arr[:, 0].flatten(), match1_arr[:, 1].flatten()] = 1
	label1, nb_label1 = measure.label(mask1, connectivity=2, return_num=True)
	dict_match = dict(zip(match1, match2))
	dict_score = dict(zip(match1, score))
	
	CC = []
	CC_score = np.zeros(nb_label1)
	for i in range(1, nb_label1 + 1) : 
		CC.append({})
		posx, posy = np.where(label1 == i)
		tmp_match1 = [(posx[j], posy[j]) for j in range(len(posx))]
		tmp_match2 = [dict_match[item] for item in tmp_match1]
		CC[i-1] = dict(zip(tmp_match1, tmp_match2))
		CC[i-1]['mask2shape'] = mask2.shape
		CC_score[i -1 ] = sum(dict_score[item] for item in tmp_match1)
	return CC, CC_score 
开发者ID:XiSHEN0220,项目名称:ArtMiner,代码行数:20,代码来源:outils.py

示例6: __init__

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def __init__(self, threshold=0.4, iou_range=(0.5, 1.0), ignore_index=-1, min_instance_size=None,
                 use_last_target=False):
        """
        :param threshold: probability value at which the input is going to be thresholded
        :param iou_range: compute ROC curve for the the range of IoU values: range(min,max,0.05)
        :param ignore_index: label to be ignored during computation
        :param min_instance_size: minimum size of the predicted instances to be considered
        :param use_last_target: if True use the last target channel to compute AP
        """
        self.threshold = threshold
        # always have well defined ignore_index
        if ignore_index is None:
            ignore_index = -1
        self.iou_range = iou_range
        self.ignore_index = ignore_index
        self.min_instance_size = min_instance_size
        self.use_last_target = use_last_target 
开发者ID:doublechenching,项目名称:brats_segmentation-pytorch,代码行数:19,代码来源:metrics_torch.py

示例7: _find_overlapping_target

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def _find_overlapping_target(self, predicted_label, predicted, target, min_iou):
        """
        Return ground truth label which overlaps by at least 'min_iou' with a given input label 'p_label'
        or None if such ground truth label does not exist.
        """
        mask_predicted = predicted == predicted_label
        overlapping_labels = target[mask_predicted]
        labels, counts = np.unique(overlapping_labels, return_counts=True)
        # retrieve the biggest overlapping label
        target_label_ind = np.argmax(counts)
        target_label = labels[target_label_ind]
        # return target label if IoU greater than 'min_iou'; since we're starting from 0.5 IoU there might be
        # only one target label that fulfill this criterion
        mask_target = target == target_label
        # return target_label if IoU > min_iou
        if self._iou(mask_predicted, mask_target) > min_iou:
            return target_label
        return None 
开发者ID:doublechenching,项目名称:brats_segmentation-pytorch,代码行数:20,代码来源:metrics_torch.py

示例8: _filter_instances

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def _filter_instances(self, input):
        """
        Filters instances smaller than 'min_instance_size' by overriding them with 'ignore_index'
        :param input: input instance segmentation
        :return: tuple: (instance segmentation with small instances filtered, set of unique labels without the 'ignore_index')
        """
        if self.min_instance_size is not None:
            labels, counts = np.unique(input, return_counts=True)
            for label, count in zip(labels, counts):
                if count < self.min_instance_size:
                    mask = input == label
                    input[mask] = self.ignore_index

        labels = set(np.unique(input))
        labels.discard(self.ignore_index)

        return input, labels 
开发者ID:doublechenching,项目名称:brats_segmentation-pytorch,代码行数:19,代码来源:metrics_torch.py

示例9: plot_regions

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def plot_regions(self, fill=True, bgimage=None, alpha=0.5):
        import pylab as pl
        ax = pl.gca()
        assert isinstance(ax, pl.Axes)

        colors = i12.JET_12

        self._plot_background(bgimage)

        for label in self.regions:
            color = colors[i12.LABELS.index(label)] / 255.

            for region in self.regions[label]:
                t = region['top']
                l = self.facade_left + region['left']
                b = region['bottom']
                r = self.facade_left + region['right']
                patch = pl.Rectangle((l, t), r - l, b - t, color=color, fill=fill, alpha=alpha)
                ax.add_patch(patch) 
开发者ID:jfemiani,项目名称:facade-segmentation,代码行数:21,代码来源:megafacade.py

示例10: DynamicWatershedAlias

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def DynamicWatershedAlias(p_img, lamb, p_thresh = 0.5):
    """
    Applies our dynamic watershed to 2D prob/dist image.
    """
    b_img = (p_img > p_thresh) + 0
    Probs_inv = PrepareProb(p_img)

    Hrecons = HreconstructionErosion(Probs_inv, lamb)
    markers_Probs_inv = find_maxima(Hrecons, mask = b_img)
    markers_Probs_inv = label(markers_Probs_inv)
    ws_labels = watershed(Hrecons, markers_Probs_inv, mask=b_img)
    arrange_label = ArrangeLabel(ws_labels)
    wsl = generate_wsl(arrange_label)
    arrange_label[wsl > 0] = 0
    
    return arrange_label

#### 
开发者ID:vqdang,项目名称:hover_net,代码行数:20,代码来源:dist.py

示例11: computeEvaluationMask

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def computeEvaluationMask(maskDIR, resolution, level):
    """Computes the evaluation mask.
    
    Args:
        maskDIR:    the directory of the ground truth mask
        resolution: Pixel resolution of the image at level 0
        level:      The level at which the evaluation mask is made
        
    Returns:
        evaluation_mask
    """
    slide = openslide.open_slide(maskDIR)
    dims = slide.level_dimensions[level]
    pixelarray = np.zeros(dims[0]*dims[1], dtype='uint')
    pixelarray = np.array(slide.read_region((0,0), level, dims))
    distance = nd.distance_transform_edt(255 - pixelarray[:,:,0])
    Threshold = 75/(resolution * pow(2, level) * 2) # 75µm is the equivalent size of 5 tumor cells
    binary = distance < Threshold
    filled_image = nd.morphology.binary_fill_holes(binary)
    evaluation_mask = measure.label(filled_image, connectivity = 2) 
    return evaluation_mask 
开发者ID:baidu-research,项目名称:NCRF,代码行数:23,代码来源:Evaluation_FROC.py

示例12: segment_body

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def segment_body (image, smooth=1, th=-300):
    blur = scipy.ndimage.filters.gaussian_filter(image, smooth, mode='constant')
    binary = np.array(blur < th, dtype=np.uint8)

    # body is a rough region covering human body
    body = np.zeros_like(binary)
    for i, sl in enumerate(binary):
        #H, W = sl.shape
        ll = measure.label(sl, background=1)   # connected components
        # biggest CC should be body
        pp = measure.regionprops(ll)
        boxes = [(x.area, x.bbox, x.filled_image) for x in pp if x.label != 0]  # label 0 is air
        boxes = sorted(boxes, key = lambda x: -x[0])
        if len(boxes) == 0:
            continue
        y0, x0, y1, x1 = boxes[0][1]
        body[i,y0:y1,x0:x1] = boxes[0][2]
        pass
    return body, None 
开发者ID:aaalgo,项目名称:plumo,代码行数:21,代码来源:mesh.py

示例13: keep_largest_connected_components

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def keep_largest_connected_components(mask):
    '''
    Keeps only the largest connected components of each label for a segmentation mask.
    '''

    out_img = np.zeros(mask.shape, dtype=np.uint8)

    for struc_id in [1, 2, 3]:

        binary_img = mask == struc_id
        blobs = measure.label(binary_img, connectivity=1)

        props = measure.regionprops(blobs)

        if not props:
            continue

        area = [ele.area for ele in props]
        largest_blob_ind = np.argmax(area)
        largest_blob_label = props[largest_blob_ind].label

        out_img[blobs == largest_blob_label] = struc_id

    return out_img 
开发者ID:baumgach,项目名称:acdc_segmenter,代码行数:26,代码来源:image_utils.py

示例14: convert_image_to_text

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def convert_image_to_text(path):
    img = cv2.imread(path, 0)
    new_mask = np.zeros(img.shape, dtype=np.uint8)
    im2, contours, hierarchy = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    print('Total contours: {}'.format(len(contours)))
    small_area = 0
    for c in contours:
        area = cv2.contourArea(c)
        # print(area)
        if area < 100:
            small_area += 1
            continue
        cv2.drawContours(new_mask, [c], 0, (255, 255, 255), -1)

    # show_resized_image(new_mask)
    arr = measure.label(new_mask, connectivity=1)
    str1 = rle(arr)
    # print(str1)
    # tmp_mask = np.zeros(img.shape, dtype=np.uint8)
    # tmp_mask[arr == 1] = 255
    # show_resized_image(tmp_mask)
    # print(arr.min(), arr.max())
    print('Small contours: {}'.format(small_area))
    return str1 
开发者ID:topcoderinc,项目名称:Urban3d,代码行数:26,代码来源:a50_create_submission.py

示例15: extractCornersFromSegmentation

# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import label [as 别名]
def extractCornersFromSegmentation(segmentation, cornerTypeRange=[0, 13]):
    from skimage import measure
    orientationPoints = []
    for heatmapIndex in xrange(cornerTypeRange[0], cornerTypeRange[1]):
        heatmap = segmentation == heatmapIndex
        #heatmap = cv2.dilate(cv2.erode(heatmap, kernel), kernel)
        components = measure.label(heatmap, background=0)
        points = []
        for componentIndex in xrange(components.min()+1, components.max() + 1):
            ys, xs = (components == componentIndex).nonzero()
            points.append((xs.mean(), ys.mean()))
            continue
        orientationPoints.append(points)
        continue
    return orientationPoints

#Extract corners from heatmaps 
开发者ID:art-programmer,项目名称:FloorNet,代码行数:19,代码来源:utils.py


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