Skip to main content

A lightweight synthetic dataset image generation library built on top of Pillow.

Project description

Ranger

Lightweight synthetic dataset image generation — powered by Pillow.

Python 3.9+ License: MIT Version

Ranger is a small, focused library for generating synthetic training images and their annotations. You describe what to put on a canvas — backgrounds, shapes, images — and Ranger gives you back pixel-perfect bounding boxes and segmentation masks in plain Python data structures. No frameworks. No hidden config files. No magic.


Contents


Installation

pip install ranger

Ranger requires Python 3.9+ and Pillow ≥ 10.0.


Quick Start

import ranger

# 1. Set up a 640×480 canvas
ranger.init(w=640, h=480)

# 2. Dark gradient background
ranger.background("gradient", fill={
    "type": "gradient",
    "start": "#1A1A2E",
    "end": "#16213E",
    "direction": "vertical",
})

# 3. Define a reusable shape template
ranger.shape("car", w=120, h=60)
ranger.shape_add("car", "rectangle", fill="#E63946", x0=0, y0=10, x1=120, y1=60)
ranger.shape_add("car", "rectangle", fill="#222222", x0=20, y0=0, x1=100, y1=20)

# 4. Place two cars on the canvas
ranger.append("car_001", "car", x=50, y=200)
ranger.append("car_002", "car", x=350, y=300)

# 5. Get annotations
print(ranger.bbox())
# [
#   {"id": "car_001", "class": "car", "bbox": [50, 200, 170, 260]},
#   {"id": "car_002", "class": "car", "bbox": [350, 300, 470, 360]},
# ]

# 6. Save and reset
ranger.save("frame_001.png")
ranger.rm()

Design Philosophy

Ranger is deliberately narrow. It does exactly three things:

  1. Generate images — backgrounds, shapes, composited objects.
  2. Generate bounding box annotations — pixel-aligned [x1, y1, x2, y2].
  3. Generate segmentation annotations — per-pixel binary masks.

Everything else — writing COCO JSON, YOLO .txt files, Pascal VOC XML, training loops, data augmentation — is intentionally left to you. Ranger integrates cleanly with whatever export or training pipeline you already have, because it only returns standard Python lists and dicts.

Guiding principles:

  • Flat API. Everything is a module-level function. No classes to instantiate, no context managers to juggle.
  • Minimal dependencies. Only Pillow. No NumPy required (though masks are trivial to convert).
  • Beginner friendly. If you can write ranger.append(...) and ranger.save(...), you have a dataset.
  • Standard types. Returns list, dict, and tuple — no custom objects to unwrap.
  • Both colour notations. RGB tuples (255, 0, 0) and hex strings "#FF0000" work everywhere a colour is expected.

API Reference

init

ranger.init(device="cpu", w=1024, h=1024)

Initialise Ranger and create a blank canvas.

Parameter Type Default Description
device str "cpu" Compute device: "cpu", "cuda", or "mps". cuda and mps are reserved for future GPU acceleration and currently behave identically to cpu.
w int 1024 Canvas width in pixels.
h int 1024 Canvas height in pixels.

background

ranger.background(bg_type, *, fill=..., path=None, seed=None)

Fill the entire canvas with a background.

Parameter Type Description
bg_type str "color", "gradient", "noise", "perlin", "img"
fill colour or dict Colour value or fill spec (see Fill System)
path str | None Path to source image — required for bg_type="img".
seed int | None Random seed for reproducible noise/perlin backgrounds.

Examples:

# Solid colour
ranger.background("color", fill=(30, 30, 30))
ranger.background("color", fill="#1A1A2E")

# Horizontal gradient
ranger.background("gradient", fill={
    "type": "gradient",
    "start": "#FF6B6B",
    "end":   "#4ECDC4",
    "direction": "horizontal",
})

# Seeded noise
ranger.background("noise", fill={
    "type": "noise",
    "base": (100, 100, 100),
    "scale": 0.4,
}, seed=42)

# Perlin-like noise
ranger.background("perlin", fill={
    "type": "perlin",
    "base": "#2C3E50",
    "scale": 0.6,
    "octaves": 5,
}, seed=7)

# From an existing image file
ranger.background("img", path="sky.jpg")

shape / shape_add

ranger.shape(name, *, w, h)
ranger.shape_add(name, primitive, *, fill=..., **params)

Define a reusable shape template by stacking primitives.

shape

Parameter Type Description
name str Unique template name.
w int Template width in pixels.
h int Template height in pixels.

shape_add — primitives

