本文整理汇总了Python中skimage.measure.find_contours方法的典型用法代码示例。如果您正苦于以下问题:Python measure.find_contours方法的具体用法?Python measure.find_contours怎么用?Python measure.find_contours使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类skimage.measure
的用法示例。
在下文中一共展示了measure.find_contours方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def __call__(self, img_binary):
cs = measure.find_contours(img_binary, 0.5)
# Collect contours into RotatedBoxes
results = []
for c in cs:
# Now examine the bounding box. If it is too small, we ignore the contour
ll, ur = np.min(c, 0), np.max(c, 0)
wh = ur - ll
if wh[0] * wh[1] < self.min_area:
continue
# Finally, construct the rotatedbox. If its aspect ratio is too small, we ignore it
rb = RotatedBox.from_points(c, self.box_type)
if rb.height == 0 or rb.width / rb.height < self.min_box_aspect:
continue
# All tests fine, add to the list
results.append(rb)
# Next sort and leave only max_boxes largest boxes by area
results.sort(key=lambda x: -x.area)
return self._merge_boxes(results[0:self.max_boxes])
示例2: critical_curve_via_magnification_from_tracer_and_grid
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def critical_curve_via_magnification_from_tracer_and_grid(tracer, grid):
magnification = tracer.magnification_from_grid(grid=grid)
inverse_magnification = 1 / magnification
critical_curves_indices = measure.find_contours(inverse_magnification.in_2d, 0)
no_critical_curves = len(critical_curves_indices)
contours = []
critical_curves = []
for jj in np.arange(no_critical_curves):
contours.append(critical_curves_indices[jj])
contour_x, contour_y = contours[jj].T
pixel_coord = np.stack((contour_x, contour_y), axis=-1)
critical_curve = grid.geometry.grid_scaled_from_grid_pixels_1d_for_marching_squares(
grid_pixels_1d=pixel_coord, shape_2d=magnification.sub_shape_2d
)
critical_curve = np.array(grid=critical_curve)
critical_curves.append(critical_curve)
return critical_curves
示例3: fill_convex
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def fill_convex (image):
H, W = image.shape
padded = np.zeros((H+20, W+20), dtype=np.uint8)
padded[10:(10+H),10:(10+W)] = image
contours = measure.find_contours(padded, 0.5)
if len(contours) == 0:
return image
if len(contours) == 1:
contour = contours[0]
else:
contour = np.vstack(contours)
cc = np.zeros_like(contour, dtype=np.int32)
cc[:,0] = contour[:, 1]
cc[:,1] = contour[:, 0]
hull = cv2.convexHull(cc)
contour = hull.reshape((1, -1, 2))
cv2.fillPoly(padded, contour, 1)
return padded[10:(10+H),10:(10+W)]
示例4: vectorize
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def vectorize(self, **pixelBlocks):
image = pixelBlocks['raster_pixels']
_, height, width = image.shape
image = np.transpose(image, [1,2,0])
with self.graph.as_default():
results = self.model.detect([image], verbose=1)
masks = results[0]['masks']
mask_count = masks.shape[-1]
coord_list = []
for m in range(mask_count):
mask = masks[:, :, m]
padded_mask = np.zeros((mask.shape[0]+2, mask.shape[1]+2), dtype=np.uint8)
padded_mask[1:-1, 1:-1] = mask
contours = find_contours(padded_mask, 0.5, fully_connected='high')
if len(contours) != 0:
verts = contours[0] - 1
coord_list.append(verts)
if self.padding != 0:
coord_list[:] = [item - self.padding for item in coord_list]
return coord_list, results[0]['scores'], results[0]['class_ids']
示例5: vectorize_regions
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def vectorize_regions(im: np.ndarray, threshold: float = 0.5):
"""
Vectorizes lines from a binarized array.
Args:
im (np.ndarray): Array of shape (H, W) with the first dimension
being a probability distribution over the region.
threshold (float): Threshold for binarization
Returns:
[[x0, y0, ... xn, yn], [xm, ym, ..., xk, yk], ... ]
A list of lists containing the region polygons.
"""
bin = im > threshold
contours = find_contours(bin, 0.5, fully_connected='high', positive_orientation='high')
if len(contours) == 0:
return contours
approx_contours = []
for contour in contours:
approx_contours.append(approximate_polygon(contour[:,[1,0]], 1).astype('uint').tolist())
return approx_contours
示例6: binary_mask_to_polygon
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def binary_mask_to_polygon(binary_mask, tolerance=0):
"""Converts a binary mask to COCO polygon representation
Args:
binary_mask: a 2D binary numpy array where '1's represent the object
tolerance: Maximum distance from original points of polygon to approximated
polygonal chain. If tolerance is 0, the original coordinate array is returned.
"""
polygons = []
# pad mask to close contours of shapes which start and end at an edge
padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
contours = measure.find_contours(padded_binary_mask, 0.5)
contours = np.subtract(contours, 1)
for contour in contours:
contour = close_contour(contour)
contour = measure.approximate_polygon(contour, tolerance)
if len(contour) < 3:
continue
contour = np.flip(contour, axis=1)
segmentation = contour.ravel().tolist()
# after padding and subtracting 1 we may get -0.5 points in our segmentation
segmentation = [0 if i < 0 else i for i in segmentation]
polygons.append(segmentation)
return polygons
示例7: binary_mask_to_polygon
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def binary_mask_to_polygon(binary_mask, tolerance=0):
"""Converts a binary mask to COCO polygon representation
Args:
binary_mask: a 2D binary numpy array where '1's represent the object
tolerance: Maximum distance from original points of polygon to approximated
polygonal chain. If tolerance is 0, the original coordinate array is returned.
"""
polygons = []
# pad mask to close contours of shapes which start and end at an edge
padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
contours = measure.find_contours(padded_binary_mask, 0.5)
contours = np.subtract(contours, 1)
for contour in contours:
contour = close_contour(contour)
contour = measure.approximate_polygon(contour, tolerance)
if len(contour) < 3:
continue
contour = np.flip(contour, axis=1)
segmentation = contour
# after padding and subtracting 1 we may get -0.5 points in our segmentation
segmentation = [np.clip(i,0.0,i).tolist() for i in segmentation]
polygons.append(segmentation)
return polygons
示例8: level_curves
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def level_curves(fname, npoints = 200, smoothing = 10, level = 0.5) :
"Loads regularly sampled curves from a .PNG image."
# Find the contour lines
img = misc.imread(fname, flatten = True) # Grayscale
img = (img.T[:, ::-1]) / 255.
img = gaussian_filter(img, smoothing, mode='nearest')
lines = find_contours(img, level)
# Compute the sampling ratio for every contour line
lengths = np.array( [arclength(line) for line in lines] )
points_per_line = np.ceil( npoints * lengths / np.sum(lengths) )
# Interpolate accordingly
points = [] ; connec = [] ; index_offset = 0
for ppl, line in zip(points_per_line, lines) :
(p, c) = resample(line, ppl)
points.append(p)
connec.append(c + index_offset)
index_offset += len(p)
size = np.maximum(img.shape[0], img.shape[1])
points = np.vstack(points) / size
connec = np.vstack(connec)
return Curve(points, connec)
# Pyplot Output =================================================================================
示例9: make_contours
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def make_contours(self, level=0.):
"""
This function returns the contours as a List of coordinate positions
at one given level - run this more than once with different levels
if desired
:type level: float
:param level: Level (z value) of grid to contour
:return:
contours: List of contours with coordinate positions
"""
try:
from skimage import measure
except:
raise(Exception("Package 'scikit-image' not available to make contours."))
return measure.find_contours(self.data, level)
示例10: find_contours
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def find_contours(*args):
contours = FC(*args)
simplified_contours = [np.array(simplify_coords(x, 1), dtype=np.int32) \
for x in contours]
return simplified_contours
示例11: get_points
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def get_points(mask, spacing):
points = []
if np.amax(mask) > 0:
contours = measure.find_contours(mask.astype(np.float32), 0.5)
for contour in contours:
con = contour.ravel().reshape((-1, 2)) # con[0] is along x (last dimension of mask)
for p in con:
points.append([p[1] * spacing[0], p[0] * spacing[1]])
return np.asarray(points, dtype=np.float32)
示例12: binary_mask_to_polygon
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def binary_mask_to_polygon(binary_mask, tolerance=0):
"""Converts a binary mask to COCO polygon representation
Args:
binary_mask: a 2D binary numpy array where '1's represent the object
tolerance: Maximum distance from original points of polygon to approximated
polygonal chain. If tolerance is 0, the original coordinate array is returned.
"""
polygons = []
# pad mask to close contours of shapes which start and end at an edge
padded_binary_mask = np.pad(binary_mask, pad_width=1, mode='constant', constant_values=0)
contours = measure.find_contours(padded_binary_mask, 0.5)
contours = np.subtract(contours, 1)
for contour in contours:
contour = close_contour(contour)
contour = measure.approximate_polygon(contour, tolerance)
if len(contour) < 3:
continue
contour = np.flip(contour, axis=1)
segmentation = contour.ravel().tolist()
# after padding and subtracting 1 we may get -0.5 points in our segmentation
segmentation = [0 if i < 0 else i for i in segmentation]
polygons.append(segmentation)
return polygons
示例13: convex_hull
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def convex_hull (binary):
swap_sequence = [(0, 1), # 102
(0, 2), # 201
(0, 2)] # 102
output = np.ndarray(binary.shape, dtype=binary.dtype)
for swp1, swp2 in swap_sequence:
N = binary.shape[0]
print 'shape', binary.shape
for i in range(N):
contours = measure.find_contours(binary[i], 0.5)
if len(contours) == 0:
continue
if len(contours) == 1:
contour = contours[0]
else:
contour = np.vstack(contours)
cc = np.zeros_like(contour, dtype=np.int32)
cc[:,0] = contour[:, 1]
cc[:,1] = contour[:, 0]
hull = cv2.convexHull(cc)
contour = hull.reshape((1, -1, 2))
cv2.fillPoly(binary[i], contour, 1)
#binary[i] = skimage.morphology.convex_hull_image(binary[i])
pass
print 'swap', swp1, swp2
nb = np.swapaxes(binary, swp1, swp2)
binary = np.ndarray(nb.shape, dtype=nb.dtype)
binary[:,:] = nb[:,:]
pass
binary = np.swapaxes(binary, 0, 1)
output[:,:] = binary[:,:]
return output;
#binary = binary_dilation(output, iterations=dilate)
#return binary
示例14: show_fig2
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def show_fig2():
contours = measure.find_contours(phi, 0)
ax2 = fig2.add_subplot(111)
ax2.imshow(img, interpolation='nearest', cmap=plt.cm.gray)
for n, contour in enumerate(contours):
ax2.plot(contour[:, 1], contour[:, 0], linewidth=2)
示例15: _calculate_contours_centroids
# 需要导入模块: from skimage import measure [as 别名]
# 或者: from skimage.measure import find_contours [as 别名]
def _calculate_contours_centroids(self):
cnts_df_list = []
cts_df_list = []
A = self.cnmf['A'].load()
for uid in range(self._u):
cur_A = A.sel(unit_id=uid)
cur_idxs = cur_A.squeeze().dims
cur_thres = dask.delayed(cur_A.max)()
cur_thres = dask.delayed(float)(cur_thres * .3)
cur_cnts = dask.delayed(find_contours)(cur_A, cur_thres)
cur_cnts = dask.delayed(np.concatenate)(cur_cnts)
cur_cnts = dask.delayed(pd.DataFrame)(cur_cnts, columns=cur_idxs)
cur_cnts = cur_cnts.assign(unit_id=uid)
cur_cts = dask.delayed(center_of_mass)(cur_A.values)
cur_cts = dask.delayed(pd.Series)(cur_cts, index=cur_idxs)
cur_cts = cur_cts.append(pd.Series(dict(unit_id=uid)))
cnts_df_list.append(cur_cnts)
cts_df_list.append(cur_cts)
cnts_df_list = dask.compute(*cnts_df_list)
cts_df_list = dask.compute(*cts_df_list)
cnts_df = pd.concat(cnts_df_list)
cts_df = pd.concat(cts_df_list, axis=1).T
for dim in cur_idxs:
cnts_df[dim].update(cnts_df[dim] / A.sizes[dim] * self._dims[dim])
cts_df[dim].update(cts_df[dim] / A.sizes[dim] * self._dims[dim])
return cnts_df, cts_df