File size: 4,109 Bytes
d03ebb8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | #!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "Pillow>=10.0",
# "datasets>=2.14",
# ]
# ///
"""Composite a cursor from the Fraser/cursors dataset onto a screenshot.
Usage:
uv run composite_cursor.py sample_screenshots/some_image.png
Produces: sample_screenshots/some_image_cursored.png
"""
import random
import sys
from pathlib import Path
from datasets import load_dataset
from PIL import Image
def load_cursors(os_filter=None):
"""Load the cursor dataset, optionally filtering by OS."""
ds = load_dataset("Fraser/cursors", split="train")
if os_filter:
ds = ds.filter(lambda r: r["os"] == os_filter)
return ds
def composite_cursor(
screenshot: Image.Image,
cursor_frame: Image.Image,
hotspot_x: float,
hotspot_y: float,
target_x: int,
target_y: int,
cursor_size: int = 32,
) -> Image.Image:
"""Place a cursor onto a screenshot so the hotspot lands at (target_x, target_y).
Args:
screenshot: The background image (any mode, will be converted to RGBA).
cursor_frame: A single RGBA cursor frame.
hotspot_x: Normalised hotspot x (0-1 within cursor image).
hotspot_y: Normalised hotspot y (0-1 within cursor image).
target_x: Pixel x on the screenshot where the hotspot should land.
target_y: Pixel y on the screenshot where the hotspot should land.
cursor_size: Desired cursor height in pixels (width scales proportionally).
Returns:
Composited image in the same mode as the input screenshot.
"""
orig_mode = screenshot.mode
canvas = screenshot.convert("RGBA")
cw, ch = cursor_frame.size
scale = cursor_size / max(cw, ch)
new_w, new_h = max(1, round(cw * scale)), max(1, round(ch * scale))
cursor_scaled = cursor_frame.convert("RGBA").resize(
(new_w, new_h), Image.LANCZOS
)
paste_x = target_x - round(hotspot_x * new_w)
paste_y = target_y - round(hotspot_y * new_h)
# Crop cursor if it extends beyond the screenshot edges
sw, sh = canvas.size
src_left = max(0, -paste_x)
src_top = max(0, -paste_y)
src_right = min(new_w, sw - paste_x)
src_bottom = min(new_h, sh - paste_y)
if src_left >= src_right or src_top >= src_bottom:
return screenshot
cropped = cursor_scaled.crop((src_left, src_top, src_right, src_bottom))
dst_x = paste_x + src_left
dst_y = paste_y + src_top
canvas.alpha_composite(cropped, (dst_x, dst_y))
if orig_mode != "RGBA":
canvas = canvas.convert(orig_mode)
return canvas
def main():
if len(sys.argv) < 2:
print("Usage: uv run composite_cursor.py <screenshot.png> [x y] [cursor_size]")
print(" x, y: click-point position (default: random)")
print(" cursor_size: cursor height in pixels (default: 32)")
sys.exit(1)
screenshot_path = Path(sys.argv[1])
screenshot = Image.open(screenshot_path)
sw, sh = screenshot.size
if len(sys.argv) >= 4:
tx, ty = int(sys.argv[2]), int(sys.argv[3])
else:
tx = random.randint(int(sw * 0.05), int(sw * 0.95))
ty = random.randint(int(sh * 0.05), int(sh * 0.95))
cursor_size = int(sys.argv[4]) if len(sys.argv) >= 5 else 32
print(f"Screenshot: {screenshot_path} ({sw}x{sh})")
print(f"Loading cursors...")
ds = load_cursors()
# Pick a random static cursor
static = [i for i in range(len(ds)) if len(ds[i]["frames"]) == 1]
idx = random.choice(static)
row = ds[idx]
cursor_frame = row["frames"][0]
print(f"Cursor: {row['cursor_type']} / {row['os']} / {row['variant']}")
print(f"Hotspot: ({row['hotspot_x']:.2f}, {row['hotspot_y']:.2f})")
print(f"Placing at: ({tx}, {ty}), size={cursor_size}px")
result = composite_cursor(
screenshot, cursor_frame,
row["hotspot_x"], row["hotspot_y"],
tx, ty, cursor_size,
)
out_path = screenshot_path.with_stem(screenshot_path.stem + "_cursored")
result.save(out_path)
print(f"Saved: {out_path}")
if __name__ == "__main__":
main()
|