本文整理汇总了Python中scipy.ndimage.measurements.label方法的典型用法代码示例。如果您正苦于以下问题:Python measurements.label方法的具体用法?Python measurements.label怎么用?Python measurements.label使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块scipy.ndimage.measurements
的用法示例。
在下文中一共展示了measurements.label方法的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: connected_components_reference_implementation
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def connected_components_reference_implementation(images):
try:
from scipy.ndimage import measurements
except ImportError:
logging.exception("Skipping test method because scipy could not be loaded")
return
image_or_images = np.asarray(images)
if len(image_or_images.shape) == 2:
images = image_or_images[None, :, :]
elif len(image_or_images.shape) == 3:
images = image_or_images
components = np.asarray([measurements.label(image)[0] for image in images])
# Get the count of nonzero ids for each image, and offset each image's nonzero
# ids using the cumulative sum.
num_ids_per_image = components.reshape(
[-1, components.shape[1] * components.shape[2]]
).max(axis=-1)
positive_id_start_per_image = np.cumsum(num_ids_per_image)
for i in range(components.shape[0]):
new_id_start = positive_id_start_per_image[i - 1] if i > 0 else 0
components[i, components[i] > 0] += new_id_start
if len(image_or_images.shape) == 2:
return components[0, :, :]
else:
return components
示例2: _filter_grouplen
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def _filter_grouplen(arr, minsize=3):
"""Filter out the groups of grid points smaller than minsize
Parameters
----------
arr : the array to filter (should be False and Trues)
minsize : the minimum size of the group
Returns
-------
the array, with small groups removed
"""
# Do it with trues
r, nr = label(arr)
nr = [i+1 for i, o in enumerate(find_objects(r)) if (len(r[o]) >= minsize)]
arr = np.asarray([ri in nr for ri in r])
# and with Falses
r, nr = label(~ arr)
nr = [i+1 for i, o in enumerate(find_objects(r)) if (len(r[o]) >= minsize)]
arr = ~ np.asarray([ri in nr for ri in r])
return arr
示例3: _fix_mirror_padding
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def _fix_mirror_padding(self, ann):
"""
Deal with duplicated instances due to mirroring in interpolation
during shape augmentation (scale, rotation etc.)
"""
current_max_id = np.amax(ann)
inst_list = list(np.unique(ann))
inst_list.remove(0) # 0 is background
for inst_id in inst_list:
inst_map = np.array(ann == inst_id, np.uint8)
remapped_ids = measurements.label(inst_map)[0]
remapped_ids[remapped_ids > 1] += current_max_id
ann[remapped_ids > 1] = remapped_ids[remapped_ids > 1]
current_max_id = np.amax(ann)
return ann
####
示例4: greedy_decoder
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def greedy_decoder(outputs: np.ndarray) -> List[Tuple[int, int, int, float]]:
"""
Translates back the network output to a label sequence using greedy/best
path decoding as described in [0].
[0] Graves, Alex, et al. "Connectionist temporal classification: labelling
unsegmented sequence data with recurrent neural networks." Proceedings of
the 23rd international conference on Machine learning. ACM, 2006.
Args:
output (numpy.array): (C, W) shaped softmax output tensor
Returns:
A list with tuples (class, start, end, max). max is the maximum value
of the softmax layer in the region.
"""
labels = np.argmax(outputs, 0)
seq_len = outputs.shape[1]
mask = np.eye(outputs.shape[0], dtype='bool')[labels].T
classes = []
for label, group in groupby(zip(np.arange(seq_len), labels, outputs[mask]), key=lambda x: x[1]):
lgroup = list(group)
if label != 0:
classes.append((label, lgroup[0][0], lgroup[-1][0], max(x[2] for x in lgroup)))
return classes
示例5: label
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def label(image: np.array, **kw) -> np.array:
"""
Redefine the scipy.ndimage.measurements.label function to work with a wider
range of data types. The default function is inconsistent about the data
types it accepts on different platforms.
"""
try:
return measurements.label(image, **kw)
except Exception:
pass
types = ["int32", "uint32", "int64", "uint64", "int16", "uint16"]
for t in types:
try:
return measurements.label(np.array(image, dtype=t), **kw)
except Exception:
pass
# let it raise the same exception as before
return measurements.label(image, **kw)
示例6: propagate_labels
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def propagate_labels(image, labels, conflict=0):
"""Given an image and a set of labels, apply the labels
to all the regions in the image that overlap a label.
Assign the value `conflict` to any labels that have a conflict."""
rlabels, _ = label(image)
cors = correspondences(rlabels, labels)
outputs = np.zeros(np.amax(rlabels) + 1, 'i')
oops = -(1 << 30)
for o, i in cors.T:
if outputs[o] != 0:
outputs[o] = oops
else:
outputs[o] = i
outputs[outputs == oops] = conflict
outputs[0] = 0
return outputs[rlabels]
示例7: _remove_blobs
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def _remove_blobs(data):
"""Remove false positive blobs, likely occuring in brain sections."""
labeled_obj, num_obj = label(data)
if num_obj > 1: # If there is more than one connected object
bigger_obj = (labeled_obj == (np.bincount(labeled_obj.flat)[1:].argmax() + 1))
data2clean = np.copy(data)
# remove blobs only above the bigger connected object
z_max = np.max(np.where(bigger_obj)[2])
data2clean[:, :, :z_max + 1] = 0
labeled_obj2clean, num_obj2clean = label(data2clean)
if num_obj2clean: # If there is connected object above the biffer connected one
for obj_id in range(1, num_obj2clean + 1):
# if the blob has a volume < 10% of the bigger connected object, then remove it
if np.sum(labeled_obj2clean == obj_id) < 0.1 * np.sum(bigger_obj):
logger.warning('Removing small objects above slice #' + str(z_max))
data[np.where(labeled_obj2clean == obj_id)] = 0
return data
示例8: get_n_largest_components
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def get_n_largest_components(vol, se, n, return_sizes=False):
"""Get the n largest components from a volume.
PARAMETERS
----------
vol : ndarray
Image volume. A dimX x dimY x dimZ array containing the image data.
se : ndarray
Structuring element to use when detecting components (i.e. setting the
connectivity which defines a component).
n : int
Number of (largest) components to retain.
return_sizes : bool, optional
Whether or not to also return the sizes (in voxels) of each component
that was retained (default = False).
RETURNS
----------
Components : ndarray
Binary dimX x dimY x dimZ array where entries corresponding to retained
components are True and the remaining entries are False.
"""
vol_lbl = label(vol,se)[0]
labels,region_size = np.unique(vol_lbl,return_counts=True)
labels = labels[1:] # disregard background (label=0)
region_size = region_size[1:] #
labels = labels[ np.argsort(region_size)[::-1]]
components = np.any(np.array([vol_lbl == i for i in labels[:n]]),
axis=0)
# if no components are found, components will be reduced to false. Replace
# by array of appropriate size
if components.sum() == 0:
components = np.zeros_like(vol, dtype=bool)
if return_sizes:
return components,region_size[labels[:n]]
else:
return components
示例9: get_large_components
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def get_large_components(vol, se, threshold):
"""Get the components larger than a given threshold from a volume.
PARAMETERS
----------
vol : ndarray
Image volume. A dimX x dimY x dimZ array containing the image data.
se : ndarray
Structuring element to use when detecting components (i.e. setting the
connectivity which defines a component).
threshold : float
Only components (strictly) larger than this value (# of voxels) are
retained.
RETURNS
----------
components : ndarray
Binary dimX x dimY x dimZ array where entries corresponding to retained
components are True and the remaining entries are False.
"""
vol_lbl = label(vol,se)[0]
labels, region_size = np.unique(vol_lbl,return_counts=True)
labels = labels[1:] # disregard background (label=0)
region_size = region_size[1:]
components = np.any(np.array([vol_lbl == i for i in labels[region_size > threshold]]),
axis=0)
# if no components are found, components will be reduced to false. Replace
# by array of appropriate size
if components.sum() == 0:
components = np.zeros_like(vol, dtype=bool)
return components
示例10: relabel_compartments
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def relabel_compartments(mesh, old, new):
"""Relabel elements belonging to compartment 'old' (as defined by tag1 and
tag2 fields) to compartment 'new' of a .msh file. If 'old' and 'new' are
lists of indices then they are zipped such that relabelling is from old[0]
to new[0], from old[1] to new[1] etc.
PARAMETERS
----------
mesh : str or mesh_io msh object
The mesh whose elements are relabelled.
old : int or list of ints
Old label.
new : int or list of ints
New label.
RETURNS
----------
mesh : mesh_io msh object
The modified input object.
"""
if type(mesh) == str:
mesh = mesh_io.read_msh(mesh)
# ensure iterable
try:
next(iter(old))
except TypeError:
old = [old]
try:
next(iter(new))
except TypeError:
new = [new]
# renumber
for iold, inew in zip(old,new):
mesh.elm.tag1[mesh.elm.tag1 == iold] = inew
mesh.elm.tag2[mesh.elm.tag2 == iold] = inew
return mesh
示例11: vmesh2nifti
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def vmesh2nifti(mesh, vol, filename):
"""Given a volume mesh and an image file (e.g., .nii file), determine which
voxels in vol are inside which elements of the mesh and label according to
the values found in mesh.elm.tag1.
PARAMETERS
----------
mesh : str or mesh_io volume mesh object
Object describing the volume mesh.
vol : str or nibabel image object
Reference volume. The output volume is similar to this with respect to
image dimensions, voxel size etc. only with voxel values being replaced
by corresponding values of the labels of the tetrahedra in the mesh.
filename : str
Name of the saved volume.
RETURNS
----------
Nothing, saves a nifti file by the name of filename to disk.
"""
if type(mesh) == str:
mesh = mesh_io.read_msh(mesh)
if type(vol) == str:
vol = nib.load(vol)
img_dims = vol.shape
points = np.array(np.meshgrid(*tuple(map(np.arange,img_dims)),
indexing="ij")).reshape((3,-1)).T
tetrahedra = mesh.nodes.node_coord[mesh.elm.node_number_list[mesh.elm.elm_type==4]-1]
tetrahedra_regions = mesh.elm.tag1[mesh.elm.elm_type==4]
tetrahedra = apply_affine(tetrahedra, np.linalg.inv(vol.affine))
labels = label_points(tetrahedra, points, tetrahedra_regions)
write_nifti(labels.reshape(img_dims), filename, vol, dtype=np.uint8,
return_volume=False)
示例12: tf_categorical_dice
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def tf_categorical_dice(pred, truth, k):
""" Dice overlap metric for label k """
A = tf.cast(tf.equal(pred, k), dtype=tf.float32)
B = tf.cast(tf.equal(truth, k), dtype=tf.float32)
return 2 * tf.reduce_sum(tf.multiply(A, B)) / (tf.reduce_sum(A) + tf.reduce_sum(B))
示例13: data_augmenter
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def data_augmenter(image, label, shift, rotate, scale, intensity, flip):
"""
Online data augmentation
Perform affine transformation on image and label,
which are 4D tensor of shape (N, H, W, C) and 3D tensor of shape (N, H, W).
"""
image2 = np.zeros(image.shape, dtype=np.float32)
label2 = np.zeros(label.shape, dtype=np.int32)
for i in range(image.shape[0]):
# For each image slice, generate random affine transformation parameters
# using the Gaussian distribution
shift_val = [np.clip(np.random.normal(), -3, 3) * shift,
np.clip(np.random.normal(), -3, 3) * shift]
rotate_val = np.clip(np.random.normal(), -3, 3) * rotate
scale_val = 1 + np.clip(np.random.normal(), -3, 3) * scale
intensity_val = 1 + np.clip(np.random.normal(), -3, 3) * intensity
# Apply the affine transformation (rotation + scale + shift) to the image
row, col = image.shape[1:3]
M = cv2.getRotationMatrix2D((row / 2, col / 2), rotate_val, 1.0 / scale_val)
M[:, 2] += shift_val
for c in range(image.shape[3]):
image2[i, :, :, c] = ndimage.interpolation.affine_transform(image[i, :, :, c],
M[:, :2], M[:, 2], order=1)
# Apply the affine transformation (rotation + scale + shift) to the label map
label2[i, :, :] = ndimage.interpolation.affine_transform(label[i, :, :],
M[:, :2], M[:, 2], order=0)
# Apply intensity variation
image2[i] *= intensity_val
# Apply random horizontal or vertical flipping
if flip:
if np.random.uniform() >= 0.5:
image2[i] = image2[i, ::-1, :, :]
label2[i] = label2[i, ::-1, :]
else:
image2[i] = image2[i, :, ::-1, :]
label2[i] = label2[i, :, ::-1]
return image2, label2
示例14: np_categorical_dice
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def np_categorical_dice(pred, truth, k):
""" Dice overlap metric for label k """
A = (pred == k).astype(np.float32)
B = (truth == k).astype(np.float32)
return 2 * np.sum(A * B) / (np.sum(A) + np.sum(B))
示例15: get_largest_cc
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def get_largest_cc(binary):
""" Get the largest connected component in the foreground. """
cc, n_cc = measure.label(binary)
max_n = -1
max_area = 0
for n in range(1, n_cc + 1):
area = np.sum(cc == n)
if area > max_area:
max_area = area
max_n = n
largest_cc = (cc == max_n)
return largest_cc
示例16: label_regions
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def label_regions(math_regions, image):
labeled = np.zeros(image.shape[:2])
math_regions = math_regions[math_regions[:, 4].argsort()]
for label, math_region in enumerate(math_regions):
labeled[math_region[1]:math_region[3], math_region[0]:math_region[2]] = label
#uniq_labels = np.unique(labeled)
return labeled
示例17: clustering
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def clustering(math_regions, char_data, image, algorithm, thresh_votes):
centers = []
for math_region in math_regions:
center = [(math_region[0]+math_region[2])/2, (math_region[1]+math_region[3])/2]
centers.append(center)
clustering = AgglomerativeClustering().fit(centers)
labels = np.unique(clustering.labels_)
for label in labels:
regions = math_regions[labels==label]
pass
示例18: find_blank_rows
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def find_blank_rows(image, line_spacing=1):
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blank_rows = np.all(gray_image == 255, axis=1)
im_bw = np.zeros(gray_image.shape)
im_bw[blank_rows] = 255
#gray_image[~blank_rows] = 0
#cv2.imwrite("/home/psm2208/code/eval/test.png", im_bw)
labeled, ncomponents = ndimage.label(im_bw)
rows = []
indices = np.indices(im_bw.shape).T[:, :, [1, 0]]
line_bbs = ndimage.find_objects(labeled)
sizes = np.array([[bb.stop - bb.start for bb in line_bb]
for line_bb in line_bbs])
sizes = sizes[:,0]
mask = (sizes > line_spacing)
idx = np.flatnonzero(mask)
for i in idx:
labels = (labeled == (i+1))
pixels = indices[labels.T]
box = [min(pixels[:, 0]), min(pixels[:, 1]), max(pixels[:, 0]), max(pixels[:, 1])]
rows.append(box)
return rows
示例19: findVerticalAlternative
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def findVerticalAlternative(self):
# This is an alternative method, a bit more expensive
# than the first version, and is called on failure of
# the previous findVertical. It uses Scipy labelling to segment the a strip
# of data from the ROI
self.found = False
cx = self.ROIwh[0]//2
expectedW, expectedH = self.expectedSize
win = (expectedW - (expectedW*self.sizeMargin) )//2
#take a vertical section of pixels from the ROI and threshold it
vROI = self.ROIimg[:,cx-win:cx+win]
#Make a single pixel wide strip, with the median of all the rows
vROI = np.median(vROI,axis=1)
threshVal = int(vROI.max() * self.thresholdVal)
vROIthres = vROI >= threshVal
candidate = None
if vROIthres.min() != vROIthres.max():
# Prevent a divide by zero because roi is all the same value.
# e.g. we have a frame completely white or black
lbl,numLbl = nd.label(vROIthres)
obj = nd.find_objects(lbl)
brightest = 0
for s in obj:
print s
# s is an np.slice object
sBright = np.mean(vROI[s])
sHeight = s[0].stop - s[0].start
if (self.heightRange[0] <= sHeight <= self.heightRange[1]) and sBright > brightest:
candidate = s[0]
brightest = sBright
if candidate:
self.setPerfPosition( self.ROIcentrexy[0], self.ROIxy[1]+candidate.start + ((candidate.stop-candidate.start)/2 ))
self.found = True
示例20: decompose_vol2cube_brain
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def decompose_vol2cube_brain(vol_data, cube_size, n_chn, ita):
cube_list = []
fold, ovlap = fit_cube_param(vol_data.shape[0:3], cube_size, ita)
dim = np.asarray(vol_data.shape[0:3]) # [307, 307, 143]
# decompose
for R in range(0, fold[0]):
r_s = R * cube_size - R * ovlap[0]
r_e = r_s + cube_size
if r_e >= dim[0]: # see if exceed the boundry
r_s = dim[0] - cube_size
r_e = r_s + cube_size
for C in range(0, fold[1]):
c_s = C * cube_size - C * ovlap[1]
c_e = c_s + cube_size
if c_e >= dim[1]:
c_s = dim[1] - cube_size
c_e = c_s + cube_size
for H in range(0, fold[2]):
h_s = H * cube_size - H * ovlap[2]
h_e = h_s + cube_size
if h_e >= dim[2]:
h_s = dim[2] - cube_size
h_e = h_s + cube_size
# partition multiple channels
cube_temp = vol_data[r_s:r_e, c_s:c_e, h_s:h_e, :]
# By default batch_size = 1
cube_batch = np.zeros(
[1, cube_size, cube_size, cube_size, n_chn]).astype('float32')
cube_batch[0, :, :, :, :] = copy.deepcopy(cube_temp)
# save
cube_list.append(cube_batch)
return cube_list
# compose list of label cubes into a label volume
示例21: remove_minor_cc
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def remove_minor_cc(vol_data, rej_ratio, rename_map):
"""Remove small connected components refer to rejection ratio"""
"""Usage
# rename_map = [0, 205, 420, 500, 550, 600, 820, 850]
# nii_path = '/home/xinyang/project_xy/mmwhs2017/dataset/ct_output/test/test_4.nii'
# vol_file = nib.load(nii_path)
# vol_data = vol_file.get_data().copy()
# ref_affine = vol_file.affine
# rem_vol = remove_minor_cc(vol_data, rej_ratio=0.2, class_n=8, rename_map=rename_map)
# # save
# rem_path = 'rem_cc.nii'
# rem_vol_file = nib.Nifti1Image(rem_vol, ref_affine)
# nib.save(rem_vol_file, rem_path)
#===# possible be parallel in future
"""
rem_vol = copy.deepcopy(vol_data)
class_n = len(rename_map)
# retrieve all classes
for c in range(1, class_n):
print('processing class %d...' % c)
class_idx = (vol_data == rename_map[c]) * 1
class_vol = np.sum(class_idx)
labeled_cc, num_cc = measurements.label(class_idx)
# retrieve all connected components in this class
for cc in range(1, num_cc + 1):
single_cc = ((labeled_cc == cc) * 1)
single_vol = np.sum(single_cc)
# remove if too small
if single_vol / (class_vol * 1.0) < rej_ratio:
rem_vol[labeled_cc == cc] = 0
return rem_vol
示例22: _is_contiguous
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def _is_contiguous(self, arr):
_, num_features = scipy_label(arr)
return num_features == 1
示例23: get_components
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def get_components(inputs, batch=True):
""" Find connected components """
coords = []
num_items = len(inputs) if batch else 1
for i in range(num_items):
connected_array, num_components = measurements.label(inputs[i], output=None)
comps = []
for j in range(num_components):
c = np.where(connected_array == (j + 1))
comps.append(c)
coords.append(comps)
return coords if batch else coords[0]
示例24: _filter_small_slopes
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def _filter_small_slopes(hgt, dx, min_slope=0):
"""Masks out slopes with NaN until the slope if all valid points is at
least min_slope (in degrees).
"""
min_slope = np.deg2rad(min_slope)
slope = np.arctan(-np.gradient(hgt, dx)) # beware the minus sign
# slope at the end always OK
slope[-1] = min_slope
# Find the locs where it doesn't work and expand till we got everything
slope_mask = np.where(slope >= min_slope, slope, np.NaN)
r, nr = label(~np.isfinite(slope_mask))
for objs in find_objects(r):
obj = objs[0]
i = 0
while True:
i += 1
i0 = objs[0].start-i
if i0 < 0:
break
ngap = obj.stop - i0 - 1
nhgt = hgt[[i0, obj.stop]]
current_slope = np.arctan(-np.gradient(nhgt, ngap * dx))
if i0 <= 0 or current_slope[0] >= min_slope:
break
slope_mask[i0:obj.stop] = np.NaN
out = hgt.copy()
out[~np.isfinite(slope_mask)] = np.NaN
return out
示例25: proc_np_dist
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def proc_np_dist(pred):
"""
Process Nuclei Prediction with Distance Map
Args:
pred: prediction output, assuming
channel 0 contain probability map of nuclei
channel 1 containing the regressed distance map
"""
blb_raw = pred[...,0]
dst_raw = pred[...,1]
blb = np.copy(blb_raw)
blb[blb > 0.5] = 1
blb[blb <= 0.5] = 0
blb = measurements.label(blb)[0]
blb = remove_small_objects(blb, min_size=10)
blb[blb > 0] = 1
dst_raw[dst_raw < 0] = 0
dst = np.copy(dst_raw)
dst = dst * blb
dst[dst > 0.5] = 1
dst[dst <= 0.5] = 0
marker = dst.copy()
marker = binary_fill_holes(marker)
marker = measurements.label(marker)[0]
marker = remove_small_objects(marker, min_size=10)
proced_pred = watershed(-dst_raw, marker, mask=blb)
return proced_pred
####
示例26: draw_bboxes
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def draw_bboxes(img, heatmap_buffer, heatmap_pre, N_buffer):
heatmap_buffer.append(heatmap_pre)
if len(heatmap_buffer) > N_buffer: # remove the first component if it is more than N_buffer elements
heatmap_buffer.pop(0)
# weight the heatmap based on current frame and previous N frames
idxs = range(N_buffer)
for b, w, idx in zip(heatmap_buffer, buffer_weights, idxs):
heatmap_buffer[idx] = b * w
heatmap = np.sum(np.array(heatmap_buffer), axis=0)
heatmap = apply_threshold( heatmap, threshold= sum(buffer_weights[0:N_buffer])*2)
# Find final boxes from heatmap using label function
labels = label(heatmap)
bboxes = []
# locate the bounding box
for car_number in range(1, labels[1]+1):
# Find pixels with each car_number label value
nonzero = (labels[0] == car_number).nonzero()
# Identify x and y values of those pixels
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Define a bounding box based on min/max x and y
bbox_tmp = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))
bboxes.append(bbox_tmp)
for bbox in bboxes:
# Draw the box on the image
cv2.rectangle(img, bbox[0], bbox[1], (0,0,255), 4)
# Return the image
return img, heatmap, bboxes
示例27: blank_threshold_decoder
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def blank_threshold_decoder(outputs: np.ndarray, threshold: float = 0.5) -> List[Tuple[int, int, int, float]]:
"""
Translates back the network output to a label sequence as the original
ocropy/clstm.
Thresholds on class 0, then assigns the maximum (non-zero) class to each
region.
Args:
output (numpy.array): (C, W) shaped softmax output tensor
threshold (float): Threshold for 0 class when determining possible
label locations.
Returns:
A list with tuples (class, start, end, max). max is the maximum value
of the softmax layer in the region.
"""
outputs = outputs.T
labels, n = measurements.label(outputs[:, 0] < threshold)
mask = np.tile(labels.reshape(-1, 1), (1, outputs.shape[1]))
maxima = measurements.maximum_position(outputs, mask, np.arange(1, np.amax(mask)+1))
p = 0
start = None
x = []
for idx, val in enumerate(labels):
if val != 0 and start is None:
start = idx
p += 1
if val == 0 and start is not None:
if maxima[p-1][1] == 0:
start = None
else:
x.append((maxima[p-1][1], start, idx, outputs[maxima[p-1]]))
start = None
# append last non-zero region to list of no zero region occurs after it
if start:
x.append((maxima[p-1][1], start, len(outputs), outputs[maxima[p-1]]))
return [y for y in x if x[0] != 0]
示例28: keep_largest_object
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def keep_largest_object(z_slice_bin, x_cOm, y_cOm):
"""
Keep the largest connected object per z_slice and fill little holes.
Note: This function only works for binary segmentation.
:param z_slice: int 2d-array: Input 2d segmentation
:param x_cOm: int: X center of mass of the segmentation for the previous 2d slice
:param y_cOm: int: Y center of mass of the segmentation for the previous 2d slice
:return: z_slice: int 2d-array: Processed 2d segmentation
"""
assert z_slice_bin.dtype == np.dtype('int')
# Find number of closed objects using skimage "label"
labeled_obj, num_obj = label(z_slice_bin)
# If more than one object is found, keep the largest one
if num_obj > 1:
# If the center of mass is not provided (e.g. is first slice, or segmentation is empty), keep the largest object
if x_cOm is None or np.isnan(x_cOm):
z_slice_bin[np.where(labeled_obj != (np.bincount(labeled_obj.flat)[1:].argmax() + 1))] = 0
# If the center of mass is provided,
else:
idx_z_minus_1 = np.bincount(labeled_obj.flat)[1:].argmax() + 1
for idx in range(1, num_obj + 1):
z_idx = labeled_obj == idx
if z_idx[int(x_cOm), int(y_cOm)]:
idx_z_minus_1 = idx
z_slice_bin[np.where(labeled_obj != idx_z_minus_1)] = 0
return z_slice_bin
示例29: scan_slice
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def scan_slice(z_slice, model, mean_train, std_train, coord_lst, patch_shape, z_out_dim):
"""Scan the entire axial slice to detect the centerline."""
z_slice_out = np.zeros(z_out_dim)
sum_lst = []
# loop across all the non-overlapping blocks of a cross-sectional slice
for idx, coord in enumerate(coord_lst):
block = z_slice[coord[0]:coord[2], coord[1]:coord[3]]
block_nn = np.expand_dims(np.expand_dims(block, 0), -1)
block_nn_norm = _normalize_data(block_nn, mean_train, std_train)
block_pred = model.predict(block_nn_norm, batch_size=BATCH_SIZE)
if coord[2] > z_out_dim[0]:
x_end = patch_shape[0] - (coord[2] - z_out_dim[0])
else:
x_end = patch_shape[0]
if coord[3] > z_out_dim[1]:
y_end = patch_shape[1] - (coord[3] - z_out_dim[1])
else:
y_end = patch_shape[1]
z_slice_out[coord[0]:coord[2], coord[1]:coord[3]] = block_pred[0, :x_end, :y_end, 0]
sum_lst.append(np.sum(block_pred[0, :x_end, :y_end, 0]))
# Put first the coord of the patch were the centerline is likely located so that the search could be faster for the
# next axial slices
coord_lst.insert(0, coord_lst.pop(sum_lst.index(max(sum_lst))))
# computation of the new center of mass
if np.max(z_slice_out) > 0.5:
z_slice_out_bin = z_slice_out > 0.5
labeled_mask, numpatches = label(z_slice_out_bin)
largest_cc_mask = (labeled_mask == (np.bincount(labeled_mask.flat)[1:].argmax() + 1))
x_CoM, y_CoM = center_of_mass(largest_cc_mask)
x_CoM, y_CoM = int(x_CoM), int(y_CoM)
else:
x_CoM, y_CoM = None, None
return z_slice_out, x_CoM, y_CoM, coord_lst
示例30: save
# 需要导入模块: from scipy.ndimage import measurements [as 别名]
# 或者: from scipy.ndimage.measurements import label [as 别名]
def save(self, label):
self.save_network(self.netG, 'G', label, self.gpu_ids)
# self.save_network(self.netR, 'R', label, self.gpu_ids)
# self.save_network(self.netL, 'L', label, self.gpu_ids)
注:本文中的scipy.ndimage.measurements.label方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。