Image Segmentation
Transformers
grounding
instance-segmentation
polygon-prediction
baseline
research-code
Instructions to use royguw/ft_qwen3_5 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use royguw/ft_qwen3_5 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-segmentation", model="royguw/ft_qwen3_5")# pip install -U transformers accelerate # Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("royguw/ft_qwen3_5", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Download scripts/visualize_preprocessing.py from royguw/ft_qwen3_5: direct link, hf CLI and curl.
- Browser
- Download file 9.68 kB
-
https://huggingface.co/royguw/ft_qwen3_5/resolve/main/scripts/visualize_preprocessing.py
- Command line
-
hf download hf://royguw/ft_qwen3_5/scripts/visualize_preprocessing.py
-
curl -L -o visualize_preprocessing.py https://huggingface.co/royguw/ft_qwen3_5/resolve/main/scripts/visualize_preprocessing.py
9.68 kB
| """ | |
| Visualize ft_qwen35 data preprocessing: polygon outlines + char span highlights. | |
| For each sample, draws: | |
| - Left: original image with polygon outlines (one color per instance, reading order) | |
| - Right: grounding text with char spans highlighted in matching colors | |
| - Bottom: formatted target text (normalized coords + spans) | |
| Usage: | |
| /opt/conda/bin/python scripts/visualize_preprocessing.py \ | |
| --dataset refcoco --split val --num_samples 5 --seed 42 | |
| /opt/conda/bin/python scripts/visualize_preprocessing.py \ | |
| --dataset coconut_pancap --split val --num_samples 3 | |
| /opt/conda/bin/python scripts/visualize_preprocessing.py \ | |
| --dataset coconut_pos_neg --split val --num_samples 3 | |
| """ | |
| import argparse | |
| import logging | |
| import sys | |
| import os | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| import matplotlib.patches as mpatches | |
| from matplotlib.colors import to_rgb | |
| from PIL import Image, ImageDraw | |
| sys.path.insert(0, "/weka-mm/royg/ground_olmo") | |
| sys.path.insert(0, "/weka-mm/royg/ft_qwen3_5") | |
| from ft_qwen35.data.dataset import GroundingSourceDataset, make_random_state | |
| from ft_qwen35.data.formatter import extract_instance_polygons, format_target_text, subsample_polygon | |
| from ft_qwen35.config import FTQwen35Config | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | |
| logger = logging.getLogger(__name__) | |
| # Distinct colors for up to ~20 instances | |
| COLORS = [ | |
| "#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231", | |
| "#911eb4", "#42d4f4", "#f032e6", "#bfef45", "#fabed4", | |
| "#469990", "#dcbeff", "#9A6324", "#800000", "#aaffc3", | |
| "#808000", "#ffd8b1", "#000075", "#a9a9a9", "#ffffff", | |
| ] | |
| def draw_polygons_on_image(pil_image, instances_data, instance_order, max_poly_points=0): | |
| """Draw polygon outlines on image, one color per instance in reading order. | |
| Uses subsampled points (matching target text) when max_poly_points > 0. | |
| Also draws dots at each polygon vertex to show the actual sampled points. | |
| """ | |
| img = pil_image.copy() | |
| draw = ImageDraw.Draw(img) | |
| legend = [] # (color, label) | |
| for rank, idx in enumerate(instance_order): | |
| if idx >= len(instances_data): | |
| continue | |
| inst = instances_data[idx] | |
| polygons = inst.get("polygons", []) | |
| char_spans = inst.get("char_spans", []) | |
| color = COLORS[rank % len(COLORS)] | |
| for poly_points in polygons: | |
| if len(poly_points) < 3: | |
| continue | |
| # Apply same subsampling as format_target_text | |
| if max_poly_points > 0: | |
| poly_points = subsample_polygon(poly_points, max_poly_points) | |
| # Draw polygon outline | |
| flat = [] | |
| for x, y in poly_points: | |
| flat.extend([x, y]) | |
| # Close the polygon | |
| flat.extend([poly_points[0][0], poly_points[0][1]]) | |
| draw.line(flat, fill=color, width=3) | |
| # Draw dots at each vertex | |
| dot_r = 4 | |
| for x, y in poly_points: | |
| draw.ellipse([x - dot_r, y - dot_r, x + dot_r, y + dot_r], fill=color) | |
| n_pts = sum(len(subsample_polygon(p, max_poly_points) if max_poly_points > 0 else p) | |
| for p in inst.get("polygons", [])) | |
| span_str = ", ".join(f"[{s}:{e}]" for s, e in char_spans) | |
| legend.append((color, f"inst {idx} ({n_pts} pts, spans: {span_str})")) | |
| return img, legend | |
| def render_colored_text(ax, grounding_text, instances_data, instance_order): | |
| """Render grounding text with char spans highlighted in instance colors.""" | |
| # Build a color map: char_index -> color | |
| char_colors = [None] * len(grounding_text) | |
| for rank, idx in enumerate(instance_order): | |
| if idx >= len(instances_data): | |
| continue | |
| inst = instances_data[idx] | |
| color = COLORS[rank % len(COLORS)] | |
| for s, e in inst.get("char_spans", []): | |
| for ci in range(s, min(e, len(grounding_text))): | |
| char_colors[ci] = color | |
| ax.set_xlim(0, 1) | |
| ax.set_ylim(0, 1) | |
| ax.axis("off") | |
| # Render text with colored backgrounds, wrapping lines | |
| fontsize = 12 | |
| x, y = 0.02, 0.92 | |
| line_height = 0.06 | |
| char_width = 0.012 # approximate monospace width | |
| for i, ch in enumerate(grounding_text): | |
| if x > 0.95: | |
| x = 0.02 | |
| y -= line_height | |
| if y < 0.02: | |
| break | |
| bg = char_colors[i] | |
| if bg: | |
| ax.text(x, y, ch, fontsize=fontsize, family="monospace", | |
| va="top", ha="left", | |
| bbox=dict(boxstyle="round,pad=0.05", facecolor=bg, alpha=0.7, edgecolor="none")) | |
| else: | |
| ax.text(x, y, ch, fontsize=fontsize, family="monospace", | |
| va="top", ha="left", color="black") | |
| x += char_width | |
| def visualize_sample(example, sample_idx, dataset_name, output_dir, config): | |
| """Visualize one preprocessed sample.""" | |
| image_path = example.get("image") | |
| if image_path is None: | |
| logger.warning(f"Sample {sample_idx}: no image path, skipping") | |
| return | |
| category_name = example.get("category_name", "") | |
| instances = example.get("instances", []) | |
| instance_order = example.get("instance_order", list(range(len(instances)))) | |
| char_spans = example.get("char_spans_per_instance", []) | |
| # Open original image | |
| pil_image = Image.open(image_path).convert("RGB") | |
| orig_w, orig_h = pil_image.size | |
| # Extract polygons (same as preprocessor) | |
| instances_data = [] | |
| for i, inst in enumerate(instances): | |
| polygons, source = extract_instance_polygons(inst) | |
| inst_char_spans = char_spans[i] if i < len(char_spans) else [] | |
| instances_data.append({ | |
| "polygons": polygons, | |
| "char_spans": inst_char_spans, | |
| "polygon_source": source, | |
| }) | |
| # Format target text (same as preprocessor) | |
| target_text = format_target_text( | |
| instances_data=instances_data, | |
| instance_order=instance_order, | |
| orig_h=orig_h, | |
| orig_w=orig_w, | |
| coord_range=config.coord_range, | |
| max_poly_points=config.max_poly_points, | |
| ) | |
| # Draw polygons on image (with same subsampling as target text) | |
| annotated_img, legend = draw_polygons_on_image( | |
| pil_image, instances_data, instance_order, max_poly_points=config.max_poly_points | |
| ) | |
| # Create figure | |
| n_instances = len([i for i in instance_order if i < len(instances_data)]) | |
| fig = plt.figure(figsize=(18, 10)) | |
| # Top-left: annotated image | |
| ax_img = fig.add_axes([0.02, 0.30, 0.50, 0.65]) | |
| ax_img.imshow(np.array(annotated_img)) | |
| ax_img.set_title(f"{dataset_name} idx={sample_idx} ({orig_w}x{orig_h}, {n_instances} instances)", | |
| fontsize=11) | |
| ax_img.axis("off") | |
| # Top-right: grounding text with colored char spans | |
| ax_text = fig.add_axes([0.54, 0.30, 0.44, 0.65]) | |
| ax_text.set_title("Grounding text (char spans highlighted)", fontsize=11) | |
| render_colored_text(ax_text, category_name, instances_data, instance_order) | |
| # Legend | |
| handles = [] | |
| for color, label in legend: | |
| handles.append(mpatches.Patch(color=color, label=label)) | |
| if handles: | |
| ax_text.legend(handles=handles, loc="lower left", fontsize=8, ncol=1) | |
| # Bottom: target text (full, no truncation) | |
| # Estimate height needed: ~1 line per instance + header | |
| target_lines = target_text.split("\n") | |
| n_target_lines = len(target_lines) | |
| # Each line needs ~0.025 of figure height at fontsize 7 | |
| target_height = max(0.25, min(0.55, 0.04 + n_target_lines * 0.025)) | |
| # Adjust figure: shift image/text panels up, expand bottom | |
| fig.set_size_inches(18, 10 + max(0, (target_height - 0.25) * 10)) | |
| ax_target = fig.add_axes([0.02, 0.02, 0.96, target_height]) | |
| ax_target.axis("off") | |
| ax_target.text(0.0, 1.0, f"Target text ({n_target_lines} lines):\n{target_text}", | |
| fontsize=7, family="monospace", va="top", ha="left", | |
| transform=ax_target.transAxes) | |
| out_path = os.path.join(output_dir, f"{dataset_name}_{sample_idx:04d}.png") | |
| fig.savefig(out_path, dpi=150, bbox_inches="tight", facecolor="white") | |
| plt.close(fig) | |
| logger.info(f"Saved: {out_path}") | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Visualize ft_qwen35 preprocessing") | |
| parser.add_argument("--dataset", type=str, default="refcoco", | |
| help="Dataset name from DATASET_REGISTRY") | |
| parser.add_argument("--split", type=str, default="val") | |
| parser.add_argument("--num_samples", type=int, default=5) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--output_dir", type=str, default="data/vis") | |
| parser.add_argument("--max_poly_points", type=int, default=64) | |
| parser.add_argument("--start_idx", type=int, default=0) | |
| args = parser.parse_args() | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| config = FTQwen35Config(max_poly_points=args.max_poly_points) | |
| logger.info(f"Loading {args.dataset} ({args.split})...") | |
| ds = GroundingSourceDataset(args.dataset, split=args.split) | |
| logger.info(f"Dataset size: {len(ds)}") | |
| n = min(args.num_samples, len(ds) - args.start_idx) | |
| for i in range(n): | |
| idx = args.start_idx + i | |
| rng = make_random_state(args.seed, idx, 0, 1) | |
| try: | |
| example = ds.get(idx, rng) | |
| visualize_sample(example, idx, args.dataset, args.output_dir, config) | |
| except Exception as e: | |
| logger.error(f"Failed on sample {idx}: {e}") | |
| if __name__ == "__main__": | |
| main() | |