NoahH7 commited on
Commit
64d6f92
·
verified ·
1 Parent(s): a3306f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -16
app.py CHANGED
@@ -1,26 +1,35 @@
 
1
  from transformers import DetrImageProcessor, DetrForObjectDetection
2
  import torch
3
  from PIL import Image
4
  import requests
5
 
6
- url = "http://images.cocodataset.org/val2017/000000039769.jpg"
7
- image = Image.open(requests.get(url, stream=True).raw)
8
-
9
- # you can specify the revision tag if you don't want the timm dependency
10
  processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
11
  model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
12
 
13
- inputs = processor(images=image, return_tensors="pt")
14
- outputs = model(**inputs)
15
-
16
- # convert outputs (bounding boxes and class logits) to COCO API
17
- # let's only keep detections with score > 0.9
18
- target_sizes = torch.tensor([image.size[::-1]])
19
- results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
20
-
21
- for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
22
- box = [round(i, 2) for i in box.tolist()]
23
- print(
24
  f"Detected {model.config.id2label[label.item()]} with confidence "
25
  f"{round(score.item(), 3)} at location {box}"
26
- )
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
  from transformers import DetrImageProcessor, DetrForObjectDetection
3
  import torch
4
  from PIL import Image
5
  import requests
6
 
7
+ # Charger le modèle
 
 
 
8
  processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
9
  model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
10
 
11
+ def detect_objects(image_url):
12
+ image = Image.open(requests.get(image_url, stream=True).raw)
13
+ inputs = processor(images=image, return_tensors="pt")
14
+ outputs = model(**inputs)
15
+ target_sizes = torch.tensor([image.size[::-1]])
16
+ results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
17
+
18
+ detections = []
19
+ for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
20
+ box = [round(i, 2) for i in box.tolist()]
21
+ detections.append(
22
  f"Detected {model.config.id2label[label.item()]} with confidence "
23
  f"{round(score.item(), 3)} at location {box}"
24
+ )
25
+ return "\n".join(detections)
26
+
27
+ # Interface Gradio
28
+ iface = gr.Interface(
29
+ fn=detect_objects,
30
+ inputs="text", # Entrée: une URL d'image
31
+ outputs="text", # Sortie: liste des détections
32
+ description="Paste an image URL to detect objects."
33
+ )
34
+
35
+ iface.launch()