DawnC commited on
Commit
4984329
1 Parent(s): 18941a4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -111
app.py CHANGED
@@ -167,59 +167,35 @@ async def predict_single_dog(image):
167
  return top1_prob, topk_breeds, topk_probs_percent
168
 
169
 
170
- # async def detect_multiple_dogs(image, conf_threshold=0.25, iou_threshold=0.6):
171
- # results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0]
172
- # dogs = []
173
- # boxes = []
174
- # for box in results.boxes:
175
- # if box.cls == 16: # COCO dataset class for dog is 16
176
- # xyxy = box.xyxy[0].tolist()
177
- # confidence = box.conf.item()
178
- # boxes.append((xyxy, confidence))
179
-
180
- # if not boxes:
181
- # dogs.append((image, 1.0, [0, 0, image.width, image.height]))
182
- # else:
183
- # nms_boxes = non_max_suppression(boxes, iou_threshold)
184
-
185
- # for box, confidence in nms_boxes:
186
- # x1, y1, x2, y2 = box
187
- # w, h = x2 - x1, y2 - y1
188
- # x1 = max(0, x1 - w * 0.05)
189
- # y1 = max(0, y1 - h * 0.05)
190
- # x2 = min(image.width, x2 + w * 0.05)
191
- # y2 = min(image.height, y2 + h * 0.05)
192
- # cropped_image = image.crop((x1, y1, x2, y2))
193
- # dogs.append((cropped_image, confidence, [x1, y1, x2, y2]))
194
-
195
- # return dogs
196
-
197
-
198
- async def detect_multiple_dogs(image, conf_threshold=0.4, iou_threshold=0.5):
199
- # 提高conf_threshold來減少無效框
200
  results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0]
201
  dogs = []
202
  boxes = []
203
  for box in results.boxes:
204
- if box.cls == 16: # 確保是狗的類別
205
  xyxy = box.xyxy[0].tolist()
206
  confidence = box.conf.item()
207
- # 只保存高信心的框,降低不必要框的數量
208
- if confidence >= conf_threshold:
209
- boxes.append((xyxy, confidence))
210
 
211
  if not boxes:
212
- # 沒有檢測到狗,使用整張圖
213
  dogs.append((image, 1.0, [0, 0, image.width, image.height]))
214
  else:
215
  nms_boxes = non_max_suppression(boxes, iou_threshold)
 
216
  for box, confidence in nms_boxes:
217
  x1, y1, x2, y2 = box
 
 
 
 
 
218
  cropped_image = image.crop((x1, y1, x2, y2))
219
  dogs.append((cropped_image, confidence, [x1, y1, x2, y2]))
220
 
221
  return dogs
222
 
 
 
223
  def non_max_suppression(boxes, iou_threshold):
224
  keep = []
225
  boxes = sorted(boxes, key=lambda x: x[1], reverse=True)
@@ -291,87 +267,16 @@ async def process_single_dog(image):
291
  return explanation, image, buttons[0], buttons[1], buttons[2], gr.update(visible=True), initial_state
292
 
293
 
294
- # async def predict(image):
295
- # if image is None:
296
- # return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
297
-
298
- # try:
299
- # if isinstance(image, np.ndarray):
300
- # image = Image.fromarray(image)
301
-
302
- # dogs = await detect_multiple_dogs(image)
303
-
304
- # color_list = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#800080', '#FFA500']
305
- # explanations = []
306
- # buttons = []
307
- # annotated_image = image.copy()
308
- # draw = ImageDraw.Draw(annotated_image)
309
- # font = ImageFont.load_default()
310
-
311
- # for i, (cropped_image, detection_confidence, box) in enumerate(dogs):
312
- # top1_prob, topk_breeds, topk_probs_percent = await predict_single_dog(cropped_image)
313
- # color = color_list[i % len(color_list)]
314
- # draw.rectangle(box, outline=color, width=3)
315
- # draw.text((box[0], box[1]), f"Dog {i+1}", fill=color, font=font)
316
-
317
- # combined_confidence = detection_confidence * top1_prob
318
-
319
- # if top1_prob >= 0.5:
320
- # breed = topk_breeds[0]
321
- # description = get_dog_description(breed)
322
- # formatted_description = format_description(description, breed)
323
- # explanations.append(f"Dog {i+1}: {formatted_description}")
324
- # elif combined_confidence >= 0.2:
325
- # dog_explanation = f"Dog {i+1}: Top 3 possible breeds:\n"
326
- # dog_explanation += "\n".join([f"{j+1}. **{breed}** ({prob} confidence)" for j, (breed, prob) in enumerate(zip(topk_breeds[:3], topk_probs_percent[:3]))])
327
- # explanations.append(dog_explanation)
328
- # buttons.extend([f"Dog {i+1}: More about {breed}" for breed in topk_breeds[:3]])
329
- # else:
330
- # explanations.append(f"Dog {i+1}: The image is unclear or the breed is not in the dataset. Please upload a clearer image.")
331
-
332
- # final_explanation = "\n\n".join(explanations)
333
- # if buttons:
334
- # final_explanation += "\n\nClick on a button to view more information about the breed."
335
- # initial_state = {
336
- # "explanation": final_explanation,
337
- # "buttons": buttons,
338
- # "show_back": True,
339
- # "image": annotated_image,
340
- # "is_multi_dog": len(dogs) > 1,
341
- # "dogs_info": explanations
342
- # }
343
- # return final_explanation, annotated_image, gr.update(visible=True, choices=buttons), initial_state
344
- # else:
345
- # initial_state = {
346
- # "explanation": final_explanation,
347
- # "buttons": [],
348
- # "show_back": False,
349
- # "image": annotated_image,
350
- # "is_multi_dog": len(dogs) > 1,
351
- # "dogs_info": explanations
352
- # }
353
- # return final_explanation, annotated_image, gr.update(visible=False, choices=[]), initial_state
354
-
355
- # except Exception as e:
356
- # error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
357
- # print(error_msg)
358
- # return error_msg, None, gr.update(visible=False, choices=[]), None
359
-
360
-
361
  async def predict(image):
