Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -25,28 +25,36 @@ transform = transforms.Compose([
|
|
| 25 |
|
| 26 |
# Prediction function
|
| 27 |
def predict(image):
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
# Gradio interface
|
| 52 |
iface = gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs=gr.Image(type="pil"), title="Object Detection with Faster R-CNN")
|
|
|
|
| 25 |
|
| 26 |
# Prediction function
|
| 27 |
def predict(image):
|
| 28 |
+
try:
|
| 29 |
+
# Transform the image
|
| 30 |
+
image_tensor = transform(image).unsqueeze(0) # Add batch dimension
|
| 31 |
+
with torch.no_grad():
|
| 32 |
+
predictions = model(image_tensor)
|
| 33 |
+
|
| 34 |
+
# Process predictions
|
| 35 |
+
boxes = predictions[0]['boxes'].cpu().numpy()
|
| 36 |
+
scores = predictions[0]['scores'].cpu().numpy()
|
| 37 |
+
labels = predictions[0]['labels'].cpu().numpy()
|
| 38 |
+
|
| 39 |
+
# Filter out low-confidence predictions
|
| 40 |
+
threshold = 0.5
|
| 41 |
+
boxes = boxes[scores > threshold]
|
| 42 |
+
labels = labels[scores > threshold]
|
| 43 |
+
|
| 44 |
+
# Convert the input image to a NumPy array
|
| 45 |
+
image_np = np.array(image)
|
| 46 |
+
|
| 47 |
+
# Draw boxes on the image
|
| 48 |
+
for box, label in zip(boxes, labels):
|
| 49 |
+
x1, y1, x2, y2 = box.astype(int)
|
| 50 |
+
image_np = cv2.rectangle(image_np, (x1, y1), (x2, y2), (255, 0, 0), 2)
|
| 51 |
+
image_np = cv2.putText(image_np, str(label), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
|
| 52 |
+
|
| 53 |
+
# Ensure the output is in the correct format
|
| 54 |
+
return Image.fromarray(image_np.astype(np.uint8))
|
| 55 |
+
|
| 56 |
+
except Exception as e:
|
| 57 |
+
return f"Error: {str(e)}"
|
| 58 |
|
| 59 |
# Gradio interface
|
| 60 |
iface = gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs=gr.Image(type="pil"), title="Object Detection with Faster R-CNN")
|