Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -77,78 +77,87 @@ class CentroidTracker:
|
|
| 77 |
|
| 78 |
return self.objects
|
| 79 |
|
| 80 |
-
# --- 2.
|
| 81 |
-
def analyze_multiple_nematodes(video_path, scale, fps, body_len, min_area, max_area):
|
| 82 |
ct = CentroidTracker()
|
| 83 |
cap = cv2.VideoCapture(video_path)
|
| 84 |
|
| 85 |
if not cap.isOpened():
|
| 86 |
-
return "שגיאה: לא ניתן לפתוח את הקובץ.", None, None, None
|
| 87 |
|
| 88 |
tracks = {}
|
| 89 |
frame_idx = 0
|
| 90 |
last_vis_frame = None
|
|
|
|
| 91 |
|
|
|
|
|
|
|
|
|
|
| 92 |
while True:
|
| 93 |
ret, frame = cap.read()
|
| 94 |
if not ret: break
|
| 95 |
|
| 96 |
vis_frame = frame.copy()
|
| 97 |
-
|
| 98 |
-
# שלב 1: שיפור תמונה וזיהוי קצוות (Canny) במקום בהירות
|
| 99 |
-
# Canny מעולה במציאת קווי מתאר של הנמטודה גם כשהיא שקופה
|
| 100 |
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 101 |
|
| 102 |
-
#
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
#
|
| 106 |
-
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
# שלב
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
closed = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel, iterations=2)
|
| 112 |
-
dilated = cv2.dilate(closed, kernel, iterations=1)
|
| 113 |
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
rects = []
|
| 116 |
|
| 117 |
for c in contours:
|
| 118 |
area = cv2.contourArea(c)
|
| 119 |
-
|
| 120 |
-
# סינון גודל בסיסי
|
| 121 |
if area < min_area or area > max_area:
|
| 122 |
continue
|
| 123 |
|
| 124 |
-
# ---
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
# מעגל מושלם (בועה) = 1.0
|
| 130 |
-
# קו ישר או מפותל (נמטודה) = שואף ל-0
|
| 131 |
-
circularity = 4 * np.pi * (area / (perimeter * perimeter))
|
| 132 |
|
| 133 |
-
#
|
| 134 |
-
|
| 135 |
-
if
|
| 136 |
-
continue
|
| 137 |
-
|
| 138 |
-
# חישוב Aspect Ratio (יחס אורך/��וחב של הריבוע החוסם)
|
| 139 |
-
(x, y, w, h) = cv2.boundingRect(c)
|
| 140 |
-
aspect_ratio = float(w) / h if h > 0 else 0
|
| 141 |
-
|
| 142 |
-
# בועות הן ריבועיות (יחס קרוב ל-1). נמטודות הן מלבניות.
|
| 143 |
-
# נשמור רק אם היחס רחוק מ-1 (כלומר הצורה ארוכה או רחבה מאוד)
|
| 144 |
-
if 0.6 < aspect_ratio < 1.4:
|
| 145 |
-
# זה ריבוע/עיגול -> כנראה בועה -> דלג
|
| 146 |
-
continue
|
| 147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
rects.append((x, y, x + w, y + h))
|
| 149 |
|
| 150 |
-
# ציור
|
| 151 |
-
cv2.
|
|
|
|
| 152 |
|
| 153 |
objects = ct.update(rects)
|
| 154 |
current_time = frame_idx / fps
|
|
@@ -156,7 +165,7 @@ def analyze_multiple_nematodes(video_path, scale, fps, body_len, min_area, max_a
|
|
| 156 |
for (objectID, centroid) in objects.items():
|
| 157 |
text = f"ID {objectID}"
|
| 158 |
cv2.putText(vis_frame, text, (centroid[0] - 10, centroid[1] - 10),
|
| 159 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (
|
| 160 |
|
| 161 |
x_um = centroid[0] * scale
|
| 162 |
y_um = centroid[1] * scale
|
|
@@ -180,11 +189,15 @@ def analyze_multiple_nematodes(video_path, scale, fps, body_len, min_area, max_a
|
|
| 180 |
|
| 181 |
if last_vis_frame is not None:
|
| 182 |
last_vis_frame = cv2.cvtColor(last_vis_frame, cv2.COLOR_BGR2RGB)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
if not tracks:
|
| 185 |
-
return f"לא
|
| 186 |
|
| 187 |
-
# ---
|
| 188 |
summary_rows = []
|
| 189 |
raw_data_rows = []
|
| 190 |
|
|
@@ -264,20 +277,20 @@ def analyze_multiple_nematodes(video_path, scale, fps, body_len, min_area, max_a
|
|
| 264 |
final_avg_speed = means["Avg_Speed (um/s)"] if not df_summary.empty else 0
|
| 265 |
final_eff = means["Efficiency (V/fL)"] if not df_summary.empty else 0
|
| 266 |
|
| 267 |
-
res_text = f"זוהו {valid_worms} נמטודות (
|
| 268 |
res_text += f"מהירות ממוצעת: {final_avg_speed:.2f} um/s\n"
|
| 269 |
res_text += f"יעילות ממוצעת: {final_eff:.3f}"
|
| 270 |
|
| 271 |
-
return res_text, fig, zip_filename, last_vis_frame
|
| 272 |
|
| 273 |
# --- 3. Gradio Interface ---
|
| 274 |
-
def wrapper_analyze(file_obj, scale, fps, body, min_a, max_a):
|
| 275 |
-
if file_obj is None: return "אנא העלה קובץ", None, None, None
|
| 276 |
-
return analyze_multiple_nematodes(file_obj.name, scale, fps, body, min_a, max_a)
|
| 277 |
|
| 278 |
with gr.Blocks(title="NemaAnalyzer Pro") as demo:
|
| 279 |
-
gr.Markdown("# 🔬 NemaAnalyzer Pro -
|
| 280 |
-
gr.Markdown("מודל זה מת
|
| 281 |
|
| 282 |
with gr.Row():
|
| 283 |
file_in = gr.File(label="העלה קובץ וידאו (AVI)")
|
|
@@ -286,23 +299,28 @@ with gr.Blocks(title="NemaAnalyzer Pro") as demo:
|
|
| 286 |
fps_in = gr.Number(value=30, label="FPS")
|
| 287 |
body_in = gr.Number(value=1000, label="Body Length (um)")
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
| 292 |
|
| 293 |
-
btn = gr.Button("▶ בצע אנליזה
|
| 294 |
|
| 295 |
with gr.Row():
|
| 296 |
txt_out = gr.Textbox(label="סיכום")
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
with gr.Row():
|
| 300 |
plot_out = gr.Plot(label="גרפים")
|
| 301 |
file_out = gr.File(label="הורד דוחות (ZIP)")
|
| 302 |
|
| 303 |
btn.click(wrapper_analyze,
|
| 304 |
-
[file_in, scale_in, fps_in, body_in, min_a, max_a],
|
| 305 |
-
[txt_out, plot_out, file_out, img_out])
|
| 306 |
|
| 307 |
if __name__ == "__main__":
|
| 308 |
demo.launch()
|
|
|
|
| 77 |
|
| 78 |
return self.objects
|
| 79 |
|
| 80 |
+
# --- 2. Logic: Bubble Removal & Nematode Enhancement ---
|
| 81 |
+
def analyze_multiple_nematodes(video_path, scale, fps, body_len, min_area, max_area, bubble_thresh):
|
| 82 |
ct = CentroidTracker()
|
| 83 |
cap = cv2.VideoCapture(video_path)
|
| 84 |
|
| 85 |
if not cap.isOpened():
|
| 86 |
+
return "שגיאה: לא ניתן לפתוח את הקובץ.", None, None, None, None
|
| 87 |
|
| 88 |
tracks = {}
|
| 89 |
frame_idx = 0
|
| 90 |
last_vis_frame = None
|
| 91 |
+
debug_mask = None
|
| 92 |
|
| 93 |
+
# CLAHE לשיפור ניגודיות מקומי (עוזר להבליט את הנמטודה האפורה)
|
| 94 |
+
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
|
| 95 |
+
|
| 96 |
while True:
|
| 97 |
ret, frame = cap.read()
|
| 98 |
if not ret: break
|
| 99 |
|
| 100 |
vis_frame = frame.copy()
|
|
|
|
|
|
|
|
|
|
| 101 |
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
| 102 |
|
| 103 |
+
# --- שלב 1: מחיקת בועות (Bubble Removal) ---
|
| 104 |
+
# בועות הן שחורות מאוד (ערכים נמוכים, למשל מתחת ל-60)
|
| 105 |
+
# אנחנו יוצרים מסכה של הבועות וצובעים אותן בלבן (כמו הרקע) כדי להעלים אותן
|
| 106 |
+
_, bubble_mask = cv2.threshold(gray, bubble_thresh, 255, cv2.THRESH_BINARY_INV)
|
| 107 |
+
|
| 108 |
+
# הרחבת המסכה קצת כדי לכסות את שולי הבועות
|
| 109 |
+
kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
|
| 110 |
+
bubble_mask = cv2.dilate(bubble_mask, kernel_dilate, iterations=2)
|
| 111 |
+
|
| 112 |
+
# "מחיקת" הבועות מהתמונה המקורית (הופך אותן ללבן)
|
| 113 |
+
clean_gray = gray.copy()
|
| 114 |
+
clean_gray[bubble_mask > 0] = 255
|
| 115 |
|
| 116 |
+
# --- שלב 2: הבלטת הנמטודה ---
|
| 117 |
+
# עכשיו כשהבועות נעלמו, נשארנו עם נמטודה אפורה על רקע לבן.
|
| 118 |
+
# נשתמש ב-CLAHE כדי להפוך את האפור לשחור חזק
|
| 119 |
+
enhanced = clahe.apply(clean_gray)
|
| 120 |
|
| 121 |
+
# --- שלב 3: סף (Threshold) חדש לנמטודה ---
|
| 122 |
+
# כעת הנמטודה היא הדבר הכהה ביותר שנשאר בתמונה
|
| 123 |
+
_, thresh = cv2.threshold(enhanced, 180, 255, cv2.THRESH_BINARY_INV)
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
# ניקוי רעשים דק
|
| 126 |
+
kernel_clean = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
|
| 127 |
+
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel_clean, iterations=1)
|
| 128 |
+
|
| 129 |
+
debug_mask = thresh.copy() # לתצוגה למשתמש
|
| 130 |
+
|
| 131 |
+
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 132 |
rects = []
|
| 133 |
|
| 134 |
for c in contours:
|
| 135 |
area = cv2.contourArea(c)
|
|
|
|
|
|
|
| 136 |
if area < min_area or area > max_area:
|
| 137 |
continue
|
| 138 |
|
| 139 |
+
# --- סינון גיאומטרי לנמטודה ---
|
| 140 |
+
rect = cv2.minAreaRect(c)
|
| 141 |
+
(center), (width, height), angle = rect
|
| 142 |
+
short = min(width, height)
|
| 143 |
+
long_side = max(width, height)
|
| 144 |
|
| 145 |
+
if short == 0: continue
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
# יחס אורך/רוחב: נמטודה חייבת להיות ארוכה (לפחות פי 2.5 מהרוחב)
|
| 148 |
+
aspect_ratio = long_side / short
|
| 149 |
+
if aspect_ratio < 2.5:
|
| 150 |
+
continue # זה כנראה שארית של בועה עגולה
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
# אם עברנו את הסינון -> זו נמטודה
|
| 153 |
+
box = cv2.boxPoints(rect)
|
| 154 |
+
box = np.int0(box)
|
| 155 |
+
x, y, w, h = cv2.boundingRect(c)
|
| 156 |
rects.append((x, y, x + w, y + h))
|
| 157 |
|
| 158 |
+
# ציור קו אדום סביב הנמטודה
|
| 159 |
+
cv2.drawContours(vis_frame, [box], 0, (0, 0, 255), 2)
|
| 160 |
+
cv2.putText(vis_frame, "NEMATODE", (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
|
| 161 |
|
| 162 |
objects = ct.update(rects)
|
| 163 |
current_time = frame_idx / fps
|
|
|
|
| 165 |
for (objectID, centroid) in objects.items():
|
| 166 |
text = f"ID {objectID}"
|
| 167 |
cv2.putText(vis_frame, text, (centroid[0] - 10, centroid[1] - 10),
|
| 168 |
+
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
|
| 169 |
|
| 170 |
x_um = centroid[0] * scale
|
| 171 |
y_um = centroid[1] * scale
|
|
|
|
| 189 |
|
| 190 |
if last_vis_frame is not None:
|
| 191 |
last_vis_frame = cv2.cvtColor(last_vis_frame, cv2.COLOR_BGR2RGB)
|
| 192 |
+
|
| 193 |
+
mask_view = None
|
| 194 |
+
if debug_mask is not None:
|
| 195 |
+
mask_view = cv2.cvtColor(debug_mask, cv2.COLOR_GRAY2RGB)
|
| 196 |
|
| 197 |
if not tracks:
|
| 198 |
+
return f"לא נמצאו נמטודות. נסה לשנות את 'Bubble Threshold' (סף זיהוי הבועות).", None, None, last_vis_frame, mask_view
|
| 199 |
|
| 200 |
+
# --- Reports ---
|
| 201 |
summary_rows = []
|
| 202 |
raw_data_rows = []
|
| 203 |
|
|
|
|
| 277 |
final_avg_speed = means["Avg_Speed (um/s)"] if not df_summary.empty else 0
|
| 278 |
final_eff = means["Efficiency (V/fL)"] if not df_summary.empty else 0
|
| 279 |
|
| 280 |
+
res_text = f"זוהו {valid_worms} נמטודות (בועות הוסרו).\n"
|
| 281 |
res_text += f"מהירות ממוצעת: {final_avg_speed:.2f} um/s\n"
|
| 282 |
res_text += f"יעילות ממוצעת: {final_eff:.3f}"
|
| 283 |
|
| 284 |
+
return res_text, fig, zip_filename, last_vis_frame, mask_view
|
| 285 |
|
| 286 |
# --- 3. Gradio Interface ---
|
| 287 |
+
def wrapper_analyze(file_obj, scale, fps, body, min_a, max_a, bubble_thresh):
|
| 288 |
+
if file_obj is None: return "אנא העלה קובץ", None, None, None, None
|
| 289 |
+
return analyze_multiple_nematodes(file_obj.name, scale, fps, body, min_a, max_a, bubble_thresh)
|
| 290 |
|
| 291 |
with gr.Blocks(title="NemaAnalyzer Pro") as demo:
|
| 292 |
+
gr.Markdown("# 🔬 NemaAnalyzer Pro - Bubble Remover")
|
| 293 |
+
gr.Markdown("מודל זה מוחק כתמים שחורים (בועות) ומחפש נמטודות אפורות שנשארו.")
|
| 294 |
|
| 295 |
with gr.Row():
|
| 296 |
file_in = gr.File(label="העלה קובץ וידאו (AVI)")
|
|
|
|
| 299 |
fps_in = gr.Number(value=30, label="FPS")
|
| 300 |
body_in = gr.Number(value=1000, label="Body Length (um)")
|
| 301 |
|
| 302 |
+
with gr.Accordion("הגדרות מתקדמות", open=True):
|
| 303 |
+
min_a = gr.Number(value=500, label="Min Area (px)")
|
| 304 |
+
max_a = gr.Number(value=20000, label="Max Area (px)")
|
| 305 |
+
# סף זיהוי בועות: כל מה שכהה מזה (למשל 60) ייחשב בועה ויימחק
|
| 306 |
+
bubble_thresh = gr.Slider(minimum=10, maximum=150, value=65, label="Bubble Threshold (Darkness Level)")
|
| 307 |
|
| 308 |
+
btn = gr.Button("▶ בצע אנליזה (מחיקת בועות)", variant="primary")
|
| 309 |
|
| 310 |
with gr.Row():
|
| 311 |
txt_out = gr.Textbox(label="סיכום")
|
| 312 |
+
|
| 313 |
+
with gr.Row():
|
| 314 |
+
img_out = gr.Image(label="זיהוי סופי (אדום = נמטודה)")
|
| 315 |
+
mask_out = gr.Image(label="מה המחשב רואה (אחרי מחיקת בועות)")
|
| 316 |
|
| 317 |
with gr.Row():
|
| 318 |
plot_out = gr.Plot(label="גרפים")
|
| 319 |
file_out = gr.File(label="הורד דוחות (ZIP)")
|
| 320 |
|
| 321 |
btn.click(wrapper_analyze,
|
| 322 |
+
[file_in, scale_in, fps_in, body_in, min_a, max_a, bubble_thresh],
|
| 323 |
+
[txt_out, plot_out, file_out, img_out, mask_out])
|
| 324 |
|
| 325 |
if __name__ == "__main__":
|
| 326 |
demo.launch()
|