Ashegh-Sad-Warrior commited on
Commit
d507b48
·
verified ·
1 Parent(s): c27b4a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -91
app.py CHANGED
@@ -1,8 +1,9 @@
1
  import cv2
2
  from ultralytics import YOLO
3
- from PIL import Image, ImageDraw
4
  import gradio as gr
5
  import pandas as pd
 
6
 
7
  # بارگذاری مدل آموزش‌دیده شما
8
  model = YOLO('weights/best.pt')
@@ -28,93 +29,32 @@ class_names = {
28
 
29
  # تابع برای تشخیص اشیاء در تصاویر
30
  def detect_and_draw_image(input_image):
31
- # اجرای مدل با تنظیمات اطمینان و iou برای بهبود تشخیص
32
- results = model.predict(input_image, conf=0.5, iou=0.6)
33
-
34
- # بررسی وجود اشیاء شناسایی شده
35
- if not results or results[0].boxes is None or not results[0].boxes.boxes:
36
- # اگر هیچ شیء شناسایی نشده باشد
37
- df = pd.DataFrame({
38
- 'Label (English)': [],
39
- 'Label (Persian)': [],
40
- 'Object Count': []
41
- })
42
- return input_image, df
43
-
44
- detections = results[0].boxes.boxes # دسترسی به نتایج در YOLOv8
45
 
46
- draw = ImageDraw.Draw(input_image)
 
 
 
 
 
 
 
 
 
47
  counts = {}
48
- for detection in detections:
49
- xmin, ymin, xmax, ymax, conf, class_id = detection.cpu().numpy()
50
- label_en, label_fa = class_names.get(int(class_id), ('unknown', 'ناشناخته'))
51
  counts[label_en] = counts.get(label_en, 0) + 1
52
 
53
- draw.rectangle([(xmin, ymin), (xmax, ymax)], outline="red", width=2)
54
- draw.text((xmin, ymin), f"{label_en}: {conf:.2f}", fill="white")
55
-
56
  df = pd.DataFrame({
57
  'Label (English)': list(counts.keys()),
58
  'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in counts.keys()],
59
  'Object Count': list(counts.values())
60
  })
61
 
62
- return input_image, df
63
-
64
- # تابع برای تشخیص اشیاء در ویدئوها
65
- def detect_and_draw_video(video_path):
66
- cap = cv2.VideoCapture(video_path)
67
- frames = []
68
- overall_counts = {}
69
- seen_objects = [] # لیست برای دنبال کردن اشیاء شناسایی شده
70
-
71
- while cap.isOpened():
72
- ret, frame = cap.read()
73
- if not ret:
74
- break
75
-
76
- frame = cv2.resize(frame, (640, 480))
77
- results = model.predict(frame, conf=0.5, iou=0.6, stream=True)
78
- detections = results[0].boxes.boxes if results and results[0].boxes else None
79
-
80
- if detections is not None:
81
- detections = detections.cpu().numpy()
82
- for detection in detections:
83
- xmin, ymin, xmax, ymax, conf, class_id = detection
84
- label_en, label_fa = class_names.get(int(class_id), ('unknown', 'ناشناخته'))
85
- current_object = (label_en, int(xmin), int(ymin), int(xmax), int(ymax))
86
-
87
- # بررسی وجود شیء در لیست seen_objects
88
- if not any(existing[0] == label_en and
89
- (existing[1] < xmax and existing[3] > xmin and
90
- existing[2] < ymax and existing[4] > ymin) for existing in seen_objects):
91
- seen_objects.append(current_object)
92
- overall_counts[label_en] = overall_counts.get(label_en, 0) + 1
93
-
94
- # رسم مستطیل و نام شیء بر روی فریم
95
- cv2.rectangle(frame, (int(xmin), int(ymin)), (int(xmax), int(ymax)), (255, 0, 0), 2)
96
- cv2.putText(frame, f"{label_en}: {conf:.2f}", (int(xmin), int(ymin) - 10),
97
- cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
98
-
99
- frames.append(frame)
100
-
101
- cap.release()
102
-
103
- output_path = 'output.mp4'
104
- out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'mp4v'), 20.0, (640, 480))
105
-
106
- for frame in frames:
107
- out.write(frame)
108
- out.release()
109
-
110
- # ایجاد DataFrame برای ذخیره نتایج
111
- df = pd.DataFrame({
112
- 'Label (English)': list(overall_counts.keys()),
113
- 'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in overall_counts.keys()],
114
- 'Object Count': list(overall_counts.values())
115
- })
116
-
117
- return output_path, df
118
 
