birgermoell commited on
Commit
76707ac
1 Parent(s): 3fa5590

Create sam_api.py

Browse files
Files changed (1) hide show
  1. sam_api.py +49 -0
sam_api.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import requests
3
+ from io import BytesIO
4
+ from PIL import Image
5
+
6
+ from segment_anything import SamPredictor, sam_model_registry
7
+ from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+
11
+ def segment_image_from_url(image_url):
12
+ sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
13
+ mask_generator = SamAutomaticMaskGenerator(sam)
14
+
15
+ response = requests.get(image_url)
16
+ img = Image.open(BytesIO(response.content))
17
+ image = np.array(img)
18
+
19
+ masks = mask_generator.generate(image)
20
+
21
+ plt.figure(figsize=(20,20))
22
+ plt.imshow(image)
23
+ show_anns(masks)
24
+ plt.axis('off')
25
+ output_file = 'segmented_image.png'
26
+ plt.savefig(output_file)
27
+ plt.close()
28
+ return output_file
29
+
30
+ def show_anns(anns):
31
+ if len(anns) == 0:
32
+ return
33
+ sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)
34
+ ax = plt.gca()
35
+ ax.set_autoscale_on(False)
36
+ polygons = []
37
+ color = []
38
+ for ann in sorted_anns:
39
+ m = ann['segmentation']
40
+ img = np.ones((m.shape[0], m.shape[1], 3))
41
+ color_mask = np.random.random((1, 3)).tolist()[0]
42
+ for i in range(3):
43
+ img[:,:,i] = color_mask[i]
44
+ ax.imshow(np.dstack((img, m*0.35)))
45
+
46
+ # Example usage
47
+ # image_url = 'https://example.com/path/to/image.jpg'
48
+ # output_file = segment_image_from_url(image_url)
49
+ # print(f"Segmented image saved to {output_file}")