firgiawann commited on
Commit
420e2a4
·
verified ·
1 Parent(s): 48423a6

Add all-classes detection scope and clarify Best.pt class behavior (update 25)

Browse files
Files changed (3) hide show
  1. CHANGELOG.md +6 -0
  2. README.md +2 -0
  3. app.py +90 -16
CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
  # Changelog
2
 
 
 
 
 
 
 
3
  ## Update ke-24 - 2026-04-21
4
  - Fix runtime crash pada Gradio lama: hapus argumen `show_download_button` dari `gr.Image`.
5
  - Zoom/akses gambar hasil tetap tersedia melalui file output evaluasi lokal.
 
1
  # Changelog
2
 
3
+ ## Update ke-25 - 2026-04-21
4
+ - Tambah opsi `Scope Deteksi`: `Person saja` atau `Semua Kelas`.
5
+ - Mode `Semua Kelas` menampilkan semua kelas yang tersedia pada model, termasuk `Best.pt` jika bobot training memang memiliki kelas tersebut.
6
+ - Evaluasi tetap memakai jumlah deteksi `person` untuk confusion matrix `Person` vs `Not Person/Background`.
7
+ - Minor update dinaikkan ke-25.
8
+
9
  ## Update ke-24 - 2026-04-21
10
  - Fix runtime crash pada Gradio lama: hapus argumen `show_download_button` dari `gr.Image`.
11
  - Zoom/akses gambar hasil tetap tersedia melalui file output evaluasi lokal.
README.md CHANGED
@@ -34,6 +34,7 @@ Versi ini difokuskan untuk tahap awal:
34
  - input gambar (upload/webcam)
35
  - confidence threshold
36
  - advanced options:
 
37
  - gaya anotasi `Border + Label` atau `Label saja`
38
  - tombol proses
39
  - **Section 2 - Hasil Processing**
@@ -57,6 +58,7 @@ Catatan:
57
  - hasil confidence rendah/tinggi dapat diamati melalui slider confidence dan arsip CSV evaluasi.
58
  - UI otomatis menyesuaikan mode gelap perangkat (dark mode).
59
  - output gambar dapat diperbesar melalui file hasil evaluasi yang tersimpan.
 
60
 
61
  ## File Penting
62
 
 
34
  - input gambar (upload/webcam)
35
  - confidence threshold
36
  - advanced options:
37
+ - scope deteksi `Person saja` atau `Semua Kelas`
38
  - gaya anotasi `Border + Label` atau `Label saja`
39
  - tombol proses
40
  - **Section 2 - Hasil Processing**
 
58
  - hasil confidence rendah/tinggi dapat diamati melalui slider confidence dan arsip CSV evaluasi.
59
  - UI otomatis menyesuaikan mode gelap perangkat (dark mode).
60
  - output gambar dapat diperbesar melalui file hasil evaluasi yang tersimpan.
61
+ - `Best.pt` mengikuti kelas yang memang tersedia pada model hasil training.
62
 
63
  ## File Penting
64
 
app.py CHANGED
@@ -24,7 +24,7 @@ from ultralytics import YOLO
24
  CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
25
  EVAL_CLASSES = ["Person", "Not Person/Background"]
26
  APP_VERSION = os.getenv("APP_VERSION", "v0.9.0")
27
- APP_MINOR_UPDATE = os.getenv("APP_MINOR_UPDATE", "24")
28
 
29
 
30
  # Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