119
  # رابط کاربری تصویر
120
  image_interface = gr.Interface(
@@ -123,19 +63,9 @@ image_interface = gr.Interface(
123
  outputs=[gr.Image(type="pil"), gr.Dataframe(label="تعداد اشیاء")],
124
  title="تشخیص اشیاء در تصاویر هوایی",
125
  description="یک تصویر هوایی بارگذاری کنید تا اشیاء شناسایی شده و تعداد آن‌ها را ببینید.",
126
- examples=['Examples/images/areial_car.jpg', '/Examples/images/arieal_car_1.jpg', 'Examples/images/t.jpg']
127
- )
128
-
129
- # رابط کاربری ویدئو
130
- video_interface = gr.Interface(
131
- fn=detect_and_draw_video,
132
- inputs=gr.Video(label="بارگذاری ویدئو"),
133
- outputs=[gr.Video(label="ویدئوی پردازش شده"), gr.Dataframe(label="تعداد اشیاء")],
134
- title="تشخیص اشیاء در ویدئوها",
135
- description="یک ویدئو بارگذاری کنید تا اشیاء شناسایی شده و تعداد آن‌ها را ببینید.",
136
- examples=['Examples/video/city.mp4', 'Examples/video/airplane.mp4']
137
  )
138
 
139
- # اجرای برنامه با استفاده از رابط کاربری تب‌دار
140
- app = gr.TabbedInterface([image_interface, video_interface], ["تشخیص تصویر", "تشخیص ویدئو"])
141
  app.launch(debug=True, share=True)
 
1
  import cv2
2
  from ultralytics import YOLO
3
+ from PIL import Image
4
  import gradio as gr
5
  import pandas as pd
6
+ import numpy as np
7
 
8
  # بارگذاری مدل آموزش‌دیده شما
9
  model = YOLO('weights/best.pt')
 
29
 
30
  # تابع برای تشخیص اشیاء در تصاویر
31
  def detect_and_draw_image(input_image):
32
+ # تبدیل تصویر PIL به آرایه NumPy
33
+ input_image_np = np.array(input_image)
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ # اجرای مدل روی تصویر
36
+ results = model.predict(source=input_image_np, conf=0.25)
37
+
38
+ # دریافت تصویر با نتایج رسم‌شده
39
+ annotated_image = results[0].plot()
40
+
41
+ # تبدیل تصویر به فرمت PIL برای نمایش در Gradio
42
+ annotated_image_pil = Image.fromarray(annotated_image)
43
+
44
+ # شمارش اشیاء شناسایی‌شده
45
  counts = {}
46
+ for box in results[0].boxes:
47
+ class_id = int(box.cls[0])
48
+ label_en, label_fa = class_names.get(class_id, ('unknown', 'ناشناخته'))
49
  counts[label_en] = counts.get(label_en, 0) + 1
50
 
 
 
 
51
  df = pd.DataFrame({
52
  'Label (English)': list(counts.keys()),
53
  'Label (Persian)': [class_names.get(k, ('unknown', 'ناشناخته'))[1] for k in counts.keys()],
54
  'Object Count': list(counts.values())
55
  })
56
 
57
+ return annotated_image_pil, df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  # رابط کاربری تصویر
60
  image_interface = gr.Interface(
 
63
  outputs=[gr.Image(type="pil"), gr.Dataframe(label="تعداد اشیاء")],
64
  title="تشخیص اشیاء در تصاویر هوایی",
65
  description="یک تصویر هوایی بارگذاری کنید تا اشیاء شناسایی شده و تعداد آن‌ها را ببینید.",
66
+ examples=['Examples/images/areial_car.jpg', 'Examples/images/arieal_car_1.jpg','Examples/images/t.jpg']
 
 
 
 
 
 
 
 
 
 
67
  )
68
 
69
+ # اجرای برنامه
70
+ app = gr.Interface(fn=detect_and_draw_image, inputs=gr.Image(type="pil"), outputs=[gr.Image(type="pil"), gr.Dataframe()])
71
  app.launch(debug=True, share=True)