Skip to content

Instantly share code, notes, and snippets.

@PowerX-NOT
Created November 28, 2025 04:07
Show Gist options
  • Select an option

  • Save PowerX-NOT/06a37f3eba6aedf0fe31fad98936816d to your computer and use it in GitHub Desktop.

Select an option

Save PowerX-NOT/06a37f3eba6aedf0fe31fad98936816d to your computer and use it in GitHub Desktop.
from __future__ import annotations
import os
import sys
import argparse
import json
from inference_sdk import InferenceHTTPClient
from PIL import Image, ImageDraw, ImageFont
API_KEY = "4Ffffb9rznBnFJyZbsHv"
MODEL_ID = "emergency-vehicles-i10gn/2"
API_URL = "https://serverless.roboflow.com"
def get_text_size(text, font):
"""Cross-version text size helper."""
try:
# Pillow ≥ 10 (new)
bbox = font.getbbox(text)
width = bbox[2] - bbox[0]
height = bbox[3] - bbox[1]
return width, height
except:
# Older Pillow fallback
return font.getsize(text)
def draw_boxes(image_path, predictions, output_path="output.jpg"):
img = Image.open(image_path).convert("RGB")
draw = ImageDraw.Draw(img)
# Load font
try:
font = ImageFont.truetype("arial.ttf", 20)
except:
font = ImageFont.load_default()
for p in predictions:
x = p.get("x")
y = p.get("y")
w = p.get("width")
h = p.get("height")
if None in (x, y, w, h):
continue
# Convert center to corners
x1 = x - w / 2
y1 = y - h / 2
x2 = x + w / 2
y2 = y + h / 2
label = p.get("class", "Object")
conf = p.get("confidence", 0.0)
text = f"{label} {conf:.2f}"
# NEW: Safe text sizing
text_w, text_h = get_text_size(text, font)
# Draw rectangle
draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
# Draw label background
text_y = max(0, y1 - text_h)
draw.rectangle([x1, text_y, x1 + text_w, text_y + text_h], fill="red")
# Draw text
draw.text((x1, text_y), text, fill="white", font=font)
img.save(output_path)
print(f"✔ Output saved as {output_path}")
def main(argv=None):
argv = argv if argv is not None else sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument("image", help="Path to image")
args = parser.parse_args(argv)
if not os.path.isfile(args.image):
print("❌ Error: image not found:", args.image)
sys.exit(2)
client = InferenceHTTPClient(api_url=API_URL, api_key=API_KEY)
print("🔍 Running inference...")
result = client.infer(args.image, model_id=MODEL_ID)
preds = result.get("predictions", [])
print(json.dumps(preds, indent=2))
if preds:
draw_boxes(args.image, preds)
else:
print("⚠ No objects detected.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment