qonitasal commited on
Commit
7c1de4e
·
verified ·
1 Parent(s): cf2f67f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -22
app.py CHANGED
@@ -7,12 +7,11 @@ from ultralytics import YOLO
7
  from pathlib import Path
8
 
9
  # === Konfigurasi ===
10
- model_path = "best.pt"
11
  class_names = ['coral or rock', 'pipeline', 'ripple marks', 'shipwreck']
12
-
13
  model = YOLO(model_path)
14
 
15
- # === Fungsi untuk menggambar mask hasil deteksi ===
16
  def draw_predictions(img, segments, class_ids, confs, color=(255, 0, 0), alpha=0.5):
17
  overlay = img.copy()
18
  for i, seg in enumerate(segments):
@@ -21,31 +20,40 @@ def draw_predictions(img, segments, class_ids, confs, color=(255, 0, 0), alpha=0
21
  polygon[:, 1] *= img.shape[0]
22
  polygon = polygon.astype(np.int32)
23
 
24
- label = f"{class_names[int(class_ids[i])]} ({confs[i]:.2f})"
 
 
 
25
  cv2.fillPoly(overlay, [polygon], color)
 
 
26
  x, y, w, h = cv2.boundingRect(polygon)
27
- cv2.putText(overlay, label, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1)
28
- cv2.rectangle(overlay, (x, y), (x + w, y + h), color, 1)
 
 
 
29
 
30
  return cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
31
 
32
- # === Fungsi utama proses dan simpan report ===
33
- def process_image_and_generate_report(image):
34
  temp_path = "temp.jpg"
35
  image.save(temp_path)
36
  img = cv2.imread(temp_path)
37
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
38
 
39
- # Prediksi dari YOLOv8
40
  results = model(temp_path)[0]
41
  segs = [seg.xy for seg in results.masks] if results.masks else []
42
  cls_ids = results.boxes.cls.tolist() if results.boxes else []
43
  confs = results.boxes.conf.tolist() if results.boxes else []
44
  xywh = results.boxes.xywhn.tolist() if results.boxes else []
45
 
46
- img_result = draw_predictions(img.copy(), segs, cls_ids, confs)
 
47
 
48
- # Simpan CSV
49
  rows = []
50
  for i in range(len(cls_ids)):
51
  rows.append({
@@ -59,27 +67,25 @@ def process_image_and_generate_report(image):
59
  })
60
 
61
  df = pd.DataFrame(rows)
62
- csv_path = "detection_result.csv"
63
  df.to_csv(csv_path, index=False)
64
 
65
- return img_result, csv_path
66
 
67
- # === UI Gradio ===
68
  with gr.Blocks() as demo:
69
- gr.Markdown("## 🎯 YOLOv8 Segmentasi: Prediksi dan Laporan Otomatis")
70
- gr.Markdown("Upload gambar untuk mendeteksi objek dan mengunduh hasil deteksi sebagai CSV")
71
 
72
  with gr.Row():
73
  with gr.Column():
74
  image_input = gr.Image(type="pil", label="Upload Image")
75
- run_btn = gr.Button("Deteksi dan Simpan Report")
76
  with gr.Column():
77
- result_image = gr.Image(type="numpy", label="Hasil Prediksi")
78
- download_btn = gr.File(label="Unduh CSV Deteksi")
79
 
80
- run_btn.click(fn=process_image_and_generate_report,
81
- inputs=image_input,
82
- outputs=[result_image, download_btn])
83
 
84
  if __name__ == "__main__":
85
  demo.launch()
 
7
  from pathlib import Path
8
 
9
  # === Konfigurasi ===
10
+ model_path = "best.pt" # Ganti dengan path model kamu
11
  class_names = ['coral or rock', 'pipeline', 'ripple marks', 'shipwreck']
 
12
  model = YOLO(model_path)
13
 
14
+ # === Fungsi untuk menggambar prediksi lengkap ===
15
  def draw_predictions(img, segments, class_ids, confs, color=(255, 0, 0), alpha=0.5):
16
  overlay = img.copy()
17
  for i, seg in enumerate(segments):
 
20
  polygon[:, 1] *= img.shape[0]
21
  polygon = polygon.astype(np.int32)
22
 
23
+ cls_id = int(class_ids[i]) # pastikan integer
24
+ conf = confs[i]
25
+
26
+ # Draw mask
27
  cv2.fillPoly(overlay, [polygon], color)
28
+
29
+ # Draw bounding box
30
  x, y, w, h = cv2.boundingRect(polygon)
31
+ cv2.rectangle(overlay, (x, y), (x + w, y + h), color, 2)
32
+
33
+ # Draw label + confidence
34
+ label = f"{class_names[cls_id]} ({conf:.2f})"
35
+ cv2.putText(overlay, label, (x, y - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)
36
 
37
  return cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
38
 
39
+ # === Fungsi proses gambar dan hasil deteksi ===
40
+ def process_image_and_report(image):
41
  temp_path = "temp.jpg"
42
  image.save(temp_path)
43
  img = cv2.imread(temp_path)
44
  img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
45
 
46
+ # === Prediksi menggunakan YOLOv8
47
  results = model(temp_path)[0]
48
  segs = [seg.xy for seg in results.masks] if results.masks else []
49
  cls_ids = results.boxes.cls.tolist() if results.boxes else []
50
  confs = results.boxes.conf.tolist() if results.boxes else []
51
  xywh = results.boxes.xywhn.tolist() if results.boxes else []
52
 
53
+ # === Visualisasi prediksi
54
+ img_pred = draw_predictions(img.copy(), segs, cls_ids, confs)
55
 
56
+ # === Buat laporan CSV
57
  rows = []
58
  for i in range(len(cls_ids)):
59
  rows.append({
 
67
  })
68
 
69
  df = pd.DataFrame(rows)
70
+ csv_path = "detection_report.csv"
71
  df.to_csv(csv_path, index=False)
72
 
73
+ return img_pred, csv_path
74
 
75
+ # === Gradio UI ===
76
  with gr.Blocks() as demo:
77
+ gr.Markdown("## 🧠 YOLOv8 Segmentation Viewer + Detection Report")
78
+ gr.Markdown("Upload image lihat hasil deteksi (mask, box, label, confidence) → unduh CSV")
79
 
80
  with gr.Row():
81
  with gr.Column():
82
  image_input = gr.Image(type="pil", label="Upload Image")
83
+ submit_btn = gr.Button("Predict and Generate Report")
84
  with gr.Column():
85
+ image_output = gr.Image(type="numpy", label="Prediction Result")
86
+ download_csv = gr.File(label="Download Detection CSV")
87
 
88
+ submit_btn.click(fn=process_image_and_report, inputs=image_input, outputs=[image_output, download_csv])
 
 
89
 
90
  if __name__ == "__main__":
91
  demo.launch()