How to use the skimage.measure.label function in skimage

To help you get started, we’ve selected a few skimage examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github scikit-image / scikit-image / skimage / morphology / attribute.py View on Github external
>>> closed = attribute.diameter_closing(f, 3, connectivity=1)

    The small (but deep) dark objects are removed, except for the longest one.
    """

    if mask is not None and mask.shape != image.shape:
        raise ValueError("mask must have same shape as image")
    if mask is None:
        # Use a complete `True` mask if none is provided
        mask = np.ones(image.shape, bool)

    neighbors, offset = _validate_connectivity(image.ndim, connectivity,
                                               offset=None)

    seeds_bin = local_minima(image, selem=neighbors)
    seeds = label(seeds_bin, connectivity=connectivity).astype(np.uint64)
    output = image.copy()

    image = np.pad(image, 1, mode='constant')
    mask = np.pad(mask, 1, mode='constant')
    seeds = np.pad(seeds, 1, mode='constant')
    output = np.pad(output, 1, mode='constant')

    flat_neighborhood = _compute_neighbors(image, neighbors, offset)
    image_strides = np.array(image.strides, dtype=np.int32) // image.itemsize

    _attribute.diameter_closing(image.ravel(),
                                diameter_threshold,
                                seeds.ravel(),
                                flat_neighborhood,
                                mask.ravel().astype(np.uint8),
                                image_strides,
github mpicbg-csbd / stardist / tests / _old_test_all.py View on Github external
def random_image(shape=(128,128)):
    from skimage.measure import label
    from skimage.morphology import binary_closing, binary_opening
    from skimage.morphology import disk
    img = np.random.normal(size=shape)
    img = img > -0.7
    img = binary_opening(img,disk(2))
    img = binary_closing(img,disk(1))
    img = label(img)
    return img
github SpaceNetChallenge / SpaceNet_Off_Nadir_Solutions / XD_XD / main.py View on Github external
y_pred_avg = np.zeros((900, 900), dtype=np.float32)

            imageid = name.lstrip('Pan-Sharpen_').rstrip('.tif')
            for model_name in model_names:
                # Prediction mask
                prefix = '_'.join(model_name.split('_')[:2])
                pred_mask_dir = f'/wdata/models/{prefix}/test_{model_name}/'
                y_pred = np.array(ss.load_npz(
                    str(Path(pred_mask_dir) / Path(f'{imageid}.npz'))
                ).todense() / 255.0)
                y_pred_avg += y_pred
            y_pred_avg /= len(model_names)

            # Remove small objects
            y_pred = (y_pred_avg > 0.5)
            y_pred_label = skimage.measure.label(y_pred)

            nadir_angle = int(imageid.split('_')[1].lstrip('nadir'))

            min_area_thresh = 200
            if nadir_angle <= 25:
                min_area_thresh = 150
            if nadir_angle <= 40 and nadir_angle > 25:
                min_area_thresh = 200
            if nadir_angle > 40:
                min_area_thresh = 250

            for lbl_idx in np.unique(y_pred_label):
                if (y_pred_label == lbl_idx).sum() < min_area_thresh:
                    y_pred_label[y_pred_label == lbl_idx] = 0

            # to_summary
github wikke / Tianchi-Medical-LungTumorDetect / preprocess.py View on Github external
if DEBUG_PLOT_WHEN_PREPROCESSING:
        plot_slices(img, 'origin')

    # binary
    img = img < BINARY_THRESHOLD
    if DEBUG_PLOT_WHEN_PREPROCESSING:
        plot_slices(img, 'binary')

    # clear_border
    for c in range(img.shape[2]):
        img[:, :, c] = segmentation.clear_border(img[:, :, c])
    if DEBUG_PLOT_WHEN_PREPROCESSING:
        plot_slices(img, 'clear_border')

    # keep 2 lagest connected graph
    labels = measure.label(img)
    regions = measure.regionprops(labels)
    labels = [(r.area, r.label) for r in regions]

    if len(labels) > 2:
        labels.sort(reverse=True)
        max_area = labels[2][0]

        for r in regions:
            if r.area < max_area:
                for c in r.coords:
                    img[c[0], c[1], c[2]] = 0
    if DEBUG_PLOT_WHEN_PREPROCESSING:
        plot_slices(img, 'keep 2 lagest connected graph')

    # erosion
    # img = morphology.erosion(img, selem=np.ones((2, 2, 2)))
github KChen89 / Cell-Nuclei-Detection-and-Segmentation / util / util.py View on Github external
def draw_individual_edge(mask):
	v,h=mask.shape
	edge=np.zeros([v,h])
	individual_mask=label(mask, connectivity=2)
	for index in np.unique(individual_mask):
		if index==0:
			continue
		temp_mask=np.copy(individual_mask)
		temp_mask[temp_mask!=index]=0
		temp_mask[temp_mask==index]=1
		temp_mask=dilation(temp_mask, square(3))
		temp_edge=cv2.Canny(temp_mask.astype(np.uint8), 2,5)/255
		edge+=temp_edge
	return np.clip(edge, a_min=0, a_max=1).astype(np.uint8)
github yijingru / ANCIS-Pytorch / dec_utils / dec_dataset_kaggle.py View on Github external
def load_gt_kaggle(annoDir):
    bboxes = []
    labels = []
    files = os.listdir(annoDir)
    for anno_file in files:
        mask = cv2.imread(os.path.join(annoDir, anno_file), -1)
        labelImg = label(np.where(mask>0, 1., 0.))
        props = regionprops(labelImg)
        props = sorted(props, key=lambda x: x.area, reverse=True)
        r,c = np.where(labelImg==props[0].label)
        y1 = np.min(r)
        x1 = np.min(c)
        y2 = np.max(r)
        x2 = np.max(c)
        if (abs(y2 - y1) <= 1 or abs(x2 - x1) <= 1):
            continue
        bboxes.append([y1, x1, y2, x2])
        labels.append([1])
    return bboxes, labels
github femioladeji / License-Plate-Recognition-Nigerian-vehicles / preprocess.py View on Github external
The plate dimensions were based on the following characteristics
        i.  They are rectangular in shape.
        ii. The width is more than the height
        iii. The ratio of the width to height is approximately 2:1
        iv. The proportion of the width of the license plate region to the 
        full image ranges between 15% to 40% depending on how the car image 
        was taken
        v.  The proportion of the height of the license plate region to the 
        full image is between 8% to 20%

        Return:
        --------
        3-D Array of license plate candidates region

        """
        self.label_image = measure.label(self.binary_image)
        self.plate_objects_cordinates = []
        threshold = self.binary_image
        plate_dimensions = (0.08*threshold.shape[0], 0.2*threshold.shape[0], 0.15*threshold.shape[1], 0.4*threshold.shape[1])
        minHeight, maxHeight, minWidth, maxWidth = plate_dimensions
        plate_like_objects = []
        for region in regionprops(self.label_image):
            if region.area < 10:
                continue
        
            minimumRow, minimumCol, maximumRow, maximumCol = region.bbox
            regionHeight = maximumRow - minimumRow
            regionWidth = maximumCol - minimumCol
            if regionHeight >= minHeight and regionHeight <= maxHeight and regionWidth >= minWidth and regionWidth <= maxWidth and regionWidth > regionHeight:
                plate_like_objects.append(self.full_car_image[minimumRow:maximumRow,
                    minimumCol:maximumCol])
                self.plate_objects_cordinates.append((minimumRow, minimumCol,
github DeepinSC / PyTorch-Luna16 / data_processing / LUNA_code / classify_nodes.py View on Github external
def getRegionFromMap(slice_npy):
    thr = np.where(slice_npy > np.mean(slice_npy), 0., 1.0)
    label_image = label(thr)
    labels = label_image.astype(int)
    regions = regionprops(labels)
    return regions
github byungsook / vectornet / vectorize_local.py View on Github external
unique_label = np.unique(labels)
    num_path_pixels = len(pm.path_pixels[0])

    new_label = FLAGS.max_num_labels
    for i in unique_label:
        i_label_list = np.nonzero(labels == i)

        # handle duplicated pixels
        for j, i_label in enumerate(i_label_list[0]):
            if i_label >= num_path_pixels:
                i_label_list[0][j] = pm.dup_rev_dict[i_label]

        # connected component analysis on 'i' label map
        i_label_map = np.zeros([FLAGS.image_height, FLAGS.image_width], dtype=np.float)
        i_label_map[pm.path_pixels[0][i_label_list],pm.path_pixels[1][i_label_list]] = 1.0
        cc_map, num_cc = skimage.measure.label(i_label_map, background=0, return_num=True)

        if num_cc > 1:
            for i_label in i_label_list[0]:
                cc_label = cc_map[pm.path_pixels[0][i_label],pm.path_pixels[1][i_label]]
                if cc_label > 1:
                    labels[i_label] = new_label + (cc_label-2)

            new_label += (num_cc - 1)

    return labels