Skip to content

Instantly share code, notes, and snippets.

@twilligon
Created May 24, 2024 23:48
Show Gist options
  • Save twilligon/5fde389474e8d0f0b597c021ef15f9cf to your computer and use it in GitHub Desktop.
Save twilligon/5fde389474e8d0f0b597c021ef15f9cf to your computer and use it in GitHub Desktop.
Decode COCO RLE images to PNG masks
#!/usr/bin/env python3
import sys
import re
import numpy as np
from PIL import Image
def decode_rle(rle, width, height):
img = np.zeros((height, width), dtype=np.uint8)
seq = img.ravel()
idx = 0
pattern = re.compile(r"(\d+)([FT])")
for match in pattern.finditer(rle):
length = int(match.group(1))
bit = match.group(2)
if bit == "T":
seq[idx:idx + length] = 1
idx += length
assert idx == width * height, "RLE does not decode to expected image size"
return Image.fromarray(img * 255, mode="L").convert("1")
if __name__ == "__main__":
if len(sys.argv) != 5:
print("Usage: python3 coco.py <width> <height> <in.rle> <out.png>")
sys.exit(1)
width = int(sys.argv[1])
height = int(sys.argv[2])
with open(sys.argv[3], "r") as f:
rle = f.read().strip()
img = decode_rle(rle, width, height)
img.save(sys.argv[4], format="PNG")
@twilligon
Copy link
Author

License: CC0-1.0

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