我已经使用OpenCV从蒙版图像中成功提取轮廓:
image = cv2.imread(file)
lower = np.array([240, 240, 240])
upper = np.array([255, 255, 255])
shape_mask = cv2.inRange(image, lower, upper)
contours, hierarchy = cv2.findContours(shape_mask.copy(), cv2.RETR_CCOMP,
cv2.CHAIN_APPROX_SIMPLE)
现在如何继续将此轮廓映射到多边形(带有孔)的列表中,并以形状将其导出为SHP文件?
此处给出部分答案:How to convert NumPy arrays obtained from cv2.findContours to Shapely polygons?
但是,这忽略了在多边形内部有孔的情况。我将如何继续获取所有多边形?
找到答案:https://michhar.github.io/masks_to_polygons_and_back/
从蒙版图像以numpy数组创建MultiPolygons的助手:
def mask_to_polygons(mask, epsilon=10., min_area=10.):
"""Convert a mask ndarray (binarized image) to Multipolygons"""
# first, find contours with cv2: it's much faster than shapely
image, contours, hierarchy = cv2.findContours(mask,
cv2.RETR_CCOMP,
cv2.CHAIN_APPROX_NONE)
if not contours:
return MultiPolygon()
# now messy stuff to associate parent and child contours
cnt_children = defaultdict(list)
child_contours = set()
assert hierarchy.shape[0] == 1
# http://docs.opencv.org/3.1.0/d9/d8b/tutorial_py_contours_hierarchy.html
for idx, (_, _, _, parent_idx) in enumerate(hierarchy[0]):
if parent_idx != -1:
child_contours.add(idx)
cnt_children[parent_idx].append(contours[idx])
# create actual polygons filtering by area (removes artifacts)
all_polygons = []
for idx, cnt in enumerate(contours):
if idx not in child_contours and cv2.contourArea(cnt) >= min_area:
assert cnt.shape[1] == 1
poly = Polygon(
shell=cnt[:, 0, :],
holes=[c[:, 0, :] for c in cnt_children.get(idx, [])
if cv2.contourArea(c) >= min_area])
all_polygons.append(poly)
all_polygons = MultiPolygon(all_polygons)
return all_polygons
创建这些辅助功能的信用:
这些帮助者的原始来源是Konstantin发表的Kaggle帖子Lopuhin here-您需要登录Kaggle才能看到它