我有一个图像的 numpy 数组:
红色是特定部分的二进制掩模,我的目标是计算该掩模中的最大直径长度。我尝试过使用边界框并测量盒子的直径(从一端到另一端),但它没有我想要的那么准确,特别是当掩模的形状接近圆形时。
我的下一个想法是使用边界圆而不是盒子,并测量半径,这样会非常准确。问题是我不知道有任何包或函数可以给我一个边界圆。即使有这样的函数,我也不知道如何测量给定圆的半径,因为圆中没有尖点可以端到端。
感谢任何想法。
最佳答案
关于我的解决方案的一些注释:
(0) 它接受二进制图像作为输入。
(1) 它为图像中的所有区域找到它。
(2) 求该区域凸包的最大直径。我认为这是一个合理的做法,但如果您愿意,您可以调整实现。
(3) 我使用 skimage.data“硬币”图像,以便您可以自己重现。
import sys
# To find the diameters
from skimage.measure import regionprops, label
from sklearn.metrics import pairwise_distances
from scipy import ndimage as ndi
import numpy as np
# To generate test data
from skimage import data
from skimage.filters import sobel
from skimage.morphology import watershed
# For visualization
import matplotlib.pyplot as plt
STREL_4 = np.array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype=np.bool)
def get_border_image(region):
convex_hull_mask = region.convex_image
eroded_image = ndi.binary_erosion(convex_hull_mask, STREL_4, border_value=0)
border_image = np.logical_xor(convex_hull_mask, eroded_image)
return border_image
def get_region_diameters(img):
assert img.dtype == np.bool and len(img.shape) == 2
label_img = label(img, connectivity=img.ndim)
for region in regionprops(label_img):
border_image = get_border_image(region)
perimeter_coordinates = np.transpose(np.nonzero(border_image))
pairwise_distances_matrix = pairwise_distances(perimeter_coordinates)
i, j = np.unravel_index(np.argmax(pairwise_distances_matrix), pairwise_distances_matrix.shape)
ptA, ptB = perimeter_coordinates[i], perimeter_coordinates[j]
region_offset = np.asarray([region.bbox[0], region.bbox[1]])
ptA += region_offset
ptB += region_offset
yield pairwise_distances_matrix[i, j], ptA, ptB
if __name__ == "__main__":
# Create a segmentation of the coins image, for testing purposes.
# You should create a binary image
coins = data.coins()
elevation_map = sobel(coins)
markers = np.zeros_like(coins)
markers[coins < 30] = 1
markers[coins > 150] = 2
segmentation = (watershed(elevation_map, markers) > 1)
for distance, ptA, ptB in get_region_diameters(segmentation):
plt.imshow(segmentation)
x1, x2, y1, y2 = ptA[1], ptB[1], ptA[0], ptB[0]
plt.plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)
print(distance, ptA, ptB)
plt.show()
关于python - 计算二进制掩码数组上的封闭圆的半径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57999933/