Skip to content

Commit 1708692

Browse files
committed
segment_farmbot_images example
1 parent 3ea91d5 commit 1708692

6 files changed

+114
-0
lines changed

examples/README.md

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
These examples showcase various ways in which you might use the sidecar-starter-pack to augment and expand upon your FarmBot's capabilities.
2+
3+
# Copy Plants to New Account
4+
5+
[copy_plants_to_new_account.py](copy_plants_to_new_account.py)
6+
7+
This script will copy all plants from one FarmBot account to another. Note: It will not copy any associated water, height, or spread curves ids because they will not exist in the target account.
8+
9+
# Segment FarmBot Images
10+
11+
[segment_farmbot_images.py](segment_farmbot_images.py)
12+
13+
This script demonstrates how to use the Segment Anything Model (SAM) to segment images from a FarmBot account. See https://github.com/facebookresearch/segment-anything for additional installation requirements and to download a SAM model.
14+
15+
## Example 1: Segmenting an image of a plant
16+
17+
Input image:
18+
![input image](plant_segmentation_input.jpeg)
19+
20+
`vit_l` model output:
21+
![vit_l output](plant_segmentation_output.png)
22+
23+
## Example 2: Segmenting an image of the FarmBot toolbay and other objects
24+
25+
Input image:
26+
![input image](toolbay_segmentation_input.jpeg)
27+
28+
`vit_l` model output:
29+
![vit_l output](toolbay_segmentation_output.png)
306 KB
Loading
887 KB
Loading

examples/segment_farmbot_images.py

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
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()
299 KB
Loading
694 KB
Loading

0 commit comments

Comments
 (0)