Girishug commited on
Commit
8e98acf
·
verified ·
1 Parent(s): 2db4c71

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -22
app.py CHANGED
@@ -25,28 +25,36 @@ transform = transforms.Compose([
25
 
26
  # Prediction function
27
  def predict(image):
28
- image = transform(image).unsqueeze(0) # Add batch dimension
29
- with torch.no_grad():
30
- predictions = model(image)
31
-
32
- # Process predictions
33
- boxes = predictions[0]['boxes'].cpu().numpy()
34
- scores = predictions[0]['scores'].cpu().numpy()
35
- labels = predictions[0]['labels'].cpu().numpy()
36
-
37
- # Filter out low-confidence predictions
38
- threshold = 0.5
39
- boxes = boxes[scores > threshold]
40
- labels = labels[scores > threshold]
41
-
42
- # Draw boxes on the image
43
- image_np = np.array(image.squeeze().permute(1, 2, 0).cpu())
44
- for box, label in zip(boxes, labels):
45
- x1, y1, x2, y2 = box.astype(int)
46
- image_np = cv2.rectangle(image_np, (x1, y1), (x2, y2), (255, 0, 0), 2)
47
- image_np = cv2.putText(image_np, str(label), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
48
-
49
- return Image.fromarray(image_np)
 
 
 
 
 
 
 
 
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")