rgera commited on
Commit
40574ce
·
1 Parent(s): ff86e73
Files changed (1) hide show
  1. app.py +28 -11
app.py CHANGED
@@ -14,24 +14,41 @@ model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=0.9)
14
  #path = Path("object_detection_model.pth")
15
  #model = torch.load(path)
16
 
17
- def predict(inp1):
18
- model.eval()
 
 
 
 
 
 
19
 
20
- # Step 2: Initialize the inference transforms
21
- preprocess = weights.transforms()
 
 
 
 
 
22
 
23
- # Step 3: Apply inference preprocessing transforms
24
  batch = [preprocess(inp1)]
25
 
26
  # Step 4: Use the model and visualize the prediction
27
  prediction = model(batch)[0]
28
  labels = [weights.meta["categories"][i] for i in prediction["labels"]]
29
- box = draw_bounding_boxes(inp1, boxes=prediction["boxes"],
30
- labels=labels,
31
- colors="red",
32
- width=4, font_size=30)
33
- im = to_pil_image(box.detach())
34
- return labels[0],im
 
 
 
 
 
 
 
35
 
36
 
37
  # Get example filepaths in a list of lists
 
14
  #path = Path("object_detection_model.pth")
15
  #model = torch.load(path)
16
 
17
+ from PIL import Image,ImageDraw
18
+ from torchvision.io.image import read_image
19
+ from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2, FasterRCNN_ResNet50_FPN_V2_Weights
20
+ from torchvision.utils import draw_bounding_boxes
21
+ from torchvision import transforms
22
+ from torchvision.transforms.functional import to_pil_image,to_tensor
23
+ from pathlib import Path
24
+ import torch
25
 
26
+ # Step 1: Initiali1ze model with the best available weights
27
+ weights = FasterRCNN_ResNet50_FPN_V2_Weights.DEFAULT
28
+ model = fasterrcnn_resnet50_fpn_v2(weights=weights, box_score_thresh=0.9)
29
+ preprocess = weights.transforms()
30
+
31
+ def predict1(inp1):
32
+ model.eval()
33
 
 
34
  batch = [preprocess(inp1)]
35
 
36
  # Step 4: Use the model and visualize the prediction
37
  prediction = model(batch)[0]
38
  labels = [weights.meta["categories"][i] for i in prediction["labels"]]
39
+
40
+ draw = ImageDraw.Draw(inp1)
41
+ z = prediction["boxes"]
42
+
43
+ # Define the bounding box coordinates and size (adjust these values as needed)
44
+ outline_color = "red"
45
+ line_width = 2
46
+
47
+ # Draw the bounding box as a rectangle
48
+ x,y,l,k = z[0][0].item(), z[0][1].item(), z[0][2].item(), z[0][3].item()
49
+ draw.rectangle([x, y,l,k], outline=outline_color, width=line_width)
50
+
51
+ return labels[0],inp1
52
 
53
 
54
  # Get example filepaths in a list of lists