muhammadsalmanalfaridzi commited on
Commit
d38d4bd
·
verified ·
1 Parent(s): b60852c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -34
app.py CHANGED
@@ -17,21 +17,24 @@ workspace = os.getenv("ROBOFLOW_WORKSPACE")
17
  project_name = os.getenv("ROBOFLOW_PROJECT")
18
  model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
19
 
20
- # CountGD Config (Replace DINO-X)
21
- # Set your CountGD API key in your .env file (e.g., COUNTGD_API_KEY=YourEncodedAPIKey)
22
  COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
23
 
24
- # Inisialisasi YOLO Model from Roboflow
25
  rf = Roboflow(api_key=rf_api_key)
26
  project = rf.workspace(workspace).project(project_name)
27
  yolo_model = project.version(model_version).model
28
 
29
- # ========== Function to Check Overlap ==========
 
 
 
30
  def is_overlap(box1, boxes2, threshold=0.3):
31
  """
32
- Checks if box1 (format: (x_min, y_min, x_max, y_max)) overlaps with any boxes in boxes2.
33
- boxes2 is a list of YOLO bounding boxes in the format (x_center, y_center, width, height).
34
- Returns True if the overlap ratio of box1 is greater than the threshold.
35
  """
36
  x1_min, y1_min, x1_max, y1_max = box1
37
  for b2 in boxes2:
@@ -41,7 +44,6 @@ def is_overlap(box1, boxes2, threshold=0.3):
41
  y2_min = y_center - h2 / 2
42
  y2_max = y_center + h2 / 2
43
 
44
- # Calculate overlap area
45
  dx = min(x1_max, x2_max) - max(x1_min, x2_min)
46
  dy = min(y1_max, y2_max) - max(y1_min, y2_min)
47
  if dx > 0 and dy > 0:
@@ -51,44 +53,45 @@ def is_overlap(box1, boxes2, threshold=0.3):
51
  return True
52
  return False
53
 
54
- # ========== Combined Object Detection Function ==========
55
  def detect_combined(image):
56
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
57
  image.save(temp_file, format="JPEG")
58
  temp_path = temp_file.name
59
 
60
  try:
61
- # ===== YOLO Detection (Nestlé products) =====
62
  yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
63
  nestle_class_count = {}
64
- nestle_boxes = [] # List to hold YOLO bounding boxes (format: x_center, y_center, width, height)
65
  for pred in yolo_pred['predictions']:
66
  class_name = pred['class']
67
  nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
68
  nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
69
  total_nestle = sum(nestle_class_count.values())
70
 
71
- # ===== CountGD Detection (Competitor products) =====
72
  url = "https://api.landing.ai/v1/tools/text-to-object-detection"
73
  files = {"image": open(temp_path, "rb")}
74
- data = {"prompts": ["mixed box"], "model": "countgd"}
 
75
  headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
76
  response = requests.post(url, files=files, data=data, headers=headers)
77
  result = response.json()
78
 
79
  competitor_class_count = {}
80
- competitor_boxes = [] # List to hold CountGD bounding boxes (format: x_min, y_min, x_max, y_max)
81
  if 'data' in result:
 
82
  for obj in result['data'][0]:
83
  if 'bounding_box' in obj:
84
- # CountGD returns bounding_box as [x_min, y_min, x_max, y_max]
85
  x1, y1, x2, y2 = obj['bounding_box']
86
- countgd_box = (x1, y1, x2, y2)
87
- # Only add CountGD detection if it does NOT significantly overlap with any YOLO detection
88
- if not is_overlap(countgd_box, nestle_boxes, threshold=0.3):
89
- class_name = "unclassified" # Generic label for competitor objects
90
- competitor_class_count[class_name] = competitor_class_count.get(class_name, 0) + 1
91
- competitor_boxes.append(countgd_box)
92
  total_competitor = sum(competitor_class_count.values())
93
 
94
  # ===== Format Output Text =====
@@ -97,13 +100,16 @@ def detect_combined(image):
97
  result_text += f"{class_name}: {count}\n"
98
  result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
99
  if total_competitor:
100
- result_text += f"Total Unclassified Products: {total_competitor}\n"
 
 
 
101
  else:
102
  result_text += "No Unclassified Products detected\n"
103
 
104
- # ===== Visualization =====
105
  img = cv2.imread(temp_path)
106
- # Draw YOLO boxes in green
107
  for pred in yolo_pred['predictions']:
108
  x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
109
  pt1 = (int(x - w/2), int(y - h/2))
@@ -111,10 +117,11 @@ def detect_combined(image):
111
  cv2.rectangle(img, pt1, pt2, (0, 255, 0), 2)
112
  cv2.putText(img, pred['class'], (pt1[0], pt1[1]-10),
113
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0), 3)
114
- # Draw CountGD boxes in red
115
  for box in competitor_boxes:
116
  x1, y1, x2, y2 = box
117
  cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
 