Primitive Required params Description
"circle" cx, cy, r Circle with centre and radius.
"rectangle" x0, y0, x1, y1 Axis-aligned rectangle.
"img" path, optionally x, y Paste an image at an offset.

All primitives accept a fill parameter (colour or fill spec).

Example:

ranger.shape("traffic_light", w=40, h=100)
ranger.shape_add("traffic_light", "rectangle", fill="#222222", x0=0, y0=0, x1=40, y1=100)
ranger.shape_add("traffic_light", "circle",    fill="#FF0000", cx=20, cy=20, r=14)
ranger.shape_add("traffic_light", "circle",    fill="#FFA500", cx=20, cy=50, r=14)
ranger.shape_add("traffic_light", "circle",    fill="#00CC00", cx=20, cy=80, r=14)

append

ranger.append(obj_id, obj_class, *, x=0, y=0, **kwargs)

Place an object on the canvas and record its annotation.

Parameter Type Description
obj_id str Unique instance ID used in annotation output.
obj_class str A registered shape name, "img", or any free-form label.
x int Left edge of the object in canvas pixels.
y int Top edge of the object in canvas pixels.
**kwargs Forwarded to the renderer: path, w, h, fill, etc.

Class resolution order:

  1. If obj_class matches a registered shape name → render that template.
  2. If obj_class == "img" → load the image at path=.
  3. Otherwise → render a placeholder rectangle using fill=, w=, h=.

Examples:

# Named shape
ranger.append("tl_north", "traffic_light", x=100, y=50)

# Inline image
ranger.append("sponsor_logo", "img", path="logo.png", x=20, y=20)

# Placeholder (useful for layout testing)
ranger.append("unknown_001", "unknown", x=300, y=150, fill="#AAAAAA", w=80, h=80)

bbox

ranger.bbox(obj_id=None) -> list[dict]

Return bounding-box annotations.

[
    {
        "id":    "car_001",
        "class": "car",
        "bbox":  [x1, y1, x2, y2]   # pixel coordinates, inclusive corners
    },
    ...
]

Pass obj_id="car_001" to retrieve a single object's annotation.


seg

ranger.seg(obj_id=None) -> list[dict]

Return segmentation annotations.

[
    {
        "id":        "car_001",
        "class":     "car",
        "bbox":      [x1, y1, x2, y2],
        "mask":      [...],         # flat list, len == w * h, values 0 or 255
        "mask_size": (w, h)
    },
    ...
]

Converting the mask to a NumPy array (NumPy is not a Ranger dependency, but it is easy to integrate):

import numpy as np

entries = ranger.seg()
w, h = entries[0]["mask_size"]
mask = np.array(entries[0]["mask"], dtype=np.uint8).reshape(h, w)

save

ranger.save(path)

Save the current canvas to disk. The file format is inferred from the extension by Pillow (.png, .jpg, .bmp, .webp, etc.).

ranger.save("output/frame_042.png")

rm

ranger.rm()

Clear the canvas to black and remove all placed objects. Shape templates are kept so you can reuse them in the next frame.


Fill System

Wherever a fill parameter is accepted, Ranger understands two notations:

Solid colour

fill=(255, 99, 71)      # RGB tuple
fill="#FF6347"          # hex string (with or without #)

Gradient

fill={
    "type":      "gradient",
    "start":     "#FF6B6B",     # any colour value
    "end":       "#4ECDC4",
    "direction": "horizontal",  # or "vertical"
}

Noise (uniform random per-pixel offsets from a base colour)

fill={
    "type":  "noise",
    "base":  (128, 128, 128),
    "scale": 0.5,               # 0.0 → no noise, 1.0 → maximum noise
}

Perlin (layered smooth noise — good for terrain-like backgrounds)

fill={
    "type":    "perlin",
    "base":    "#2C3E50",
    "scale":   0.6,
    "octaves": 4,               # more octaves → more detail
}

Examples

Minimal YOLO-style loop

import json
import ranger

ranger.init(w=416, h=416)

dataset = []
for i in range(100):
    ranger.rm()
    ranger.background("noise", fill={"type": "noise", "base": (80, 80, 80), "scale": 0.3}, seed=i)

    ranger.shape("ball", w=32, h=32)
    ranger.shape_add("ball", "circle", fill="#F72585", cx=16, cy=16, r=15)

    x, y = i * 3 % 380, i * 7 % 380
    ranger.append(f"ball_{i:04d}", "ball", x=x, y=y)

    boxes = ranger.bbox()
    ranger.save(f"images/frame_{i:04d}.png")
    dataset.append({"frame": i, "annotations": boxes})

