sakshee05 commited on
Commit
70ae50f
·
verified ·
1 Parent(s): 1085ce5

add sam2 endpoint

Browse files
Files changed (1) hide show
  1. main.py +69 -4
main.py CHANGED
@@ -14,6 +14,10 @@ import io
14
  import numpy as np
15
  from lang_sam import LangSAM
16
  import supervision as sv
 
 
 
 
17
 
18
  app = FastAPI()
19
 
@@ -30,13 +34,36 @@ app.add_middleware(
30
  os.makedirs("/tmp/huggingface", exist_ok=True)
31
  os.makedirs("/tmp/torch", exist_ok=True)
32
 
33
- # Load the segmentation model
34
- model = LangSAM()
 
 
 
 
 
 
 
 
35
 
36
  @app.get("/")
37
  async def root():
38
  return {"message": "LangSAM API is running!"}
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def draw_image(image_rgb, masks, xyxy, probs, labels):
41
  mask_annotator = sv.MaskAnnotator()
42
  # Create class_id for each unique label
@@ -54,13 +81,51 @@ def draw_image(image_rgb, masks, xyxy, probs, labels):
54
  annotated_image = mask_annotator.annotate(scene=image_rgb.copy(), detections=detections)
55
  return annotated_image
56
 
57
- @app.post("/segment/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  async def segment_image(file: UploadFile = File(...), text_prompt: str = Form(...)):
59
  image_bytes = await file.read()
60
  image_pil = Image.open(io.BytesIO(image_bytes)).convert("RGB")
61
 
62
  # Run segmentation
63
- results = model.predict([image_pil], [text_prompt])
64
 
65
  # Convert to NumPy array
66
  image_array = np.asarray(image_pil)
 
14
  import numpy as np
15
  from lang_sam import LangSAM
16
  import supervision as sv
17
+ from sam2.build_sam import build_sam2
18
+ from sam2.sam2_image_predictor import SAM2ImagePredictor
19
+ import torch
20
+ import cv2
21
 
22
  app = FastAPI()
23
 
 
34
  os.makedirs("/tmp/huggingface", exist_ok=True)
35
  os.makedirs("/tmp/torch", exist_ok=True)
36
 
37
+ # Load the langSAM model
38
+ langsam_model = LangSAM()
39
+
40
+ # Load SAM2 Model
41
+ sam2_checkpoint = "sam2.1_hiera_small.pt"
42
+ model_cfg = "configs/sam2.1/sam2.1_hiera_s.yaml"
43
+ device = torch.device("cpu")
44
+
45
+ sam2_model = build_sam2(model_cfg, sam2_checkpoint, device=device)
46
+ predictor = SAM2ImagePredictor(sam2_model)
47
 
48
  @app.get("/")
49
  async def root():
50
  return {"message": "LangSAM API is running!"}
51
 
52
+ def apply_mask(image, mask):
53
+ """Overlay mask on image."""
54
+ mask = mask.astype(np.uint8) * 255 # Convert mask to 0-255 scale
55
+ mask_colored = np.zeros((*mask.shape, 3), dtype=np.uint8)
56
+ mask_colored[mask > 0] = [30, 144, 255] # Blue color for the mask
57
+
58
+ # Add contour
59
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
60
+ cv2.drawContours(mask_colored, contours, -1, (255, 255, 255), thickness=2)
61
+
62
+ # Blend with original image
63
+ overlay = cv2.addWeighted(image, 0.7, mask_colored, 0.3, 0)
64
+ return overlay
65
+
66
+
67
  def draw_image(image_rgb, masks, xyxy, probs, labels):
68
  mask_annotator = sv.MaskAnnotator()
69
  # Create class_id for each unique label
 
81
  annotated_image = mask_annotator.annotate(scene=image_rgb.copy(), detections=detections)
82
  return annotated_image
83
 
84
+ @app.post("/segment/sam2")
85
+ async def segment_image(
86
+ file: UploadFile = File(...),
87
+ x: int = Form(...),
88
+ y: int = Form(...)
89
+ ):
90
+ """Segment image using SAM2 with a single input point."""
91
+ image_bytes = await file.read()
92
+ image_pil = Image.open(io.BytesIO(image_bytes)).convert("RGB")
93
+ image_array = np.array(image_pil)
94
+
95
+ predictor.set_image(image_array)
96
+
97
+ input_point = np.array([[x, y]])
98
+ input_label = np.array([1]) # Foreground point
99
+
100
+ # Run SAM2 model
101
+ masks, scores, logits = predictor.predict(
102
+ point_coords=input_point,
103
+ point_labels=input_label,
104
+ multimask_output=True,
105
+ )
106
+
107
+ # Get top mask
108
+ top_mask = masks[np.argmax(scores)]
109
+
110
+ # Apply mask overlay
111
+ output_image = apply_mask(image_array, top_mask)
112
+
113
+ # Convert to PNG
114
+ output_pil = Image.fromarray(output_image)
115
+ img_io = io.BytesIO()
116
+ output_pil.save(img_io, format="PNG")
117
+ img_io.seek(0)
118
+
119
+ return Response(content=img_io.getvalue(), media_type="image/png")
120
+
121
+
122
+ @app.post("/segment/langsam")
123
  async def segment_image(file: UploadFile = File(...), text_prompt: str = Form(...)):
124
  image_bytes = await file.read()
125
  image_pil = Image.open(io.BytesIO(image_bytes)).convert("RGB")
126
 
127
  # Run segmentation
128
+ results = langsam_model.predict([image_pil], [text_prompt])
129
 
130
  # Convert to NumPy array
131
  image_array = np.asarray(image_pil)