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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -71
app.py CHANGED
@@ -1,71 +1,64 @@
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()
 
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
+ import requests
9
+ import os
10
+
11
+ # Model setup
12
+ model_url = "https://huggingface.co/your_model_path/mask_rcnn_lego.pth" # Replace with your URL
13
+ model_path = "mask_rcnn_lego.pth"
14
+
15
+ if not os.path.exists(model_path):
16
+ response = requests.get(model_url)
17
+ with open(model_path, "wb") as f:
18
+ f.write(response.content)
19
+
20
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
+ model = maskrcnn_resnet50_fpn(weights="DEFAULT")
22
+ in_features = model.roi_heads.box_predictor.cls_score.in_features
23
+ model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes=2)
24
+ in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels
25
+ hidden_layer = 256
26
+ model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, hidden_layer, num_classes=2)
27
+ model.load_state_dict(torch.load(model_path, map_location=device))
28
+ model.to(device)
29
+ model.eval()
30
+
31
+ # Set up transformations
32
+ transform = T.Compose([T.ToTensor()])
33
+
34
+ # Function for image processing and bounding box detection
35
+ def detect_legos(image):
36
+ img_tensor = transform(image).unsqueeze(0).to(device)
37
+ with torch.no_grad():
38
+ outputs = model(img_tensor)
39
+ boxes = outputs[0]["boxes"].cpu().numpy()
40
+ num_legos_detected = len(boxes)
41
+ draw = ImageDraw.Draw(image)
42
+ for box in boxes:
43
+ x1, y1, x2, y2 = box
44
+ draw.rectangle([x1, y1, x2, y2], outline="red", width=3)
45
+ title = f"Detected LEGO pieces: {num_legos_detected}"
46
+ return image, title
47
+
48
+ # Gradio interface function
49
+ def gradio_interface(image):
50
+ image_with_boxes, title = detect_legos(image)
51
+ return image_with_boxes, title
52
+
53
+ # Set up Gradio Interface
54
+ interface = gr.Interface(
55
+ fn=gradio_interface,
56
+ inputs=gr.Image(type="pil"),
57
+ outputs=[gr.Image(type="pil"), gr.Textbox(label="Detection Summary")],
58
+ title="LEGO Detection with Mask R-CNN",
59
+ description="Upload an image to detect and count LEGO pieces with bounding boxes."
60
+ )
61
+
62
+ # Launch interface (no share=True needed for Gradio hosted or Hugging Face)
63
+ interface.launch()
64
+