---
updatedAt: 2025-09-22T20:38:46.000Z
agentTools:
  projectIndex: https://docs.v7labs.com/llms.txt
---

# Extract darwin polygon from mask (Python)

```python Python
import numpy as np
from upolygon import find_contours
from PIL import Image


filename = "example.png"
masked_image = Image.open(filename).convert('L')


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


_labels, external, _internal = find_contours(mask)
path = []
for external_path in external:
  # 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)
      path.append({"x": x, "y": y})
    except StopIteration:
      break

print(path)
```

```json Response Example
{"success":true}
```

# Import required libraries

<!-- python@1-3 -->

PIL can be replaced with any library for reading the masks.

# Load the mask

<!-- python@6-7 -->

`convert('L')` loades the images as grey scale. It's important to ensure that the mask has the shape `HxWx1`

# Preprocess the mask

<!-- python@10-11 -->

To find the conotur the foreground needs to be set to 1 and the background to 0, other values are undefined.

# Extract the contour

<!-- python@14-28 -->

upolygon provides `find_contours` that finds both external and internal paths, for darwin's polygon (including complex) external paths are enough. 

The result is returned as an list of list, every x and y values are stored like: `x1, y1, x2, y2, x3 ...`