Search code examples
pythonnumpyopencvcomputer-visionscikit-image

Extract polygon coordinates from image (map)


I have the following map:

enter image description here

I want to extract the polygon coordinates (pixls), I am using the following code snipt, but the inteverted labeled image is all 0's (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])

The inverted image is as follow:

enter image description here

I belive the probem is in the value of the selem in this line:

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

Could you please advise what is the problem in this code..

EDIT The unique values if the inverted image (grayscaled):

[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]

I think I need to classify these value into two categories (white/black) based on some threshold value. Could you please confirm my finding, and if it is so how can I calculate this value?


Solution

  • Yes a threshold here would work. Having a look at the minimum and maximum values of the image 0.7 seems reasonable:

    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]))
    

    produced mask

    And if you just want the perimeter line rather than area (as it has a width) then you could do:

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

    skeletonized