with open("annotations.json", "w") as f:
    json.dump(dataset, f, indent=2)

Multi-class scene

import ranger

ranger.init(w=800, h=600)
ranger.background("perlin", fill={
    "type":    "perlin",
    "base":    (34, 85, 34),
    "scale":   0.5,
    "octaves": 5,
}, seed=99)

# Define classes
ranger.shape("vehicle", w=100, h=50)
ranger.shape_add("vehicle", "rectangle", fill="#264653", x0=0,  y0=10, x1=100, y1=50)
ranger.shape_add("vehicle", "rectangle", fill="#2A9D8F", x0=15, y0=0,  x1=85,  y1=20)

ranger.shape("pedestrian", w=20, h=50)
ranger.shape_add("pedestrian", "rectangle", fill="#E9C46A", x0=6, y0=0,  x1=14, y1=12)  # head
ranger.shape_add("pedestrian", "rectangle", fill="#F4A261", x0=4, y0=12, x1=16, y1=50)  # body

# Populate scene
ranger.append("v_001", "vehicle",    x=50,  y=280)
ranger.append("v_002", "vehicle",    x=400, y=320)
ranger.append("p_001", "pedestrian", x=250, y=260)
ranger.append("p_002", "pedestrian", x=310, y=270)
ranger.append("p_003", "pedestrian", x=600, y=290)

print(ranger.bbox())
ranger.save("scene.png")

Pasting real images with segmentation

import ranger

ranger.init(w=512, h=512)
ranger.background("color", fill="#F0F0F0")

ranger.append("product_01", "img", path="product.png", x=128, y=128)

for entry in ranger.seg():
    w, h  = entry["mask_size"]
    total = w * h
    hit   = sum(1 for v in entry["mask"] if v > 0)
    print(f'{entry["id"]} covers {hit/total:.1%} of the canvas')

ranger.save("product_scene.png")

Exporting Annotations

Ranger returns plain Python dicts so you can convert to any format you need:

YOLO .txt

boxes = ranger.bbox()
W, H  = 640, 480

with open("labels/frame_001.txt", "w") as f:
    class_map = {"car": 0, "pedestrian": 1}
    for obj in boxes:
        x1, y1, x2, y2 = obj["bbox"]
        cx = ((x1 + x2) / 2) / W
        cy = ((y1 + y2) / 2) / H
        bw = (x2 - x1) / W
        bh = (y2 - y1) / H
        cls = class_map.get(obj["class"], 0)
        f.write(f"{cls} {cx:.6f} {cy:.6f} {bw:.6f} {bh:.6f}\n")

COCO-style JSON snippet

boxes = ranger.bbox()
coco_annotations = [
    {
        "id":          i,
        "image_id":    42,
        "category_id": 1,
        "bbox":        [b["bbox"][0], b["bbox"][1],
                        b["bbox"][2] - b["bbox"][0],
                        b["bbox"][3] - b["bbox"][1]],
        "area":        (b["bbox"][2] - b["bbox"][0]) * (b["bbox"][3] - b["bbox"][1]),
        "iscrowd":     0,
    }
    for i, b in enumerate(boxes)
]

Future Roadmap

Ranger is intentionally minimal today. Planned additions in future releases:

  • Shape nesting — embed one named shape inside another to build hierarchical objects.
  • Transforms — per-object rotation, scaling, and opacity.
  • GPU acceleration — real CUDA/MPS paths for faster noise generation at high resolutions.
  • Z-ordering — explicit depth control for overlapping objects.
  • Polygon segmentation — return polygon contours in addition to binary masks.
  • Single-object annotation queriesranger.bbox("car_001") already supported; will expand.
  • Text primitive — render text labels directly onto shapes.
  • Physics-based placement — non-overlapping random placement helpers.
  • Built-in augmentations — optional blur, brightness jitter, and crop directly in Ranger.

Ranger will never grow into a training framework or annotation exporter. Those concerns belong in your pipeline, not ours.


License

MIT © Ranger Contributors

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ranger_pipe-0.1.0-py3-none-any.whl (12.8 kB view details)

Uploaded Python 3

File details

Details for the file ranger_pipe-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: ranger_pipe-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for ranger_pipe-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f0e56d8fcd652c0e8ac230220dd188657b4530567a9e89d63b7ebef8f3ac3929
MD5 d9e33ece4e9d3e86ae516a3ddc369a0e
BLAKE2b-256 9429ef24ebd396415f39ff543621b2d7e86a33844f47eb4658fd29e20297e49c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page