|
| 1 | +import json |
| 2 | +import time |
| 3 | +import requests |
| 4 | +import numpy as np |
| 5 | +from PIL import Image |
| 6 | +from io import BytesIO |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +from farmbot_sidecar_starter_pack import Farmbot |
| 9 | +from segment_anything import SamPredictor, SamAutomaticMaskGenerator, sam_model_registry |
| 10 | + |
| 11 | +# This script demonstrates how to use the Segment Anything Model (SAM) to segment images from |
| 12 | +# a FarmBot account. See https://github.com/facebookresearch/segment-anything for additional |
| 13 | +# installation requirements and to download a SAM model. |
| 14 | + |
| 15 | +# Add the SAM model you've downloaded to the current directory and list its path and type here. |
| 16 | +# The vit_l model (1.25GB) used in this example provides a good balance between speed and results. |
| 17 | +# On an M3 Mac, it takes about 80 seconds to segment a 640 x 480 image with the vit_l model. |
| 18 | +model_checkpoint = "sam_vit_l_0b3195.pth" |
| 19 | +model_type = "vit_l" |
| 20 | + |
| 21 | +# Initialize the FarmBot class |
| 22 | +bot = Farmbot() |
| 23 | +token = bot. get_token( "[email protected]", "password") |
| 24 | +bot.set_verbosity(0) |
| 25 | + |
| 26 | +# Get images from the FarmBot API |
| 27 | +images = bot.api_get("images") |
| 28 | +image_urls = [image["attachment_url"] for image in images] |
| 29 | + |
| 30 | +if bot.state.verbosity > 0: |
| 31 | + print(json.dumps(image_urls, indent=2)) |
| 32 | + |
| 33 | +if len(image_urls) == 0: |
| 34 | + print("No images found") |
| 35 | + exit(1) |
| 36 | + |
| 37 | +print(len(image_urls), "images found") |
| 38 | + |
| 39 | +# Download the first image |
| 40 | +url = image_urls[0] |
| 41 | +first_image = requests.get(url) |
| 42 | + |
| 43 | +if first_image.status_code == 200: |
| 44 | + print("Downloaded first image from URL:", url) |
| 45 | +else: |
| 46 | + print("Failed to download first image from URL:", url) |
| 47 | + exit(1) |
| 48 | + |
| 49 | +img = Image.open(BytesIO(first_image.content)) |
| 50 | +img_np = np.array(img) |
| 51 | + |
| 52 | +# Load the Segment Anything Model (SAM) |
| 53 | +sam = sam_model_registry[model_type](checkpoint=model_checkpoint) |
| 54 | +predictor = SamPredictor(sam) |
| 55 | + |
| 56 | +# Run segmentation |
| 57 | +start_time = time.time() |
| 58 | +print("Segmenting image... this may take a few minutes depending on the model and your computer's hardware.") |
| 59 | +mask_generator = SamAutomaticMaskGenerator(sam) |
| 60 | +masks = mask_generator.generate(img_np) |
| 61 | +print("Segmentation completed in {:.1f} seconds".format(time.time() - start_time)) |
| 62 | +print("Number of masks:", len(masks)) |
| 63 | + |
| 64 | +# Function to colorize and show the segmentation masks |
| 65 | +def show_masks(masks): |
| 66 | + if len(masks) == 0: |
| 67 | + return |
| 68 | + sorted_masks = sorted(masks, key=(lambda x: x['area']), reverse=True) |
| 69 | + ax = plt.gca() |
| 70 | + ax.set_autoscale_on(False) |
| 71 | + |
| 72 | + img = np.ones((sorted_masks[0]['segmentation'].shape[0], sorted_masks[0]['segmentation'].shape[1], 4)) |
| 73 | + img[:,:,3] = 0 |
| 74 | + for mask in sorted_masks: |
| 75 | + segmentation = mask['segmentation'] |
| 76 | + color_mask = np.concatenate([np.random.random(3), [0.6]]) |
| 77 | + img[segmentation] = color_mask |
| 78 | + ax.imshow(img) |
| 79 | + |
| 80 | +# Plot the image and all the segmentation masks |
| 81 | +plt.figure(figsize=(10, 10)) |
| 82 | +plt.imshow(img) |
| 83 | +show_masks(masks) |
| 84 | +plt.axis('off') |
| 85 | +plt.show() |
0 commit comments