118
  cv2.putText(img, "unclassified", (int(x1), int(y1)-10),
119
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
120
 
@@ -129,7 +136,7 @@ def detect_combined(image):
129
  if os.path.exists(temp_path):
130
  os.remove(temp_path)
131
 
132
- # ========== Video Detection Functions ==========
133
  def convert_video_to_mp4(input_path, output_path):
134
  try:
135
  subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
@@ -141,23 +148,21 @@ def detect_objects_in_video(video_path):
141
  temp_output_path = "/tmp/output_video.mp4"
142
  temp_frames_dir = tempfile.mkdtemp()
143
  frame_count = 0
144
- previous_detections = {} # For storing previous frame's detections
145
 
146
  try:
147
- # Convert video to MP4 if necessary
148
  if not video_path.endswith(".mp4"):
149
  video_path, err = convert_video_to_mp4(video_path, temp_output_path)
150
  if not video_path:
151
  return None, f"Video conversion error: {err}"
152
 
153
- # Open video for processing
154
  video = cv2.VideoCapture(video_path)
155
  frame_rate = int(video.get(cv2.CAP_PROP_FPS))
156
  frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
157
  frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
158
  frame_size = (frame_width, frame_height)
159
 
160
- # Setup VideoWriter for output
161
  fourcc = cv2.VideoWriter_fourcc(*'mp4v')
162
  output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
163
 
@@ -166,14 +171,11 @@ def detect_objects_in_video(video_path):
166
  if not ret:
167
  break
168
 
169
- # Save frame for YOLO detection
170
  frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
171
  cv2.imwrite(frame_path, frame)
172
 
173
- # YOLO detection on the frame
174
  predictions = yolo_model.predict(frame_path, confidence=50, overlap=80).json()
175
 
176
- # Draw YOLO detections on the frame
177
  current_detections = {}
178
  for prediction in predictions['predictions']:
179
  class_name = prediction['class']
@@ -187,7 +189,6 @@ def detect_objects_in_video(video_path):
187
  cv2.putText(frame, class_name, (pt1[0], pt1[1]-10),
188
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
189
 
190
- # Count objects and overlay text
191
  object_counts = {}
192
  for detection_id in current_detections:
193
  cls = current_detections[detection_id]
 
17
  project_name = os.getenv("ROBOFLOW_PROJECT")
18
  model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
19
 
20
+ # CountGD Config (menggantikan DINO-X)
21
+ # Pastikan API key CountGD telah di-set di .env dengan key COUNTGD_API_KEY
22
  COUNTGD_API_KEY = os.getenv("COUNTGD_API_KEY")
23
 
24
+ # Inisialisasi YOLO Model dari Roboflow
25
  rf = Roboflow(api_key=rf_api_key)
26
  project = rf.workspace(workspace).project(project_name)
27
  yolo_model = project.version(model_version).model
28
 
29
+ # List prompt untuk CountGD (misal: cans, bottle, mixed box)
30
+ COUNTGD_PROMPTS = ["cans", "bottle", "mixed box"]
31
+
32
+ # ========== Fungsi untuk Mengecek Overlap ==========
33
  def is_overlap(box1, boxes2, threshold=0.3):
34
  """
35
+ Mengecek apakah box1 (format: (x_min, y_min, x_max, y_max)) overlap dengan salah satu box di boxes2.
36
+ boxes2 adalah list bounding box dari YOLO dengan format (x_center, y_center, width, height).
37
+ Mengembalikan True jika rasio overlap melebihi threshold.
38
  """
39
  x1_min, y1_min, x1_max, y1_max = box1
40
  for b2 in boxes2:
 
44
  y2_min = y_center - h2 / 2
45
  y2_max = y_center + h2 / 2
46
 
 
47
  dx = min(x1_max, x2_max) - max(x1_min, x2_min)
48
  dy = min(y1_max, y2_max) - max(y1_min, y2_min)
49
  if dx > 0 and dy > 0:
 
53
  return True
54
  return False
55
 
56
+ # ========== Fungsi Deteksi Kombinasi ==========
57
  def detect_combined(image):
58
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
59
  image.save(temp_file, format="JPEG")
60
  temp_path = temp_file.name
61
 
62
  try:
63
+ # ===== YOLO Detection (Produk Nestlé) =====
64
  yolo_pred = yolo_model.predict(temp_path, confidence=50, overlap=80).json()
65
  nestle_class_count = {}
66
+ nestle_boxes = [] # Menyimpan bounding box YOLO dengan format (x_center, y_center, width, height)
67
  for pred in yolo_pred['predictions']:
68
  class_name = pred['class']
69
  nestle_class_count[class_name] = nestle_class_count.get(class_name, 0) + 1
70
  nestle_boxes.append((pred['x'], pred['y'], pred['width'], pred['height']))
71
  total_nestle = sum(nestle_class_count.values())
72
 
73
+ # ===== CountGD Detection (Produk Kompetitor) =====
74
  url = "https://api.landing.ai/v1/tools/text-to-object-detection"
75
  files = {"image": open(temp_path, "rb")}
76
+ # Menggunakan lebih dari satu prompt
77
+ data = {"prompts": COUNTGD_PROMPTS, "model": "countgd"}
78
  headers = {"Authorization": f"Basic {COUNTGD_API_KEY}"}
79
  response = requests.post(url, files=files, data=data, headers=headers)
80
  result = response.json()
81
 
82
  competitor_class_count = {}
83
+ competitor_boxes = [] # Menyimpan bounding box CountGD dengan format (x_min, y_min, x_max, y_max)
84
  if 'data' in result:
85
+ # Asumsi API mengembalikan list deteksi pada data[0]
86
  for obj in result['data'][0]:
87
  if 'bounding_box' in obj:
 
88
  x1, y1, x2, y2 = obj['bounding_box']
89
+ # Mengambil label jika tersedia, default 'unclassified'
90
+ label = obj.get('label', 'unclassified')
91
+ # Hanya tambahkan deteksi jika tidak overlap dengan deteksi YOLO
92
+ if not is_overlap((x1, y1, x2, y2), nestle_boxes, threshold=0.3):
93
+ competitor_class_count[label] = competitor_class_count.get(label, 0) + 1
94
+ competitor_boxes.append((x1, y1, x2, y2))
95
  total_competitor = sum(competitor_class_count.values())
96
 
97
  # ===== Format Output Text =====
 
100
  result_text += f"{class_name}: {count}\n"
101
  result_text += f"\nTotal Products Nestlé: {total_nestle}\n\n"
102
  if total_competitor:
103
+ result_text += "Produk Kompetitor (CountGD) :\n"
104
+ for label, count in competitor_class_count.items():
105
+ result_text += f"{label}: {count}\n"
106
+ result_text += f"\nTotal Produk Kompetitor: {total_competitor}\n"
107
  else:
108
  result_text += "No Unclassified Products detected\n"
109
 
110
+ # ===== Visualisasi =====
111
  img = cv2.imread(temp_path)
112
+ # Gambar bounding box YOLO (hijau)
113
  for pred in yolo_pred['predictions']:
114
  x, y, w, h = pred['x'], pred['y'], pred['width'], pred['height']
115
  pt1 = (int(x - w/2), int(y - h/2))
 
117
  cv2.rectangle(img, pt1, pt2, (0, 255, 0), 2)
118
  cv2.putText(img, pred['class'], (pt1[0], pt1[1]-10),
119
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0), 3)
120
+ # Gambar bounding box CountGD (merah)
121
  for box in competitor_boxes:
122
  x1, y1, x2, y2 = box
123
  cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
124
+ # Tampilkan label hasil CountGD
125
  cv2.putText(img, "unclassified", (int(x1), int(y1)-10),
126
  cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,0,255), 3)
