Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,13 @@
|
|
1 |
import cv2
|
|
|
|
|
2 |
from ultralytics import YOLO
|
3 |
from PIL import Image, ImageDraw, ImageFont
|
4 |
-
import gradio as gr
|
5 |
import pandas as pd
|
6 |
-
import
|
7 |
|
8 |
-
# بارگذاری مدل
|
9 |
-
model = YOLO('
|
10 |
|
11 |
# تعریف نام کلاسها به انگلیسی و فارسی
|
12 |
class_names = {
|
@@ -33,30 +34,8 @@ def detect_and_draw_image(input_image):
|
|
33 |
input_image_np = np.array(input_image)
|
34 |
|
35 |
# اجرای مدل روی تصویر با سطح اطمینان پایینتر برای اطمینان از شناسایی بیشتر اشیاء
|
36 |
-
results = model(input_image_np, conf=0.
|
37 |
-
|
38 |
-
# بررسی تعداد نتایج
|
39 |
-
if not results:
|
40 |
-
print("مدل هیچ نتیجهای برنگرداند.")
|
41 |
-
df = pd.DataFrame({
|
42 |
-
'Label (English)': [],
|
43 |
-
'Label (Persian)': [],
|
44 |
-
'Object Count': []
|
45 |
-
})
|
46 |
-
return input_image, df
|
47 |
-
|
48 |
-
# بررسی وجود جعبههای شناسایی شده
|
49 |
-
detections = results[0].boxes
|
50 |
-
if detections is None or len(detections) == 0:
|
51 |
-
print("هیچ شیء شناسایی نشده است.")
|
52 |
-
df = pd.DataFrame({
|
53 |
-
'Label (English)': [],
|
54 |
-
'Label (Persian)': [],
|
55 |
-
'Object Count': []
|
56 |
-
})
|
57 |
-
return input_image, df
|
58 |
-
|
59 |
-
print(f"تعداد اشیاء شناساییشده: {len(detections)}")
|
60 |
|
61 |
# تبدیل تصویر به PIL برای رسم
|
62 |
draw = ImageDraw.Draw(input_image)
|
@@ -67,20 +46,23 @@ def detect_and_draw_image(input_image):
|
|
67 |
font = ImageFont.load_default()
|
68 |
|
69 |
counts = {}
|
70 |
-
for
|
71 |
# دسترسی به مختصات جعبه و اطمینان
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
|
76 |
# دریافت برچسبهای انگلیسی و فارسی
|
77 |
label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
|
78 |
counts[label_en] = counts.get(label_en, 0) + 1
|
79 |
|
80 |
-
# رسم
|
81 |
-
|
|
|
|
|
|
|
82 |
# نوشتن برچسب و اطمینان
|
83 |
-
draw.text((
|
84 |
|
85 |
# ایجاد DataFrame برای نمایش نتایج
|
86 |
df = pd.DataFrame({
|
@@ -91,63 +73,6 @@ def detect_and_draw_image(input_image):
|
|
91 |
|
92 |
return input_image, df
|
93 |
|
94 |
-
# تابع برای تشخیص اشیاء در ویدئوها
|
95 |
-
def detect_and_draw_video(video_path):
|
96 |
-
cap = cv2.VideoCapture(video_path)
|
97 |
-
frames = []
|
98 |
-
overall_counts = {}
|
99 |
-
seen_objects = [] # لیست برای دنبال کردن اشیاء شناسایی شده
|
100 |
-
|
101 |
-
while cap.isOpened():
|
102 |
-
ret, frame = cap.read()
|
103 |
-
if not ret:
|
104 |
-
break
|
105 |
-
|
106 |
-
frame = cv2.resize(frame, (640, 480))
|
107 |
-
results = model(frame, conf=0.25)
|
108 |
-
|
109 |
-
detections = results[0].boxes
|
110 |
-
|
111 |
-
if detections is not None and len(detections) > 0:
|
112 |
-
for box in detections:
|
113 |
-
xmin, ymin, xmax, ymax = box.xyxy[0].tolist()
|
114 |
-
conf = box.conf[0].item()
|
115 |
-
class_id = int(box.cls[0].item())
|
116 |
-
label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
|
117 |
-
current_object = (label_en, int(xmin), int(ymin), int(xmax), int(ymax))
|
118 |
-
|
119 |
-
# بررسی وجود شیء در لیست seen_objects
|
120 |
-
if not any(existing[0] == label_en and
|
121 |
-
(existing[1] < xmax and existing[3] > xmin and
|
122 |
-
existing[2] < ymax and existing[4] > ymin) for existing in seen_objects):
|
123 |
-
seen_objects.append(current_object)
|
124 |
-
overall_counts[label_en] = overall_counts.get(label_en, 0) + 1
|
125 |
-
|
126 |
-
# رسم مستطیل و نام شیء بر روی فریم
|
127 |
-
cv2.rectangle(frame, (int(xmin), int(ymin)), (int(xmax), int(ymax)), (255, 0, 0), 2)
|
128 |
-
cv2.putText(frame, f"{label_en}: {conf:.2f}", (int(xmin), int(ymin) - 10),
|
129 |
-
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
|
130 |
-
|
131 |
-
frames.append(frame)
|
132 |
-
|
133 |
-
cap.release()
|
134 |
-
|
135 |
-
output_path = 'output.mp4'
|
136 |
-
out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (640, 480))
|
137 |
-
|
138 |
-
for frame in frames:
|
139 |
-
out.write(frame)
|
140 |
-
out.release()
|
141 |
-
|
142 |
-
# ایجاد DataFrame برای ذخیره نتایج
|
143 |
-
df = pd.DataFrame({
|
144 |
-
'Label (English)': list(overall_counts.keys()),
|
145 |
-
'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in overall_counts.keys()],
|
146 |
-
'Object Count': list(overall_counts.values())
|
147 |
-
})
|
148 |
-
|
149 |
-
return output_path, df
|
150 |
-
|
151 |
# رابط کاربری تصویر
|
152 |
image_interface = gr.Interface(
|
153 |
fn=detect_and_draw_image,
|
@@ -158,16 +83,5 @@ image_interface = gr.Interface(
|
|
158 |
examples=['Examples/images/areial_car.jpg', 'Examples/images/arieal_car_1.jpg','Examples/images/t.jpg']
|
159 |
)
|
160 |
|
161 |
-
# رابط کاربری
|
162 |
-
|
163 |
-
fn=detect_and_draw_video,
|
164 |
-
inputs=gr.Video(label="بارگذاری ویدئو"),
|
165 |
-
outputs=[gr.Video(label="ویدئوی پردازش شده"), gr.Dataframe(label="تعداد اشیاء")],
|
166 |
-
title="تشخیص اشیاء در ویدئوها",
|
167 |
-
description="یک ویدئو بارگذاری کنید تا اشیاء شناسایی شده و تعداد آنها را ببینید.",
|
168 |
-
examples=['Examples/video/city.mp4', 'Examples/video/airplane.mp4']
|
169 |
-
)
|
170 |
-
|
171 |
-
# اجرای برنامه با استفاده از رابط کاربری تبدار
|
172 |
-
app = gr.TabbedInterface([image_interface, video_interface], ["تشخیص تصویر", "تشخیص ویدئو"])
|
173 |
-
app.launch(debug=True, share=True)
|
|
|
1 |
import cv2
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
import numpy as np
|
4 |
from ultralytics import YOLO
|
5 |
from PIL import Image, ImageDraw, ImageFont
|
|
|
6 |
import pandas as pd
|
7 |
+
import gradio as gr
|
8 |
|
9 |
+
# بارگذاری مدل
|
10 |
+
model = YOLO('yolo11n-obb.pt') # مدل از پیش آموزش داده شده OBB را بارگذاری کنید
|
11 |
|
12 |
# تعریف نام کلاسها به انگلیسی و فارسی
|
13 |
class_names = {
|
|
|
34 |
input_image_np = np.array(input_image)
|
35 |
|
36 |
# اجرای مدل روی تصویر با سطح اطمینان پایینتر برای اطمینان از شناسایی بیشتر اشیاء
|
37 |
+
results = model.predict(source=input_image_np, conf=0.3)
|
38 |
+
obb_results = results[0].obb
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
# تبدیل تصویر به PIL برای رسم
|
41 |
draw = ImageDraw.Draw(input_image)
|
|
|
46 |
font = ImageFont.load_default()
|
47 |
|
48 |
counts = {}
|
49 |
+
for obb, conf, cls in zip(obb_results.data.cpu().numpy(), obb_results.conf.cpu().numpy(), obb_results.cls.cpu().numpy()):
|
50 |
# دسترسی به مختصات جعبه و اطمینان
|
51 |
+
x_center, y_center, width, height, rotation = obb[:5]
|
52 |
+
class_id = int(cls)
|
53 |
+
confidence = float(conf)
|
54 |
|
55 |
# دریافت برچسبهای انگلیسی و فارسی
|
56 |
label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
|
57 |
counts[label_en] = counts.get(label_en, 0) + 1
|
58 |
|
59 |
+
# رسم جعبه چرخان با استفاده از OpenCV
|
60 |
+
rect = ((x_center, y_center), (width, height), rotation * 180.0 / np.pi) # تبدیل رادیان به درجه
|
61 |
+
box = cv2.boxPoints(rect)
|
62 |
+
box = np.int0(box)
|
63 |
+
draw.polygon([tuple(point) for point in box], outline="red")
|
64 |
# نوشتن برچسب و اطمینان
|
65 |
+
draw.text((x_center, y_center - 10), f"{label_en}: {confidence:.2f}", fill="red", font=font)
|
66 |
|
67 |
# ایجاد DataFrame برای نمایش نتایج
|
68 |
df = pd.DataFrame({
|
|
|
73 |
|
74 |
return input_image, df
|
75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
# رابط کاربری تصویر
|
77 |
image_interface = gr.Interface(
|
78 |
fn=detect_and_draw_image,
|
|
|
83 |
examples=['Examples/images/areial_car.jpg', 'Examples/images/arieal_car_1.jpg','Examples/images/t.jpg']
|
84 |
)
|
85 |
|
86 |
+
# اجرای برنامه با استفاده از رابط کاربری
|
87 |
+
image_interface.launch(debug=True, share=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|