medical-diffusion-sam / sam_api.py
birgermoell's picture
Create sam_api.py
76707ac
raw
history blame
1.46 kB
import cv2
import requests
from io import BytesIO
from PIL import Image
from segment_anything import SamPredictor, sam_model_registry
from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
import matplotlib.pyplot as plt
import numpy as np
def segment_image_from_url(image_url):
sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth")
mask_generator = SamAutomaticMaskGenerator(sam)
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
image = np.array(img)
masks = mask_generator.generate(image)
plt.figure(figsize=(20,20))
plt.imshow(image)
show_anns(masks)
plt.axis('off')
output_file = 'segmented_image.png'
plt.savefig(output_file)
plt.close()
return output_file
def show_anns(anns):
if len(anns) == 0:
return
sorted_anns = sorted(anns, key=(lambda x: x['area']), reverse=True)
ax = plt.gca()
ax.set_autoscale_on(False)
polygons = []
color = []
for ann in sorted_anns:
m = ann['segmentation']
img = np.ones((m.shape[0], m.shape[1], 3))
color_mask = np.random.random((1, 3)).tolist()[0]
for i in range(3):
img[:,:,i] = color_mask[i]
ax.imshow(np.dstack((img, m*0.35)))
# Example usage
# image_url = 'https://example.com/path/to/image.jpg'
# output_file = segment_image_from_url(image_url)
# print(f"Segmented image saved to {output_file}")