127
 
 
136
  if os.path.exists(temp_path):
137
  os.remove(temp_path)
138
 
139
+ # ========== Fungsi untuk Deteksi Video ==========
140
  def convert_video_to_mp4(input_path, output_path):
141
  try:
142
  subprocess.run(['ffmpeg', '-i', input_path, '-vcodec', 'libx264', '-acodec', 'aac', output_path], check=True)
 
148
  temp_output_path = "/tmp/output_video.mp4"
149
  temp_frames_dir = tempfile.mkdtemp()
150
  frame_count = 0
151
+ previous_detections = {} # Untuk menyimpan deteksi frame sebelumnya
152
 
153
  try:
154
+ # Konversi video ke MP4 jika perlu
155
  if not video_path.endswith(".mp4"):
156
  video_path, err = convert_video_to_mp4(video_path, temp_output_path)
157
  if not video_path:
158
  return None, f"Video conversion error: {err}"
159
 
 
160
  video = cv2.VideoCapture(video_path)
161
  frame_rate = int(video.get(cv2.CAP_PROP_FPS))
162
  frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
163
  frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
164
  frame_size = (frame_width, frame_height)
165
 
 
166
  fourcc = cv2.VideoWriter_fourcc(*'mp4v')
167
  output_video = cv2.VideoWriter(temp_output_path, fourcc, frame_rate, frame_size)
168
 
 
171
  if not ret:
172
  break
173
 
 
174
  frame_path = os.path.join(temp_frames_dir, f"frame_{frame_count}.jpg")
175
  cv2.imwrite(frame_path, frame)
176
 
 
177
  predictions = yolo_model.predict(frame_path, confidence=50, overlap=80).json()
178
 
 
179
  current_detections = {}
180
  for prediction in predictions['predictions']:
181
  class_name = prediction['class']
 
189
  cv2.putText(frame, class_name, (pt1[0], pt1[1]-10),
190
  cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
191
 
 
192
  object_counts = {}
193
  for detection_id in current_detections:
194
  cls = current_detections[detection_id]