Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -249,6 +249,7 @@ def get_akc_breeds_link():
|
|
249 |
# if __name__ == "__main__":
|
250 |
# iface.launch()
|
251 |
|
|
|
252 |
def format_description(description, breed):
|
253 |
if isinstance(description, dict):
|
254 |
# 確保每一個描述項目換行顯示
|
@@ -267,6 +268,38 @@ def format_description(description, breed):
|
|
267 |
|
268 |
return formatted_description
|
269 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
270 |
async def predict(image):
|
271 |
if image is None:
|
272 |
return "Please upload an image to start.", None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|
|
|
249 |
# if __name__ == "__main__":
|
250 |
# iface.launch()
|
251 |
|
252 |
+
|
253 |
def format_description(description, breed):
|
254 |
if isinstance(description, dict):
|
255 |
# 確保每一個描述項目換行顯示
|
|
|
268 |
|
269 |
return formatted_description
|
270 |
|
271 |
+
async def predict_single_dog(image):
|
272 |
+
return await asyncio.to_thread(_predict_single_dog, image)
|
273 |
+
|
274 |
+
def _predict_single_dog(image):
|
275 |
+
image_tensor = preprocess_image(image)
|
276 |
+
with torch.no_grad():
|
277 |
+
output = model(image_tensor)
|
278 |
+
logits = output[0] if isinstance(output, tuple) else output
|
279 |
+
probabilities = F.softmax(logits, dim=1)
|
280 |
+
topk_probs, topk_indices = torch.topk(probabilities, k=3)
|
281 |
+
top1_prob = topk_probs[0][0].item()
|
282 |
+
topk_breeds = [dog_breeds[idx.item()] for idx in topk_indices[0]]
|
283 |
+
topk_probs_percent = [f"{prob.item() * 100:.2f}%" for prob in topk_probs[0]]
|
284 |
+
return top1_prob, topk_breeds, topk_probs_percent
|
285 |
+
|
286 |
+
async def detect_multiple_dogs(image, conf_threshold=0.3):
|
287 |
+
# 調整 YOLO 模型的置信度閾值
|
288 |
+
return await asyncio.to_thread(_detect_multiple_dogs, image, conf_threshold)
|
289 |
+
|
290 |
+
def _detect_multiple_dogs(image, conf_threshold):
|
291 |
+
results = model_yolo(image, conf=conf_threshold)
|
292 |
+
dogs = []
|
293 |
+
for result in results:
|
294 |
+
for box in result.boxes:
|
295 |
+
if box.cls == 16: # COCO 資料集中狗的類別是 16
|
296 |
+
xyxy = box.xyxy[0].tolist()
|
297 |
+
confidence = box.conf.item()
|
298 |
+
if confidence >= conf_threshold: # 只保留置信度高於閾值的框
|
299 |
+
cropped_image = image.crop((xyxy[0], xyxy[1], xyxy[2], xyxy[3]))
|
300 |
+
dogs.append((cropped_image, confidence, xyxy))
|
301 |
+
return dogs
|
302 |
+
|
303 |
async def predict(image):
|
304 |
if image is None:
|
305 |
return "Please upload an image to start.", None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
|