Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -82,14 +82,30 @@ def detect_objects(image):
|
|
82 |
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
|
83 |
|
84 |
inputs = processor(images=image, return_tensors="pt")
|
85 |
-
|
86 |
outputs = model(**inputs)
|
87 |
|
88 |
target_sizes = torch.tensor([image.size[::-1]])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
return image, detected_cars
|
91 |
|
92 |
-
|
93 |
def image_to_bytes(img):
|
94 |
# Convert a PIL image to bytes
|
95 |
from io import BytesIO
|
|
|
82 |
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
|
83 |
|
84 |
inputs = processor(images=image, return_tensors="pt")
|
|
|
85 |
outputs = model(**inputs)
|
86 |
|
87 |
target_sizes = torch.tensor([image.size[::-1]])
|
88 |
+
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.9)[0]
|
89 |
+
|
90 |
+
detected_cars = []
|
91 |
+
draw = ImageDraw.Draw(image)
|
92 |
+
|
93 |
+
# Loop through detections and filter only "car" class (ID 3 for COCO dataset)
|
94 |
+
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
|
95 |
+
if model.config.id2label[label.item()] == 'car' and score.item() > 0.9:
|
96 |
+
box = [round(i, 2) for i in box.tolist()]
|
97 |
+
# Crop the detected car
|
98 |
+
cropped_car = image.crop(box)
|
99 |
+
# Convert the cropped image to bytes
|
100 |
+
cropped_car_bytes = image_to_bytes(cropped_car)
|
101 |
+
detected_cars.append((cropped_car_bytes, box))
|
102 |
+
|
103 |
+
# Draw bounding box around the car
|
104 |
+
draw.rectangle(box, outline="red", width=3)
|
105 |
+
draw.text((box[0], box[1]), f"Car: {round(score.item(), 2)}", fill="red")
|
106 |
|
107 |
return image, detected_cars
|
108 |
|
|
|
109 |
def image_to_bytes(img):
|
110 |
# Convert a PIL image to bytes
|
111 |
from io import BytesIO
|