Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,18 +5,15 @@ import gradio as gr
|
|
5 |
import pandas as pd
|
6 |
from ultralytics import YOLO
|
7 |
from pathlib import Path
|
8 |
-
from datetime import datetime
|
9 |
|
10 |
# === Konfigurasi ===
|
11 |
-
model_path = "best.pt"
|
12 |
-
gt_label_dir = "data/labels" # sesuaikan dengan struktur foldermu
|
13 |
class_names = ['coral or rock', 'pipeline', 'ripple marks', 'shipwreck']
|
14 |
|
15 |
-
# Load model
|
16 |
model = YOLO(model_path)
|
17 |
|
18 |
-
# === Fungsi untuk menggambar
|
19 |
-
def
|
20 |
overlay = img.copy()
|
21 |
for i, seg in enumerate(segments):
|
22 |
polygon = np.array(seg).reshape(-1, 2)
|
@@ -24,57 +21,31 @@ def draw_mask(img, segments, class_ids, color=(255, 0, 0), alpha=0.5, label_type
|
|
24 |
polygon[:, 1] *= img.shape[0]
|
25 |
polygon = polygon.astype(np.int32)
|
26 |
|
27 |
-
|
28 |
-
label = f"{label_type}: {class_names[cls_id]}"
|
29 |
-
if confs and i < len(confs):
|
30 |
-
label += f" ({confs[i]:.2f})"
|
31 |
-
|
32 |
cv2.fillPoly(overlay, [polygon], color)
|
33 |
x, y, w, h = cv2.boundingRect(polygon)
|
34 |
cv2.putText(overlay, label, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 1)
|
|
|
35 |
|
36 |
return cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
|
37 |
|
38 |
-
# ===
|
39 |
-
def
|
40 |
-
|
41 |
-
temp_path = f"/tmp/temp_{timestamp}.jpg"
|
42 |
-
csv_path = f"/tmp/detection_report_{timestamp}.csv"
|
43 |
-
|
44 |
image.save(temp_path)
|
45 |
img = cv2.imread(temp_path)
|
46 |
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
47 |
|
48 |
-
#
|
49 |
-
label_path = os.path.join(gt_label_dir, Path(temp_path).with_suffix(".txt").name)
|
50 |
-
img_gt = img.copy()
|
51 |
-
if os.path.exists(label_path):
|
52 |
-
with open(label_path, "r") as f:
|
53 |
-
gt_segments = []
|
54 |
-
gt_ids = []
|
55 |
-
for line in f:
|
56 |
-
parts = line.strip().split()
|
57 |
-
if len(parts) < 3:
|
58 |
-
continue
|
59 |
-
cls_id = int(parts[0])
|
60 |
-
coords = list(map(float, parts[1:]))
|
61 |
-
gt_segments.append(np.array(coords).reshape(-1, 2))
|
62 |
-
gt_ids.append(cls_id)
|
63 |
-
img_gt = draw_mask(img_gt, gt_segments, gt_ids, color=(0, 255, 0), label_type="GT")
|
64 |
-
|
65 |
-
# === Deteksi dengan YOLOv8 ===
|
66 |
results = model(temp_path)[0]
|
67 |
segs = [seg.xy for seg in results.masks] if results.masks else []
|
68 |
cls_ids = results.boxes.cls.tolist() if results.boxes else []
|
69 |
confs = results.boxes.conf.tolist() if results.boxes else []
|
70 |
xywh = results.boxes.xywhn.tolist() if results.boxes else []
|
71 |
|
72 |
-
|
73 |
-
|
74 |
-
# === Gabung GT dan Prediksi
|
75 |
-
combined = np.concatenate((img_gt, img_pred), axis=1)
|
76 |
|
77 |
-
#
|
78 |
rows = []
|
79 |
for i in range(len(cls_ids)):
|
80 |
rows.append({
|
@@ -88,24 +59,27 @@ def process_image_and_report(image):
|
|
88 |
})
|
89 |
|
90 |
df = pd.DataFrame(rows)
|
|
|
91 |
df.to_csv(csv_path, index=False)
|
92 |
|
93 |
-
return
|
94 |
|
95 |
# === UI Gradio ===
|
96 |
with gr.Blocks() as demo:
|
97 |
-
gr.Markdown("##
|
98 |
-
gr.Markdown("Upload gambar
|
99 |
|
100 |
with gr.Row():
|
101 |
with gr.Column():
|
102 |
image_input = gr.Image(type="pil", label="Upload Image")
|
103 |
-
|
104 |
with gr.Column():
|
105 |
-
|
106 |
-
|
107 |
|
108 |
-
|
|
|
|
|
109 |
|
110 |
if __name__ == "__main__":
|
111 |
demo.launch()
|
|
|
5 |
import pandas as pd
|
6 |
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):
|
19 |
polygon = np.array(seg).reshape(-1, 2)
|
|
|
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 |
})
|
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()
|