从图像(地图)中提取多边形坐标

Extract polygon coordinates from image (map)

我有以下地图:

我想提取多边形坐标(pixls),我用的是下面的代码片段,但是倒置标注的图像全是0(False):

import numpy as np
from skimage import io, measure, morphology
from skimage.io import imsave, imread

img = io.imread('map.png', as_gray=True)
imsave("test.png", img)

img = morphology.binary_dilation(img, selem=np.ones((5,5)))

img_inverted = np.invert(img)
img_inverted_labeled = measure.label(img_inverted)

n_lbls = np.unique(img_inverted_labeled)[1:]

pols = []
for i in n_lbls:
  img_part = (img_inverted_labeled == i)
  pols.append(measure.find_contours(img_part, level=0)[0])

倒像如下:

我相信问题在于这一行中的 selem 值:

img = morphology.binary_dilation(img, selem=np.ones((5,5)))

请问这段代码有什么问题..

编辑 反转图像(灰度)的唯一值:

[235, 227, 219, 212, 204, 230, 215, 199, 207, 188, 184, 172, 176, 196, 192, 179, 223, 211, 203, 173, 191, 228, 216, 232, 200, 208, 171, 183, 175, 180, 195, 236, 221, 234, 233, 226, 220]

我想我需要根据一些阈值将这些值分为两类 (white/black)。能否请您确认我的发现,如果是,我该如何计算这个值?

是的,这里的阈值会起作用。查看图像的最小值和最大值 0.7 似乎是合理的:

import numpy as np
from skimage import io, measure, morphology
from skimage.io import imsave, imread
from matplotlib import pyplot as plt

img = io.imread('map.png', as_gray=True)
# do thresholding
mask = img < 0.7

plt.matshow(mask, cmap='gray')

# ij coords of perimeter
coords = np.nonzero(mask)
coords
>>> (array([ 61,  61,  61, ..., 428, 428, 428]),
     array([200, 201, 202, ..., 293, 294, 295]))

如果您只想要周界线而不是面积(因为它有宽度),那么您可以这样做:

from skimage.morphology import skeletonize

fig, ax = plt.subplots(dpi=150)
ax.matshow(skeletonize(mask), cmap='gray')