Skip to content

Instantly share code, notes, and snippets.

@urschrei
Last active November 16, 2022 16:58
Show Gist options
  • Save urschrei/a391f6e18a551f8cbfec377903920eca to your computer and use it in GitHub Desktop.
Save urschrei/a391f6e18a551f8cbfec377903920eca to your computer and use it in GitHub Desktop.
Read a PNG into a numpy array, convert it to a Shapely Polygon, and dump it as GeoJSON
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created by Stephan Hügel on 2017-03-02
The MIT License (MIT)
Copyright (c) 2017 Stephan Hügel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
# requires scipy, scikit-image, shapely, geojson and dependencies
# this script is simple, but "heavy" on packages bc scipy and scikit
from imageio import imread
from skimage import measure
from skimage.color.colorconv import rgb2gray, rgba2rgb
from shapely.geometry import shape, Point, Polygon, LineString
import geojson
# read a PNG
polypic = imread("poly.png")
# convert to greyscale if need be
gray = rgb2gray(rgba2rgb(polypic))
# find contours
# Not sure why 1.0 works as a level -- maybe experiment with lower values
contours = measure.find_contours(gray, 1.0)
# build polygon, and simplify its vertices if need be
# this assumes a single, contiguous shape
# if you have e.g. multiple shapes, build a MultiPolygon with a list comp
# RESULTING POLYGONS ARE NOT GUARANTEED TO BE SIMPLE OR VALID
# check this yourself using e.g. poly.is_valid
poly = Polygon(contours[0]).simplify(1.0)
# write out to cwd as JSON
with open("polygon.json", "w") as f:
f.write(geojson.dumps(poly))
This file has been truncated, but you can view the full file.
@omi-akif
Copy link

Hello,

Thank you providing this code. I wanted to use it to extract labels from map. The labels are all triangles, circles, etc. I used your code to convert a raster file (png) of the map to geojson file. However, the problem was that I encountered at this line:

gray = rgb2gray(rgba2rgb(polypic))

The error is :


ValueError Traceback (most recent call last)
in ()
8 polypic = imread("DHKICCDRB1.png")
9 # convert to greyscale if need be
---> 10 gray = rgb2gray(rgba2rgb(polypic))
11
12 # find contours

/usr/local/lib/python3.7/dist-packages/skimage/color/colorconv.py in rgba2rgb(rgba, background)
166 msg = ("the input array must have shape == (..., 4)), "
167 f"got {arr.shape}")
--> 168 raise ValueError(msg)
169
170 arr = dtype.img_as_float(arr)

ValueError: the input array must have shape == (..., 4)), got (4961, 3508, 3)

I am not sure how to overcome it. I only know basic python. Is there any workaround for this? I am working on google colab.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment