MohammadRezaHalakoo
commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,7 +11,7 @@ import tempfile
|
|
| 11 |
import os
|
| 12 |
|
| 13 |
# بارگذاری مدل آموزشدیده شما
|
| 14 |
-
# اطمینان حاصل کنید که مسیر مدل صحیح است
|
| 15 |
model = YOLO('weights/best.pt') # یا '/content/best.pt' بر اساس مدل مورد نظر شما
|
| 16 |
|
| 17 |
# تعریف نام کلاسها به انگلیسی و فارسی
|
|
@@ -57,12 +57,19 @@ def detect_and_draw_image(input_image):
|
|
| 57 |
try:
|
| 58 |
# تبدیل تصویر PIL به آرایه NumPy (RGB)
|
| 59 |
input_image_np = np.array(input_image)
|
|
|
|
| 60 |
|
| 61 |
# اجرای مدل روی تصویر
|
| 62 |
results = model.predict(source=input_image_np, conf=0.3)
|
|
|
|
| 63 |
|
| 64 |
# دسترسی به نتایج OBB
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
# بررسی وجود جعبههای شناسایی شده
|
| 68 |
if obb_results is None or len(obb_results.data) == 0:
|
|
@@ -76,6 +83,7 @@ def detect_and_draw_image(input_image):
|
|
| 76 |
|
| 77 |
# بارگذاری تصویر اصلی به صورت OpenCV برای رسم جعبهها (BGR)
|
| 78 |
image_cv = cv2.cvtColor(input_image_np, cv2.COLOR_RGB2BGR)
|
|
|
|
| 79 |
|
| 80 |
counts = {}
|
| 81 |
for obb, conf, cls in zip(obb_results.data.cpu().numpy(), obb_results.conf.cpu().numpy(), obb_results.cls.cpu().numpy()):
|
|
@@ -89,6 +97,7 @@ def detect_and_draw_image(input_image):
|
|
| 89 |
box = np.int0(box)
|
| 90 |
color = colors.get(class_id, (0, 255, 0)) # استفاده از رنگ مشخص برای هر کلاس
|
| 91 |
cv2.drawContours(image_cv, [box], 0, color, 2)
|
|
|
|
| 92 |
|
| 93 |
# رسم برچسب
|
| 94 |
label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
|
|
@@ -102,6 +111,7 @@ def detect_and_draw_image(input_image):
|
|
| 102 |
# تبدیل تصویر به RGB برای Gradio
|
| 103 |
image_rgb = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)
|
| 104 |
output_image = Image.fromarray(image_rgb)
|
|
|
|
| 105 |
|
| 106 |
# ایجاد DataFrame برای نمایش نتایج
|
| 107 |
df = pd.DataFrame({
|
|
@@ -109,6 +119,7 @@ def detect_and_draw_image(input_image):
|
|
| 109 |
'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in counts.keys()],
|
| 110 |
'Object Count': list(counts.values())
|
| 111 |
})
|
|
|
|
| 112 |
|
| 113 |
return output_image, df
|
| 114 |
|
|
@@ -128,12 +139,16 @@ def detect_and_draw_video(video_path):
|
|
| 128 |
frames = []
|
| 129 |
overall_counts = {}
|
| 130 |
seen_objects = [] # لیست برای دنبال کردن اشیاء شناسایی شده
|
|
|
|
| 131 |
|
| 132 |
while cap.isOpened():
|
| 133 |
ret, frame = cap.read()
|
| 134 |
if not ret:
|
| 135 |
break
|
| 136 |
|
|
|
|
|
|
|
|
|
|
| 137 |
# تغییر اندازه فریم
|
| 138 |
frame = cv2.resize(frame, (640, 480))
|
| 139 |
|
|
@@ -142,9 +157,15 @@ def detect_and_draw_video(video_path):
|
|
| 142 |
|
| 143 |
# اجرای مدل روی فریم
|
| 144 |
results = model.predict(source=frame_rgb, conf=0.3)
|
|
|
|
| 145 |
|
| 146 |
# دسترسی به نتایج OBB
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
if obb_results is not None and len(obb_results.data) > 0:
|
| 150 |
for obb, conf, cls in zip(obb_results.data.cpu().numpy(), obb_results.conf.cpu().numpy(), obb_results.cls.cpu().numpy()):
|
|
@@ -158,6 +179,7 @@ def detect_and_draw_video(video_path):
|
|
| 158 |
box = np.int0(box)
|
| 159 |
color = colors.get(class_id, (0, 255, 0)) # استفاده از رنگ مشخص برای هر کلاس
|
| 160 |
cv2.drawContours(frame, [box], 0, color, 2)
|
|
|
|
| 161 |
|
| 162 |
# رسم برچسب
|
| 163 |
label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
|
|
@@ -169,18 +191,25 @@ def detect_and_draw_video(video_path):
|
|
| 169 |
overall_counts[label_en] = overall_counts.get(label_en, 0) + 1
|
| 170 |
|
| 171 |
frames.append(frame)
|
|
|
|
| 172 |
|
| 173 |
cap.release()
|
|
|
|
| 174 |
|
| 175 |
# ذخیره ویدئو پردازششده در یک فایل موقت
|
| 176 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmpfile:
|
| 177 |
output_path = tmpfile.name
|
| 178 |
|
| 179 |
out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (640, 480))
|
|
|
|
| 180 |
|
| 181 |
-
for frame in frames:
|
| 182 |
out.write(frame)
|
|
|
|
|
|
|
|
|
|
| 183 |
out.release()
|
|
|
|
| 184 |
|
| 185 |
# ایجاد DataFrame برای ذخیره نتایج
|
| 186 |
df = pd.DataFrame({
|
|
@@ -188,6 +217,7 @@ def detect_and_draw_video(video_path):
|
|
| 188 |
'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in overall_counts.keys()],
|
| 189 |
'Object Count': list(overall_counts.values())
|
| 190 |
})
|
|
|
|
| 191 |
|
| 192 |
return output_path, df
|
| 193 |
|
|
|
|
| 11 |
import os
|
| 12 |
|
| 13 |
# بارگذاری مدل آموزشدیده شما
|
| 14 |
+
# اطمینان حاصل کنید که مسیر مدل صحیح است و فقط یک بار مدل را بارگذاری میکنید
|
| 15 |
model = YOLO('weights/best.pt') # یا '/content/best.pt' بر اساس مدل مورد نظر شما
|
| 16 |
|
| 17 |
# تعریف نام کلاسها به انگلیسی و فارسی
|
|
|
|
| 57 |
try:
|
| 58 |
# تبدیل تصویر PIL به آرایه NumPy (RGB)
|
| 59 |
input_image_np = np.array(input_image)
|
| 60 |
+
print("Image converted to NumPy array.")
|
| 61 |
|
| 62 |
# اجرای مدل روی تصویر
|
| 63 |
results = model.predict(source=input_image_np, conf=0.3)
|
| 64 |
+
print("Model prediction completed.")
|
| 65 |
|
| 66 |
# دسترسی به نتایج OBB
|
| 67 |
+
if hasattr(results[0], 'obb') and results[0].obb is not None:
|
| 68 |
+
obb_results = results[0].obb
|
| 69 |
+
print("Accessed obb_results.")
|
| 70 |
+
else:
|
| 71 |
+
print("No 'obb' attribute found in results[0].")
|
| 72 |
+
obb_results = None
|
| 73 |
|
| 74 |
# بررسی وجود جعبههای شناسایی شده
|
| 75 |
if obb_results is None or len(obb_results.data) == 0:
|
|
|
|
| 83 |
|
| 84 |
# بارگذاری تصویر اصلی به صورت OpenCV برای رسم جعبهها (BGR)
|
| 85 |
image_cv = cv2.cvtColor(input_image_np, cv2.COLOR_RGB2BGR)
|
| 86 |
+
print("Image converted to BGR for OpenCV.")
|
| 87 |
|
| 88 |
counts = {}
|
| 89 |
for obb, conf, cls in zip(obb_results.data.cpu().numpy(), obb_results.conf.cpu().numpy(), obb_results.cls.cpu().numpy()):
|
|
|
|
| 97 |
box = np.int0(box)
|
| 98 |
color = colors.get(class_id, (0, 255, 0)) # استفاده از رنگ مشخص برای هر کلاس
|
| 99 |
cv2.drawContours(image_cv, [box], 0, color, 2)
|
| 100 |
+
print(f"Drawn OBB for class_id {class_id} with confidence {confidence}.")
|
| 101 |
|
| 102 |
# رسم برچسب
|
| 103 |
label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
|
|
|
|
| 111 |
# تبدیل تصویر به RGB برای Gradio
|
| 112 |
image_rgb = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)
|
| 113 |
output_image = Image.fromarray(image_rgb)
|
| 114 |
+
print("Image converted back to RGB for Gradio.")
|
| 115 |
|
| 116 |
# ایجاد DataFrame برای نمایش نتایج
|
| 117 |
df = pd.DataFrame({
|
|
|
|
| 119 |
'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in counts.keys()],
|
| 120 |
'Object Count': list(counts.values())
|
| 121 |
})
|
| 122 |
+
print("DataFrame created.")
|
| 123 |
|
| 124 |
return output_image, df
|
| 125 |
|
|
|
|
| 139 |
frames = []
|
| 140 |
overall_counts = {}
|
| 141 |
seen_objects = [] # لیست برای دنبال کردن اشیاء شناسایی شده
|
| 142 |
+
frame_count = 0
|
| 143 |
|
| 144 |
while cap.isOpened():
|
| 145 |
ret, frame = cap.read()
|
| 146 |
if not ret:
|
| 147 |
break
|
| 148 |
|
| 149 |
+
frame_count +=1
|
| 150 |
+
print(f"Processing frame {frame_count}")
|
| 151 |
+
|
| 152 |
# تغییر اندازه فریم
|
| 153 |
frame = cv2.resize(frame, (640, 480))
|
| 154 |
|
|
|
|
| 157 |
|
| 158 |
# اجرای مدل روی فریم
|
| 159 |
results = model.predict(source=frame_rgb, conf=0.3)
|
| 160 |
+
print(f"Model prediction completed for frame {frame_count}.")
|
| 161 |
|
| 162 |
# دسترسی به نتایج OBB
|
| 163 |
+
if hasattr(results[0], 'obb') and results[0].obb is not None:
|
| 164 |
+
obb_results = results[0].obb
|
| 165 |
+
print("Accessed obb_results for frame.")
|
| 166 |
+
else:
|
| 167 |
+
print("No 'obb' attribute found in results[0] for frame.")
|
| 168 |
+
obb_results = None
|
| 169 |
|
| 170 |
if obb_results is not None and len(obb_results.data) > 0:
|
| 171 |
for obb, conf, cls in zip(obb_results.data.cpu().numpy(), obb_results.conf.cpu().numpy(), obb_results.cls.cpu().numpy()):
|
|
|
|
| 179 |
box = np.int0(box)
|
| 180 |
color = colors.get(class_id, (0, 255, 0)) # استفاده از رنگ مشخص برای هر کلاس
|
| 181 |
cv2.drawContours(frame, [box], 0, color, 2)
|
| 182 |
+
print(f"Drawn OBB for class_id {class_id} with confidence {confidence} in frame {frame_count}.")
|
| 183 |
|
| 184 |
# رسم برچسب
|
| 185 |
label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
|
|
|
|
| 191 |
overall_counts[label_en] = overall_counts.get(label_en, 0) + 1
|
| 192 |
|
| 193 |
frames.append(frame)
|
| 194 |
+
print(f"Frame {frame_count} processed.")
|
| 195 |
|
| 196 |
cap.release()
|
| 197 |
+
print("Video processing completed.")
|
| 198 |
|
| 199 |
# ذخیره ویدئو پردازششده در یک فایل موقت
|
| 200 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmpfile:
|
| 201 |
output_path = tmpfile.name
|
| 202 |
|
| 203 |
out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (640, 480))
|
| 204 |
+
print(f"Saving processed video to {output_path}")
|
| 205 |
|
| 206 |
+
for idx, frame in enumerate(frames):
|
| 207 |
out.write(frame)
|
| 208 |
+
if idx % 100 == 0:
|
| 209 |
+
print(f"Writing frame {idx} to video.")
|
| 210 |
+
|
| 211 |
out.release()
|
| 212 |
+
print("Video saved.")
|
| 213 |
|
| 214 |
# ایجاد DataFrame برای ذخیره نتایج
|
| 215 |
df = pd.DataFrame({
|
|
|
|
| 217 |
'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in overall_counts.keys()],
|
| 218 |
'Object Count': list(overall_counts.values())
|
| 219 |
})
|
| 220 |
+
print("DataFrame created.")
|
| 221 |
|
| 222 |
return output_path, df
|
| 223 |
|