@@ -165,25 +165,90 @@ def _annotate_person_instances(
165
  return annotated, len(person_boxes)
166
 
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  def infer_image(
169
  image: np.ndarray,
170
  conf_threshold: float,
171
  model_choice: str,
172
  annotation_style: str,
 
173
  ) -> Tuple[np.ndarray, int]:
174
  if image is None:
175
  raise ValueError("Silakan unggah gambar atau gunakan kamera.")
176
  model = load_model(model_choice)
177
  person_id = _resolve_person_class_id_from_names(getattr(model, "names", {}))
178
  bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
179
- result = model.predict(
180
- source=bgr,
181
- conf=conf_threshold,
182
- classes=[person_id],
183
- verbose=False,
184
- )[0]
185
- person_id = _resolve_person_class_id(result)
186
- annotated, detected_count = _annotate_person_instances(image, result, person_id, annotation_style)
 
 
 
 
 
 
 
 
187
  return annotated, detected_count
188
 
189
 
@@ -318,11 +383,12 @@ def run_check_and_classify(
318
  model_choice: str,
319
  inference_mode: str,
320
  annotation_style: str,
 
321
  ) -> Tuple[str | np.ndarray, str, np.ndarray, str, str, str | None, str | None]:
322
  try:
323
  if inference_mode == "Bandingkan (YOLOv8n vs Best.pt)":
324
- ann_before, det_before = infer_image(image, conf_threshold, "YOLOv8n", annotation_style)
325
- ann_after, det_after = infer_image(image, conf_threshold, "Best.pt", annotation_style)
326
  pred_before = classify_person_vs_background(det_before)
327
  pred_after = classify_person_vs_background(det_after)
328
  combined = _merge_annotated_images(ann_before, ann_after)
@@ -338,14 +404,15 @@ def run_check_and_classify(
338
  summary = (
339
  "### Ringkasan Perbandingan Model\n"
340
  f"- Confidence threshold: **{conf_threshold:.2f}**\n"
 
341
  f"- **YOLOv8n**: person terdeteksi={det_before}, prediksi kelas={pred_before}\n"
342
  f"- **Best.pt**: person terdeteksi={det_after}, prediksi kelas={pred_after}\n"
343
- "- Catatan evaluasi: confusion matrix memakai prediksi **Best.pt** terhadap label aktual manual."
344
  )
345
  pred_md = f"Label prediksi evaluasi (Best.pt): **{pred_after}**"
346
  return saved_image_path or combined, summary, chart, pred_after, pred_md, saved_image_path, saved_csv_path
347
 
348
- annotated, detected = infer_image(image, conf_threshold, model_choice, annotation_style)
349
  status_presence = classify_presence(detected)
350
  predicted_label = classify_person_vs_background(detected)
351
  saved_image_path, saved_csv_path = save_detection_artifacts(
@@ -362,9 +429,10 @@ def run_check_and_classify(
362
  f"- Klasifikasi keberadaan: **{status_presence}**\n"
363
  f"- Kelas prediksi evaluasi: **{predicted_label}**\n"
364
  f"- Confidence threshold: **{conf_threshold:.2f}**\n"
 
365
  f"- Model digunakan: **{model_choice}**\n"
366
  f"- Gaya anotasi: **{annotation_style}**\n"
367
- "- Label objek: **person 1, person 2, ...**\n"
368
  f"- Arsip evaluasi lokal: **{saved_csv_path or '-'}**"
369
  )
370
  chart = draw_detection_chart(detected)
@@ -1336,11 +1404,17 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
1336
  )
1337
  conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Parameter Confidence (Deteksi)")
1338
  with gr.Accordion("Advanced Options", open=False, elem_classes=["advanced-box"]):
 
 
 
 
 
 
1339
  annotation_style = gr.Radio(
1340
  choices=["Border + Label", "Label saja"],
1341
  value="Border + Label",
1342
  label="Gaya anotasi objek",
1343
- info="Pilih tampilan bbox atau label-only untuk person 1, person 2, ...",
1344
  )
1345
  run_btn = gr.Button("Jalankan Deteksi dan Klasifikasi", variant="primary")
1346
 
@@ -1413,7 +1487,7 @@ with gr.Blocks(title="Pengecekan dan Klasifikasi Mahasiswa - YOLOv8") as demo:
1413
 
1414
  run_btn_evt = run_btn.click(
1415
  fn=run_check_and_classify,
1416
- inputs=[image_input, conf_input, model_choice, inference_mode, annotation_style],
1417
  outputs=[
1418
  output_image,
1419
  class_result_md,
 
24
  CM_INIT = {"tp": 0, "fp": 0, "fn": 0, "tn": 0}
25
  EVAL_CLASSES = ["Person", "Not Person/Background"]
26
  APP_VERSION = os.getenv("APP_VERSION", "v0.9.0")
27
+ APP_MINOR_UPDATE = os.getenv("APP_MINOR_UPDATE", "25")
28
 
29
 
30
  # Gradio/Spaces can trigger noisy asyncio cleanup traces ("Invalid file descriptor: -1")
 
165
  return annotated, len(person_boxes)
166
 
167
 
168
+ def _annotate_all_instances(
169
+ image_rgb: np.ndarray,
170
+ result: Any,
171
+ annotation_style: str,
172
+ ) -> Tuple[np.ndarray, int]:
173
+ annotated = image_rgb.copy()
174
+ if result.boxes is None:
175
+ return annotated, 0
176
+
177
+ classes = result.boxes.cls.cpu().numpy()
178
+ boxes = result.boxes.xyxy.cpu().numpy()
179
+ names = getattr(result, "names", {})
180
+ count = 0
181
+
182
+ for i, (x1, y1, x2, y2) in enumerate(boxes.tolist(), start=1):
183
+ cls_id = int(classes[i - 1])
184
+ if isinstance(names, dict):
185
+ cls_name = str(names.get(cls_id, f"class_{cls_id}"))
186
+ elif isinstance(names, list) and 0 <= cls_id < len(names):
187
+ cls_name = str(names[cls_id])
188
+ else:
189
+ cls_name = f"class_{cls_id}"
190
+
191
+ if annotation_style == "Border + Label":
192
+ cv2.rectangle(annotated, (int(x1), int(y1)), (int(x2), int(y2)), (59, 130, 246), 2)
193
+ label = f"{cls_name} {i}"
194
+ (tw, th), baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
195
+ if annotation_style == "Label saja":
196
+ label_x = max(0, min(int(x1), annotated.shape[1] - tw - 8))
197
+ label_y = max(th + 4, min(int(y1) + th + 4, annotated.shape[0] - 6))
198
+ text_y1 = max(0, label_y - th - baseline - 6)
199
+ text_y2 = min(annotated.shape[0], label_y + 2)
200
+ text_x1 = label_x
201
+ text_x2 = min(annotated.shape[1], label_x + tw + 10)
202
+ text_org = (label_x + 4, label_y - 4)
203
+ else:
204
+ text_y1 = max(0, int(y1) - th - baseline - 6)
205
+ text_y2 = int(y1)
206
+ text_x1 = int(x1)
207
+ text_x2 = min(annotated.shape[1], int(x1) + tw + 10)
208
+ text_org = (int(x1) + 4, max(14, int(y1) - 6))
209
+ cv2.rectangle(annotated, (text_x1, text_y1), (text_x2, text_y2), (59, 130, 246), -1)
210
+ cv2.putText(
211
+ annotated,
212
+ label,
213
+ text_org,
214
+ cv2.FONT_HERSHEY_SIMPLEX,
215
+ 0.6,
216
+ (255, 255, 255),
217
+ 2,
218
+ cv2.LINE_AA,
219
+ )
220
+ count += 1
221
+ return annotated, count
222
+
223
+
224
  def infer_image(
225
  image: np.ndarray,
226
  conf_threshold: float,
227
  model_choice: str,
228
  annotation_style: str,
229
+ detection_scope: str,
230
  ) -> Tuple[np.ndarray, int]:
231
  if image is None:
232
  raise ValueError("Silakan unggah gambar atau gunakan kamera.")
233
  model = load_model(model_choice)
234
  person_id = _resolve_person_class_id_from_names(getattr(model, "names", {}))
235
  bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
236
+ predict_kwargs = {
237
+ "source": bgr,
238
+ "conf": conf_threshold,
239
+ "verbose": False,
240
+ }
241
+ if detection_scope == "Person saja":
242
+ predict_kwargs["classes"] = [person_id]
243
+ result = model.predict(**predict_kwargs)[0]
244
+
245
+ if detection_scope == "Semua Kelas":
246
+ annotated, _ = _annotate_all_instances(image, result, annotation_style)
247
+ cls = result.boxes.cls.cpu().numpy() if result.boxes is not None else np.array([])
248
+ detected_count = int(np.sum(cls == person_id))
249
+ else:
250
+ person_id = _resolve_person_class_id(result)
251
+ annotated, detected_count = _annotate_person_instances(image, result, person_id, annotation_style)
252
  return annotated, detected_count
253
 
254
 
 
383
  model_choice: str,
384
  inference_mode: str,
385
  annotation_style: str,
386
+ detection_scope: str,
387
  ) -> Tuple[str | np.ndarray, str, np.ndarray, str, str, str | None, str | None]:
388
  try:
389
  if inference_mode == "Bandingkan (YOLOv8n vs Best.pt)":
390
+ ann_before, det_before = infer_image(image, conf_threshold, "YOLOv8n", annotation_style, detection_scope)
391
+ ann_after, det_after = infer_image(image, conf_threshold, "Best.pt", annotation_style, detection_scope)
392
  pred_before = classify_person_vs_background(det_before)
393
  pred_after = classify_person_vs_background(det_after)
394
  combined = _merge_annotated_images(ann_before, ann_after)
 
404
  summary = (
405
  "### Ringkasan Perbandingan Model\n"
406
  f"- Confidence threshold: **{conf_threshold:.2f}**\n"
407
+ f"- Scope deteksi: **{detection_scope}**\n"
408
  f"- **YOLOv8n**: person terdeteksi={det_before}, prediksi kelas={pred_before}\n"
409
  f"- **Best.pt**: person terdeteksi={det_after}, prediksi kelas={pred_after}\n"
410
+ "- Catatan evaluasi: confusion matrix memakai jumlah deteksi `person` dari **Best.pt** terhadap label aktual manual."
411
  )
412
  pred_md = f"Label prediksi evaluasi (Best.pt): **{pred_after}**"
413
  return saved_image_path or combined, summary, chart, pred_after, pred_md, saved_image_path, saved_csv_path
414
 
415
+ annotated, detected = infer_image(image, conf_threshold, model_choice, annotation_style, detection_scope)
416
  status_presence = classify_presence(detected)
417
  predicted_label = classify_person_vs_background(detected)
418
  saved_image_path, saved_csv_path = save_detection_artifacts(
 
429
  f"- Klasifikasi keberadaan: **{status_presence}**\n"
430
  f"- Kelas prediksi evaluasi: **{predicted_label}**\n"
431
  f"- Confidence threshold: **{conf_threshold:.2f}**\n"
432
+ f"- Scope deteksi: **{detection_scope}**\n"
433
  f"- Model digunakan: **{model_choice}**\n"
434
  f"- Gaya anotasi: **{annotation_style}**\n"
435
+ "- Label objek mengikuti kelas aktif pada model\n"
436
  f"- Arsip evaluasi lokal: **{saved_csv_path or '-'}**"
437
  )
438
  chart = draw_detection_chart(detected)
 
1404
  )
1405
  conf_input = gr.Slider(0.1, 1.0, value=0.25, step=0.05, label="Parameter Confidence (Deteksi)")
1406
  with gr.Accordion("Advanced Options", open=False, elem_classes=["advanced-box"]):
1407
+ detection_scope = gr.Radio(
1408
+ choices=["Person saja", "Semua Kelas"],
1409
+ value="Person saja",
1410
+ label="Scope deteksi",
1411
+ info="`Best.pt` akan mengikuti kelas yang tersedia pada bobot hasil training.",
1412
+ )
1413
  annotation_style = gr.Radio(
1414
  choices=["Border + Label", "Label saja"],
1415
  value="Border + Label",
1416
  label="Gaya anotasi objek",
1417
+ info="Pilih tampilan bbox atau label-only untuk label objek yang terdeteksi.",
1418
  )
1419
  run_btn = gr.Button("Jalankan Deteksi dan Klasifikasi", variant="primary")
1420
 
 
1487
 
1488
  run_btn_evt = run_btn.click(
1489
  fn=run_check_and_classify,
1490
+ inputs=[image_input, conf_input, model_choice, inference_mode, annotation_style, detection_scope],
1491
  outputs=[
1492
  output_image,
1493
  class_result_md,