File size: 3,708 Bytes
c97431f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Segmentation routes: panoptic polygon extraction and bundle generation."""

import numpy as np
import torch
from fastapi import APIRouter, File, Form, UploadFile

from config.models import ONEFORMER_MODEL_NAME
from models.loader import _load_segmentation_model
from services.image.loading import load_uploaded_rgb_image
from services.image.polygons import mask_to_polygons
from services.pipeline.builder import build_segmentation_bundle
from state import class_name_for_id

router = APIRouter(tags=["segmentation"])


def build_oneformer_polygon_response(
    contents: bytes,
    *,
    threshold: float = 0.5,
    mask_threshold: float = 0.5,
    min_area: float = 32.0,
    simplify_epsilon: float = 2.0,
) -> dict:
    img, img_np = load_uploaded_rgb_image(contents)
    h, w = img_np.shape[:2]

    threshold = float(np.clip(threshold, 0.0, 1.0))
    mask_threshold = float(np.clip(mask_threshold, 0.0, 1.0))
    min_area = max(0.0, float(min_area))
    simplify_epsilon = max(0.0, float(simplify_epsilon))

    _load_segmentation_model()

    import state as _state
    inputs = _state.seg_processor(
        images=img,
        task_inputs=["panoptic"],
        return_tensors="pt",
    ).to(_state.device)
    with torch.no_grad():
        outputs = _state.seg_model(**inputs)

    result = _state.seg_processor.post_process_panoptic_segmentation(
        outputs,
        threshold=threshold,
        mask_threshold=mask_threshold,
        target_sizes=[(h, w)],
    )[0]
    segmentation = result.get("segmentation")
    if segmentation is None:
        return {
            "model": ONEFORMER_MODEL_NAME,
            "task": "panoptic",
            "width": int(w),
            "height": int(h),
            "segments": [],
        }

    if isinstance(segmentation, torch.Tensor):
        segment_map = segmentation.cpu().numpy()
    else:
        segment_map = np.asarray(segmentation)

    segments = []
    for segment_info in result.get("segments_info", []):
        segment_id = int(segment_info["id"])
        label_id = int(segment_info["label_id"])
        mask = segment_map == segment_id
        polygons = mask_to_polygons(mask, min_area, simplify_epsilon)
        if not polygons:
            continue

        score = segment_info.get("score")
        segments.append({
            "id": segment_id,
            "labelId": label_id,
            "label": class_name_for_id(label_id),
            "confidence": float(score) if score is not None else None,
            "wasFused": bool(segment_info.get("was_fused", False)),
            "pixelArea": int(mask.sum()),
            "polygons": polygons,
        })

    segments.sort(key=lambda item: item["pixelArea"], reverse=True)
    return {
        "model": ONEFORMER_MODEL_NAME,
        "task": "panoptic",
        "width": int(w),
        "height": int(h),
        "threshold": threshold,
        "maskThreshold": mask_threshold,
        "minArea": min_area,
        "simplifyEpsilon": simplify_epsilon,
        "segmentCount": len(segments),
        "segments": segments,
    }


@router.post("/oneformer/polygons")
async def oneformer_polygons(
    file: UploadFile = File(...),
    threshold: float = Form(0.5),
    mask_threshold: float = Form(0.5),
    min_area: float = Form(32.0),
    simplify_epsilon: float = Form(2.0),
):
    contents = await file.read()
    return build_oneformer_polygon_response(
        contents,
        threshold=threshold,
        mask_threshold=mask_threshold,
        min_area=min_area,
        simplify_epsilon=simplify_epsilon,
    )


@router.post("/segment")
async def segment(file: UploadFile = File(...)):
    contents = await file.read()
    return build_segmentation_bundle(contents)