362
  if image is None:
363
- return "Please upload an image to start.", None, gr.update(visible=False), None
364
 
365
  try:
366
  if isinstance(image, np.ndarray):
367
  image = Image.fromarray(image)
368
 
369
- # 根據圖像尺寸判斷是否應該使用YOLO框選
370
- if image.width > 500: # 假設寬度超過500像素才考慮多狗情況
371
- dogs = await detect_multiple_dogs(image)
372
- else:
373
- dogs = [(image, 1.0, [0, 0, image.width, image.height])]
374
-
375
  color_list = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#800080', '#FFA500']
376
  explanations = []
377
  buttons = []
@@ -403,9 +308,25 @@ async def predict(image):
403
  final_explanation = "\n\n".join(explanations)
404
  if buttons:
405
  final_explanation += "\n\nClick on a button to view more information about the breed."
406
- return final_explanation, annotated_image, gr.update(visible=True, choices=buttons)
 
 
 
 
 
 
 
 
407
  else:
408
- return final_explanation, annotated_image, gr.update(visible=False, choices=[])
 
 
 
 
 
 
 
 
409
 
410
  except Exception as e:
411
  error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
@@ -413,6 +334,7 @@ async def predict(image):
413
  return error_msg, None, gr.update(visible=False, choices=[]), None
414
 
415
 
 
416
  def show_details(choice, previous_output, initial_state):
417
  if not choice:
418
  return previous_output, gr.update(visible=True), initial_state
 
167
  return top1_prob, topk_breeds, topk_probs_percent
168
 
169
 
170
+ async def detect_multiple_dogs(image, conf_threshold=0.3, iou_threshold=0.55):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
  results = model_yolo(image, conf=conf_threshold, iou=iou_threshold)[0]
172
  dogs = []
173
  boxes = []
174
  for box in results.boxes:
175
+ if box.cls == 16: # COCO dataset class for dog is 16
176
  xyxy = box.xyxy[0].tolist()
177
  confidence = box.conf.item()
178
+ boxes.append((xyxy, confidence))
 
 
179
 
180
  if not boxes:
 
181
  dogs.append((image, 1.0, [0, 0, image.width, image.height]))
182
  else:
183
  nms_boxes = non_max_suppression(boxes, iou_threshold)
184
+
185
  for box, confidence in nms_boxes:
186
  x1, y1, x2, y2 = box
187
+ w, h = x2 - x1, y2 - y1
188
+ x1 = max(0, x1 - w * 0.05)
189
+ y1 = max(0, y1 - h * 0.05)
190
+ x2 = min(image.width, x2 + w * 0.05)
191
+ y2 = min(image.height, y2 + h * 0.05)
192
  cropped_image = image.crop((x1, y1, x2, y2))
193
  dogs.append((cropped_image, confidence, [x1, y1, x2, y2]))
194
 
195
  return dogs
196
 
197
+
198
+
199
  def non_max_suppression(boxes, iou_threshold):
200
  keep = []
201
  boxes = sorted(boxes, key=lambda x: x[1], reverse=True)
 
267
  return explanation, image, buttons[0], buttons[1], buttons[2], gr.update(visible=True), initial_state
268
 
269
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  async def predict(image):
271
  if image is None:
272
+ return "Please upload an image to start.", None, gr.update(visible=False, choices=[]), None
273
 
274
  try:
275
  if isinstance(image, np.ndarray):
276
  image = Image.fromarray(image)
277
 
278
+ dogs = await detect_multiple_dogs(image)
279
+
 
 
 
 
280
  color_list = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF', '#800080', '#FFA500']
281
  explanations = []
282
  buttons = []
 
308
  final_explanation = "\n\n".join(explanations)
309
  if buttons:
310
  final_explanation += "\n\nClick on a button to view more information about the breed."
311
+ initial_state = {
312
+ "explanation": final_explanation,
313
+ "buttons": buttons,
314
+ "show_back": True,
315
+ "image": annotated_image,
316
+ "is_multi_dog": len(dogs) > 1,
317
+ "dogs_info": explanations
318
+ }
319
+ return final_explanation, annotated_image, gr.update(visible=True, choices=buttons), initial_state
320
  else:
321
+ initial_state = {
322
+ "explanation": final_explanation,
323
+ "buttons": [],
324
+ "show_back": False,
325
+ "image": annotated_image,
326
+ "is_multi_dog": len(dogs) > 1,
327
+ "dogs_info": explanations
328
+ }
329
+ return final_explanation, annotated_image, gr.update(visible=False, choices=[]), initial_state
330
 
331
  except Exception as e:
332
  error_msg = f"An error occurred: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
 
334
  return error_msg, None, gr.update(visible=False, choices=[]), None
335
 
336
 
337
+
338
  def show_details(choice, previous_output, initial_state):
339
  if not choice:
340
  return previous_output, gr.update(visible=True), initial_state