Importing Complex Polygons

Importing complex polygons with V7

You can natively import complex polygons in the Darwin JSON v2 format just as you would a simple polygon.

If you have a format other than Darwin JSON then you should first convert that format into a PNG. Once in PNG form then you should then run the script below to pull out the Darwin JSON paths parameter. You will need to enter into your Darwin JSON template.

import numpy as np
from upolygon import find_contours
from PIL import Image

filename = "<path/to/file.png>"

def convert_png_to_darwin_json(filename):
  """
  Converts PNG to Darwin JSON complex polygon paths
  """
  masked_image = Image.open(filename).convert('L')


  mask = np.array(masked_image)
  mask[mask > 0] = 1


  _labels, external, _internal = find_contours(mask)

  paths = []
  for external_path in external:
    new_path = []
    # skip paths with less than 2 points
    if len(external_path) // 2 <= 2:
      continue
    points = iter(external_path)
    while True:
      try:
        x, y = next(points), next(points)
        new_path.append({"x": x, "y": y})
      except StopIteration:
        break
    paths.append(new_path)

  for internal_path in _internal:
    new_path = []
    # skip paths with less than 2 points
    if len(internal_path) // 2 <= 2:
      continue
    points = iter(internal_path)
    while True:
      try:
        x, y = next(points), next(points)
        new_path.append({"x": x, "y": y})
      except StopIteration:
        break
    paths.append(new_path)

  return paths

if __name__ == "__main__":
  convert_png_to_darwin_json(filename)

Once completed and inserted into the Darwin JSON template with the relevant name and path fields, this complex polygon can then be uploaded to an item in V7 using the importer module of the darwin-py SDK. See here for more details.

For more information on the upolygon library check out this link.

🚧

Separate Annotations

Each PNG will be treated as a separate annotation. Please separate out the annotations into separate PNGs if you would like them to be uploaded as separate annotations.