yeonjung77 commited on
Commit
9fc67a4
·
verified ·
1 Parent(s): 38ec06a

Upload postprocess.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. postprocess.py +190 -0
postprocess.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """P3 후처리 -- Stage 1/2 결과 통합 + 박스 기반 Part 귀속 (Phase 4)
2
+
3
+ Stage 1(Mask R-CNN)이 뱉는 평면 인스턴스 리스트를 "본체(Main) 의류 + 그에 달린
4
+ 부위(Part)" 트리로 재구성한다. 핵심은 **단순 이미지 공존이 아니라 박스 IoU/포함도로
5
+ Part 를 가장 알맞은 Main 에 귀속**시키는 것 -- EDA 에서 본 부자연스러운 매핑
6
+ (pants→sleeve, shoe→sleeve 등 같은 사진에 있다는 이유만의 연결)을 차단한다.
7
+
8
+ 구성:
9
+ box_iou(a, b) -- 두 박스 [x1,y1,x2,y2] IoU
10
+ box_containment(part, main) -- Part 가 Main 에 포함된 비율 (intersection / part_area)
11
+ group_instances(...) -- 평면 리스트 → (mains_with_parts, orphan_parts)
12
+ build_response(...) -- 트리 + Stage 2 logits → 응답 JSON
13
+
14
+ [detection 형식] 각 인스턴스는 dict:
15
+ {"category_id": int(0~45 원본), "category": str, "box": [x1,y1,x2,y2], "score": float}
16
+ Main 인스턴스에는 pipeline 이 "attr_index"(Stage 2 logits 행 번호)를 달아 둔다.
17
+
18
+ - utils.py / model.py / dataset.py 등과 양식 통일.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Dict, List, Optional, Sequence, Tuple
24
+
25
+ import numpy as np
26
+
27
+
28
+ # ============================================================================
29
+ # 1. 기하 -- 박스 IoU / 포함도
30
+ # ============================================================================
31
+
32
+ def box_iou(box_a: Sequence[float], box_b: Sequence[float]) -> float:
33
+ """두 박스 [x1, y1, x2, y2] 의 IoU (교집합 / 합집합).
34
+
35
+ Args:
36
+ box_a, box_b: [x1, y1, x2, y2] 형식 박스.
37
+
38
+ Returns:
39
+ float: IoU (0.0 ~ 1.0). 겹치지 않으면 0.0.
40
+ """
41
+ inter = _intersection_area(box_a, box_b)
42
+ if inter <= 0:
43
+ return 0.0
44
+ area_a = max(0.0, box_a[2] - box_a[0]) * max(0.0, box_a[3] - box_a[1])
45
+ area_b = max(0.0, box_b[2] - box_b[0]) * max(0.0, box_b[3] - box_b[1])
46
+ union = area_a + area_b - inter
47
+ return inter / union if union > 0 else 0.0
48
+
49
+
50
+ def box_containment(part_box: Sequence[float], main_box: Sequence[float]) -> float:
51
+ """Part 박스가 Main 박스에 얼마나 들어가 있나 = 교집합 / Part 넓이.
52
+
53
+ IoU 와 달리 크기 차이에 둔감해, "작은 소매가 큰 상의 안에 거의 들어 있다"
54
+ 같은 포함 관계를 잘 잡는다.
55
+
56
+ Args:
57
+ part_box: 포함되는 쪽(작은) 박스 [x1,y1,x2,y2].
58
+ main_box: 포함하는 쪽(큰) 박스 [x1,y1,x2,y2].
59
+
60
+ Returns:
61
+ float: 포함 비율 (0.0 ~ 1.0). Part 넓이가 0이면 0.0.
62
+ """
63
+ inter = _intersection_area(part_box, main_box)
64
+ part_area = max(0.0, part_box[2] - part_box[0]) * max(0.0, part_box[3] - part_box[1])
65
+ return inter / part_area if part_area > 0 else 0.0
66
+
67
+
68
+ def _intersection_area(box_a: Sequence[float], box_b: Sequence[float]) -> float:
69
+ """두 박스의 교집합 넓이."""
70
+ x1 = max(box_a[0], box_b[0])
71
+ y1 = max(box_a[1], box_b[1])
72
+ x2 = min(box_a[2], box_b[2])
73
+ y2 = min(box_a[3], box_b[3])
74
+ return max(0.0, x2 - x1) * max(0.0, y2 - y1)
75
+
76
+
77
+ # ============================================================================
78
+ # 2. 인스턴스 그룹화 -- 평면 리스트 → Main 트리 + orphan
79
+ # ============================================================================
80
+
81
+ def group_instances(
82
+ detections: List[Dict],
83
+ main_ids: set,
84
+ part_ids: set,
85
+ iou_threshold: float = 0.1,
86
+ contain_threshold: float = 0.5,
87
+ ) -> Tuple[List[Dict], List[Dict]]:
88
+ """평면 detection 리스트를 Main(부위 포함) 트리로 재구성한다.
89
+
90
+ 각 Part 는 **IoU 와 포함도가 가장 큰 Main** 에 귀속된다. 단, 그 Main 과의
91
+ 관계가 `iou >= iou_threshold` 또는 `containment >= contain_threshold` 중
92
+ 하나라도 만족할 때만 귀속하고, 둘 다 아니면 orphan(고아 Part)으로 둔다.
93
+
94
+ Args:
95
+ detections: Stage 1 인스턴스 dict 리스트 ({category_id, box, score, ...}).
96
+ main_ids: Main 카테고리 ID 집합 (utils.load_category_ids).
97
+ part_ids: Part 카테고리 ID 집합.
98
+ iou_threshold: 귀속 판정 IoU 하한.
99
+ contain_threshold: 귀속 판정 포함도 하한.
100
+
101
+ Returns:
102
+ Tuple[List[Dict], List[Dict]]:
103
+ - mains_with_parts: Main dict 리스트. 각 dict 에 "parts": [Part dict, ...] 추가.
104
+ - orphan_parts: 어느 Main 에도 귀속되지 못한 Part dict 리스트.
105
+ """
106
+ mains = [dict(d, parts=[]) for d in detections if d["category_id"] in main_ids]
107
+ parts = [d for d in detections if d["category_id"] in part_ids]
108
+
109
+ orphan_parts: List[Dict] = []
110
+ for part in parts:
111
+ best_i, best_iou, best_cont, best_key = -1, 0.0, 0.0, -1.0
112
+ for i, main in enumerate(mains):
113
+ iou = box_iou(part["box"], main["box"])
114
+ cont = box_containment(part["box"], main["box"])
115
+ key = max(iou, cont) # IoU·포함도 중 큰 값으로 ���적 Main 선택
116
+ if key > best_key:
117
+ best_i, best_iou, best_cont, best_key = i, iou, cont, key
118
+
119
+ # 최적 Main 과의 관계가 임계값을 하나라도 넘으면 귀속, 아니면 orphan
120
+ if best_i >= 0 and (best_iou >= iou_threshold or best_cont >= contain_threshold):
121
+ mains[best_i]["parts"].append(part)
122
+ else:
123
+ orphan_parts.append(part)
124
+
125
+ return mains, orphan_parts
126
+
127
+
128
+ # ============================================================================
129
+ # 3. 응답 빌더 -- 트리 + Stage 2 속성 → JSON
130
+ # ============================================================================
131
+
132
+ def build_response(
133
+ mains_with_parts: List[Dict],
134
+ orphan_parts: List[Dict],
135
+ attribute_logits: Optional[np.ndarray],
136
+ threshold: float = 0.5,
137
+ id2attr_name: Optional[Sequence[str]] = None,
138
+ ) -> Dict:
139
+ """Main 트리 + Stage 2 logits 를 최종 응답 JSON 으로 만든다.
140
+
141
+ 각 Main 의 속성은 `attribute_logits[main["attr_index"]]` 를 sigmoid 한 뒤
142
+ threshold 를 넘는 속성만 모아 이름 리스트로 변환한다.
143
+
144
+ Args:
145
+ mains_with_parts: group_instances 의 첫 반환값 (각 Main 에 "attr_index" 포함).
146
+ orphan_parts: group_instances 의 둘째 반환값.
147
+ attribute_logits: Stage 2 raw logits [M, num_attrs] (M=Main 수). 없으면 속성 빈칸.
148
+ threshold: 속성 판정 임계값 (sigmoid 확률 기준).
149
+ id2attr_name: 속성 인덱스→이름. 없으면 "attr_<idx>" 로 표기.
150
+
151
+ Returns:
152
+ Dict: {"garments": [...], "orphan_parts": [...]}
153
+ """
154
+ logits = None if attribute_logits is None else np.asarray(attribute_logits)
155
+
156
+ garments = []
157
+ for main in mains_with_parts:
158
+ attrs: List[str] = []
159
+ idx = main.get("attr_index")
160
+ if logits is not None and idx is not None and 0 <= idx < len(logits):
161
+ probs = _sigmoid(logits[idx])
162
+ for a in np.where(probs > threshold)[0]:
163
+ attrs.append(id2attr_name[a] if id2attr_name is not None else f"attr_{a}")
164
+
165
+ garments.append({
166
+ "category": main.get("category", str(main["category_id"])),
167
+ "box": [float(v) for v in main["box"]],
168
+ "score": float(main["score"]),
169
+ "attributes": attrs,
170
+ "parts": [_part_dict(p) for p in main["parts"]],
171
+ })
172
+
173
+ return {
174
+ "garments": garments,
175
+ "orphan_parts": [_part_dict(p) for p in orphan_parts],
176
+ }
177
+
178
+
179
+ def _part_dict(p: Dict) -> Dict:
180
+ """Part 인스턴스를 응답용 최소 dict 로 정리."""
181
+ return {
182
+ "category": p.get("category", str(p["category_id"])),
183
+ "box": [float(v) for v in p["box"]],
184
+ "score": float(p["score"]),
185
+ }
186
+
187
+
188
+ def _sigmoid(x: np.ndarray) -> np.ndarray:
189
+ """수치 안정 sigmoid."""
190
+ return np.where(x >= 0, 1.0 / (1.0 + np.exp(-x)), np.exp(x) / (1.0 + np.exp(x)))