nnibras commited on
Commit
9bb7e7f
·
verified ·
1 Parent(s): 66a9677

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +71 -0
  2. requirements.txt.txt +5 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ import torchvision.transforms as T
4
+ from PIL import Image, ImageDraw
5
+ from torchvision.models.detection import maskrcnn_resnet50_fpn
6
+ from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
7
+ from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor
8
+
9
+ # Set up device
10
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
11
+
12
+ # Load the saved model
13
+ model_path = "mask_rcnn_lego.pth"
14
+ model = maskrcnn_resnet50_fpn(weights="DEFAULT")
15
+ in_features = model.roi_heads.box_predictor.cls_score.in_features
16
+ model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes=2)
17
+ in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels
18
+ hidden_layer = 256
19
+ model.roi_heads.mask_predictor = MaskRCNNPredictor(
20
+ in_features_mask, hidden_layer, num_classes=2
21
+ )
22
+ model.load_state_dict(torch.load(model_path, map_location=device))
23
+ model.to(device)
24
+ model.eval()
25
+
26
+ # Set up transformations
27
+ transform = T.Compose([T.ToTensor()])
28
+
29
+
30
+ # Function to process image and return bounding boxes and count
31
+ def detect_legos(image):
32
+ # Apply transformations
33
+ img_tensor = transform(image).unsqueeze(0).to(device)
34
+
35
+ # Make predictions
36
+ with torch.no_grad():
37
+ outputs = model(img_tensor)
38
+
39
+ # Extract boxes and draw them
40
+ boxes = outputs[0]["boxes"].cpu().numpy()
41
+ num_legos_detected = len(boxes)
42
+
43
+ # Draw bounding boxes on the image
44
+ draw = ImageDraw.Draw(image)
45
+ for box in boxes:
46
+ x1, y1, x2, y2 = box
47
+ draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
48
+
49
+ # Set a title with the count of detected objects
50
+ title = f"Detected LEGO pieces: {num_legos_detected}"
51
+
52
+ return image, title
53
+
54
+
55
+ # Gradio interface function
56
+ def gradio_interface(image):
57
+ image_with_boxes, title = detect_legos(image)
58
+ return image_with_boxes, title
59
+
60
+
61
+ # Set up Gradio Interface with the new API
62
+ interface = gr.Interface(
63
+ fn=gradio_interface,
64
+ inputs=gr.Image(type="pil"),
65
+ outputs=[gr.Image(type="pil"), gr.Textbox(label="Detection Summary")],
66
+ title="LEGO Detection with Mask R-CNN",
67
+ description="Upload an image to detect and count LEGO pieces with bounding boxes.",
68
+ )
69
+
70
+ # Launch the Gradio app
71
+ interface.launch()
requirements.txt.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ gradio
4
+ pillow
5
+ requests