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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
rfdetr_seg_infer.py
|
| 4 |
+
Simple RF-DETR Segmentation inference script.
|
| 5 |
+
|
| 6 |
+
Usage example:
|
| 7 |
+
python rfdetr_seg_infer.py \
|
| 8 |
+
--image path/to/image.jpg \
|
| 9 |
+
--weights-url "https://huggingface.co/<user>/<repo>/resolve/main/checkpoint_best_total.pth" \
|
| 10 |
+
--out annotated.png
|
| 11 |
+
|
| 12 |
+
Or provide a local weights path:
|
| 13 |
+
python rfdetr_seg_infer.py --image image.jpg --weights /path/to/checkpoint_best_total.pth
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import os
|
| 18 |
+
import requests
|
| 19 |
+
from io import BytesIO
|
| 20 |
+
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
import supervision as sv
|
| 25 |
+
from rfdetr import RFDETRSegPreview
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def download_file(url: str, dst: str, chunk_size: int = 8192):
|
| 29 |
+
if os.path.exists(dst):
|
| 30 |
+
return dst
|
| 31 |
+
print(f"Downloading weights from {url} -> {dst}")
|
| 32 |
+
r = requests.get(url, stream=True)
|
| 33 |
+
r.raise_for_status()
|
| 34 |
+
with open(dst, "wb") as f:
|
| 35 |
+
for chunk in r.iter_content(chunk_size=chunk_size):
|
| 36 |
+
if chunk:
|
| 37 |
+
f.write(chunk)
|
| 38 |
+
print("Download complete.")
|
| 39 |
+
return dst
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def load_image(image_path_or_url: str) -> Image.Image:
|
| 43 |
+
# Accept local path or http(s) url
|
| 44 |
+
if image_path_or_url.startswith("http://") or image_path_or_url.startswith("https://"):
|
| 45 |
+
resp = requests.get(image_path_or_url)
|
| 46 |
+
resp.raise_for_status()
|
| 47 |
+
return Image.open(BytesIO(resp.content)).convert("RGB")
|
| 48 |
+
return Image.open(image_path_or_url).convert("RGB")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def annotate_segmentation(image: Image.Image, detections: sv.Detections, classes: dict[int, str] | None = None) -> Image.Image:
|
| 52 |
+
"""
|
| 53 |
+
Annotate image with masks, polygons and labels using supervision.
|
| 54 |
+
classes: optional mapping from class_id -> class_name (int: str)
|
| 55 |
+
"""
|
| 56 |
+
# Color palette (expandable)
|
| 57 |
+
palette = sv.ColorPalette.from_hex([
|
| 58 |
+
"#ffff00", "#ff9b00", "#ff8080", "#ff66b2", "#ff66ff", "#b266ff",
|
| 59 |
+
"#9999ff", "#3399ff", "#66ffff", "#33ff99", "#66ff66", "#99ff00",
|
| 60 |
+
])
|
| 61 |
+
|
| 62 |
+
text_scale = sv.calculate_optimal_text_scale(resolution_wh=image.size)
|
| 63 |
+
mask_annotator = sv.MaskAnnotator(color=palette)
|
| 64 |
+
polygon_annotator = sv.PolygonAnnotator(color=sv.Color.WHITE)
|
| 65 |
+
label_annotator = sv.LabelAnnotator(
|
| 66 |
+
color=palette,
|
| 67 |
+
text_color=sv.Color.BLACK,
|
| 68 |
+
text_scale=text_scale,
|
| 69 |
+
text_position=sv.Position.CENTER_OF_MASS
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
labels = [
|
| 73 |
+
f"{(classes.get(class_id) if classes else str(class_id))} {conf:.2f}"
|
| 74 |
+
for class_id, conf in zip(detections.class_id, detections.confidence)
|
| 75 |
+
]
|
| 76 |
+
|
| 77 |
+
out = image.copy()
|
| 78 |
+
out = mask_annotator.annotate(out, detections)
|
| 79 |
+
out = polygon_annotator.annotate(out, detections)
|
| 80 |
+
out = label_annotator.annotate(out, detections, labels)
|
| 81 |
+
return out
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def save_combined_color_mask(detections: sv.Detections, out_path: str, image_size):
|
| 85 |
+
"""
|
| 86 |
+
Create and save a combined per-instance color mask (RGB) where each instance gets a unique color.
|
| 87 |
+
If detections has `masks` attribute (list/array of binary masks), uses that.
|
| 88 |
+
"""
|
| 89 |
+
masks = getattr(detections, "masks", None)
|
| 90 |
+
if masks is None:
|
| 91 |
+
print("[INFO] No masks available on detections; skipping combined mask save.")
|
| 92 |
+
return False
|
| 93 |
+
|
| 94 |
+
# masks expected shape: (N, H, W) or list of (H, W) masks
|
| 95 |
+
if isinstance(masks, list):
|
| 96 |
+
masks_arr = np.stack([np.asarray(m, dtype=bool) for m in masks], axis=0)
|
| 97 |
+
else:
|
| 98 |
+
masks_arr = np.asarray(masks)
|
| 99 |
+
# if (H,W,N) transpose is sometimes used; try to normalize
|
| 100 |
+
if masks_arr.ndim == 3 and masks_arr.shape[0] == image_size[1] and masks_arr.shape[1] == image_size[0]:
|
| 101 |
+
# shape likely (H, W, N) -> transpose to (N, H, W)
|
| 102 |
+
masks_arr = masks_arr.transpose(2, 0, 1)
|
| 103 |
+
|
| 104 |
+
H, W = image_size[1], image_size[0]
|
| 105 |
+
combined = np.zeros((H, W, 3), dtype=np.uint8)
|
| 106 |
+
|
| 107 |
+
palette = sv.ColorPalette.from_hex([
|
| 108 |
+
"#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF",
|
| 109 |
+
"#800000", "#008000", "#000080", "#808000", "#800080", "#008080"
|
| 110 |
+
])
|
| 111 |
+
palette_rgb = [tuple(int(h.lstrip("#")[i:i+2], 16) for i in (0, 2, 4)) for h in palette.hex_list]
|
| 112 |
+
|
| 113 |
+
for i in range(masks_arr.shape[0]):
|
| 114 |
+
mask = masks_arr[i].astype(bool)
|
| 115 |
+
color = palette_rgb[i % len(palette_rgb)]
|
| 116 |
+
# paint color where mask is True, simple overwrite (later instances will overwrite earlier)
|
| 117 |
+
combined[mask] = color
|
| 118 |
+
|
| 119 |
+
Image.fromarray(combined).save(out_path)
|
| 120 |
+
print(f"[INFO] Saved combined color mask to: {out_path}")
|
| 121 |
+
return True
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def main():
|
| 125 |
+
parser = argparse.ArgumentParser()
|
| 126 |
+
parser.add_argument("--image", required=True, help="Path or URL to input image")
|
| 127 |
+
parser.add_argument("--weights-url", help="HF resolve URL to checkpoint .pth (will be downloaded)")
|
| 128 |
+
parser.add_argument("--weights", help="Local path to checkpoint .pth")
|
| 129 |
+
parser.add_argument("--threshold", type=float, default=0.3, help="Confidence threshold")
|
| 130 |
+
parser.add_argument("--out", default="annotated.png", help="Path to save annotated overlay image")
|
| 131 |
+
parser.add_argument("--save-mask", default=None, help="Path to save combined color mask PNG (optional)")
|
| 132 |
+
parser.add_argument("--no-optimize", action="store_true", help="Skip optimize_for_inference()")
|
| 133 |
+
args = parser.parse_args()
|
| 134 |
+
|
| 135 |
+
# resolve weights: prioritize local --weights, then --weights-url
|
| 136 |
+
weights_path = None
|
| 137 |
+
if args.weights:
|
| 138 |
+
if not os.path.exists(args.weights):
|
| 139 |
+
raise FileNotFoundError(f"Weights file not found: {args.weights}")
|
| 140 |
+
weights_path = args.weights
|
| 141 |
+
elif args.weights_url:
|
| 142 |
+
# pick filename from url last segment
|
| 143 |
+
fname = os.path.basename(args.weights_url.split("?")[0])
|
| 144 |
+
if not fname:
|
| 145 |
+
fname = "checkpoint_best_total.pth"
|
| 146 |
+
weights_path = os.path.abspath(fname)
|
| 147 |
+
if not os.path.exists(weights_path):
|
| 148 |
+
download_file(args.weights_url, weights_path)
|
| 149 |
+
else:
|
| 150 |
+
weights_path = None # will use internal default if RFC allows
|
| 151 |
+
|
| 152 |
+
# load image (PIL)
|
| 153 |
+
image = load_image(args.image)
|
| 154 |
+
print(f"[INFO] Image loaded: {args.image} (size={image.size})")
|
| 155 |
+
|
| 156 |
+
# instantiate model
|
| 157 |
+
if weights_path:
|
| 158 |
+
model = RFDETRSegPreview(pretrain_weights=weights_path)
|
| 159 |
+
else:
|
| 160 |
+
model = RFDETRSegPreview()
|
| 161 |
+
|
| 162 |
+
if not args.no_optimize:
|
| 163 |
+
try:
|
| 164 |
+
model.optimize_for_inference()
|
| 165 |
+
except Exception as e:
|
| 166 |
+
print(f"[WARN] optimize_for_inference() failed or skipped: {e}")
|
| 167 |
+
|
| 168 |
+
# model.predict accepts PIL.Image or path
|
| 169 |
+
detections = model.predict(image, threshold=args.threshold)
|
| 170 |
+
print("[INFO] Inference done. Found", len(detections.boxes) if hasattr(detections, "boxes") else getattr(detections, "xyxy", "N/A"))
|
| 171 |
+
|
| 172 |
+
# annotate
|
| 173 |
+
# If you trained on custom classes the model should include class mapping. If not,
|
| 174 |
+
# you can pass classes dict e.g. {0: "Tulsi", 1: "Leaf"} depending on your dataset.
|
| 175 |
+
annotated = annotate_segmentation(image, detections, classes=None)
|
| 176 |
+
annotated.save(args.out)
|
| 177 |
+
print(f"[INFO] Saved annotated image to: {args.out}")
|
| 178 |
+
|
| 179 |
+
# optional combined color mask (per-instance overlay)
|
| 180 |
+
if args.save_mask:
|
| 181 |
+
ok = save_combined_color_mask(detections, args.save_mask, image_size=image.size)
|
| 182 |
+
if not ok:
|
| 183 |
+
print("[INFO] Combined mask not created (no mask data).")
|
| 184 |
+
|
| 185 |
+
# Also return annotated PIL object for interactive sessions
|
| 186 |
+
return annotated
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
main()
|