获取轮廓末端点
示例代码
import cv2
import numpy as np
def get_mask_thinning(mask):
mask_thinning = cv2.ximgproc.thinning(
mask,
thinningType=cv2.ximgproc.THINNING_GUOHALL,
)
return mask_thinning
def get_contour_end_points(mask):
"""
获取轮廓末端点,八领域法判断
通过计算当前像素与它相邻的像素前景数量=2即可判断它为端点
"""
end_point_list = []
nonzero_pts = cv2.findNonZero(mask)
for point in nonzero_pts:
x, y = point[0]
neighbors = np.sum(mask[y - 1 : y + 2, x - 1 : x + 2] / 255)
if neighbors == 2:
end_point_list.append((x, y))
return end_point_list
def visual_mask_points(mask, point_list, visual_color=(0, 0, 255)):
mask_visual = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
for (x, y) in point_list:
mask_visual[y, x, :] = visual_color
return mask_visual
if __name__ == "__main__":
mask_path = "./test.png"
mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)
mask_thinning = get_mask_thinning(mask)
end_point_list = get_contour_end_points(mask_thinning)
mask_visual = visual_mask_points(mask_thinning, end_point_list)
mask_visual_path = "./test_visual.png"
cv2.imwrite(mask_visual_path, mask_visual)