### Install cli-anything-samgeo Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/README.md Install the command-line tool by navigating to the agent-harness directory and running the pip install command. This makes the `cli-anything-samgeo` command available in your system's PATH. ```bash cd agent-harness pip install -e . ``` -------------------------------- ### Example: GeoJSON Mask Polygons Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Use this example to get segmentation masks as GeoJSON polygons. Ensure the image file and prompt are correctly provided. ```bash curl -X POST http://localhost:8000/segment/text \ -F "file=@image.tif" \ -F "prompt=building" \ -F "output_format=geojson" ``` -------------------------------- ### Install SamGeo with Pixi Source: https://github.com/opengeos/segment-geospatial/blob/main/README.md Instructions for installing SamGeo using pixi, a recommended package and environment manager. This includes creating a new pixi project, editing the configuration, and installing dependencies. ```bash # Install pixi (Linux/macOS) curl -fsSL https://pixi.sh/install.sh | sh # Or on Windows (PowerShell) powershell -ExecutionPolicy Bypass -c "irm -useb https://pixi.sh/install.ps1 | iex" # Create a new pixi project pixi init geo cd geo # Edit pixi.toml with your configuration (see docs for GPU/CPU examples) # Then install pixi install # Start Jupyter Lab pixi run jupyter lab ``` -------------------------------- ### Install segment-geospatial Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/skills/SKILL.md Install the segment-geospatial library with all extras and the agent-harness locally. ```bash pip install segment-geospatial[all] cd agent-harness && pip install -e . ``` -------------------------------- ### Set up virtual environment and install dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/contributing.md Set up a virtual environment using virtualenvwrapper and install the project in development mode. ```shell $ mkvirtualenv segment-geospatial $ cd segment-geospatial/ $ python setup.py develop ``` -------------------------------- ### Install Pixi environment Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Installs all dependencies defined in the pixi.toml file for the current project. ```bash pixi install ``` -------------------------------- ### Claude Code Example: Download Tiles and Get Info Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/README.md An example of Claude Code using cli-anything-samgeo to download OpenStreetMap tiles for a specified bounding box and then retrieve information about the downloaded image. This demonstrates chaining commands for data acquisition and inspection. ```bash cli-anything-samgeo --json data download-tiles -o portland.tif -b "-122.68,45.51,-122.66,45.53" -z 17 cli-anything-samgeo --json data info portland.tif ``` -------------------------------- ### Install Required Packages Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/image_captioning.ipynb Install the necessary packages for geospatial analysis and image captioning. Uncomment the line to run the installation. ```python # %pip install "segment-geospatial[samgeo3]" ``` -------------------------------- ### Install Segment-Geospatial Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_video.ipynb Install the required segment-geospatial library. Uncomment and run this cell to install. ```python # %pip install -U segment-geospatial ``` -------------------------------- ### Install necessary libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/AIforGood_2025.ipynb Installs the segment-geospatial and groundingdino-py libraries. Run this command in your environment before proceeding. ```python %pip install segment-geospatial groundingdino-py ``` -------------------------------- ### Install Pixi on Windows Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Installs Pixi using a PowerShell command. Close and re-open PowerShell after installation. ```powershell powershell -ExecutionPolicy Bypass -c "irm -useb https://pixi.sh/install.ps1 | iex" ``` ```powershell pixi --version ``` -------------------------------- ### Install QGIS Plugin using install_plugin.py Source: https://github.com/opengeos/segment-geospatial/blob/main/qgis-samgeo-plugin/README.md Steps to clone the plugin repository, activate the conda environment, and install the plugin using the provided Python script. ```bash # Clone the repository git clone https://github.com/opengeos/qgis-samgeo-plugin.git cd qgis-samgeo-plugin conda activate geo # Install (Linux/macOS) python install_plugin.py ``` -------------------------------- ### Manual Plugin Installation via Symlink Source: https://github.com/opengeos/segment-geospatial/blob/main/qgis-samgeo-plugin/README.md Instructions for manually installing the plugin by creating a symbolic link to the plugin directory within the QGIS plugins folder. ```bash ln -s /path/to/qgis-samgeo-plugin ~/.local/share/QGIS/QGIS3/profiles/default/python/plugins/samgeo_plugin ``` -------------------------------- ### Install QGIS Plugin using install_plugin.sh Source: https://github.com/opengeos/segment-geospatial/blob/main/qgis-samgeo-plugin/README.md Alternative method to install the plugin using a shell script after cloning the repository and activating the conda environment. ```bash # Clone the repository git clone https://github.com/opengeos/qgis-samgeo-plugin.git cd qgis-samgeo-plugin conda activate geo # Or use the shell script chmod +x install_plugin.sh ./install_plugin.sh ``` -------------------------------- ### Install API Dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Install the necessary dependencies for the API with the 'api' extra. To include a specific SAM model backend, combine extras. ```bash pip install "segment-geospatial[api]" ``` ```bash pip install "segment-geospatial[api,samgeo3]" ``` -------------------------------- ### Start the API Server with Uvicorn Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Alternatively, start the segment-geospatial API server directly using 'uvicorn'. ```bash uvicorn samgeo.api:app --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Install necessary libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Installs the leafmap library with raster support, segment-geospatial, and d2spy. Also installs a specific version of numpy. ```python # %pip install -U "leafmap[raster]" segment-geospatial d2spy ``` ```python # %pip install numpy==1.26.4 ``` -------------------------------- ### Download and display an example image Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_point_prompts.ipynb Download a sample image from a URL and display it using the show_image function. This prepares the image for segmentation tasks. ```python url = "https://raw.githubusercontent.com/facebookresearch/sam3/refs/heads/main/assets/images/truck.jpg" image_path = download_file(url) ``` ```python show_image(image_path, axis="on") ``` -------------------------------- ### Install Dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_automatic.ipynb Install the required libraries for segment-geospatial and leafmap. Ensure you are using a GPU runtime for optimal performance. ```python # %pip install -U segment-geospatial leafmap ``` -------------------------------- ### Install Required Packages Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/detectree2.ipynb Install PyTorch, Detectron2, detectree2, and segment-geospatial. Adjust PyTorch installation for your CUDA version. ```python # Install PyTorch (adjust for your CUDA version) # %pip install torch torchvision # Install Detectron2 # %pip install 'git+https://github.com/facebookresearch/detectron2.git' # Install detectree2 # %pip install git+https://github.com/PatBall1/detectree2.git # Install segment-geospatial # %pip install segment-geospatial ``` -------------------------------- ### Verify PyTorch and CUDA installation Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Runs a Python script using Pixi to check PyTorch version, CUDA availability, and GPU name. Essential for confirming GPU setup. ```bash pixi run python -c "import torch; print('PyTorch:', torch.__version__); print('CUDA available:', torch.cuda.is_available()); print('GPU:', (torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'None'))" ``` -------------------------------- ### Install Dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_image_segmentation_jpg.ipynb Installs the necessary libraries for SAM3 image segmentation. Ensure you have the correct version of transformers. ```python # %pip install "segment-geospatial[samgeo3]" ``` ```python # %pip install transformers==5.0.0rc0 ``` -------------------------------- ### Install QGIS and SamGeo with Conda Source: https://github.com/opengeos/segment-geospatial/blob/main/qgis-samgeo-plugin/README.md Recommended installation procedure using conda to create a dedicated environment for QGIS and the segment-geospatial package. ```bash conda create -n geo python=3.12 conda activate geo conda install -c conda-forge qgis segment-geospatial ``` -------------------------------- ### Example: JSON Output (Pixel-Coordinate Bounding Boxes) Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md This example demonstrates how to obtain segmentation results as JSON, with bounding boxes defined by pixel coordinates. Suitable for direct image analysis. ```bash curl -X POST http://localhost:8000/segment/text \ -F "file=@image.jpg" \ -F "prompt=building" \ -F "output_format=json" ``` -------------------------------- ### Install segment-geospatial Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/box_prompts.ipynb Install the required library for geospatial segmentation. This should be run in a GPU-enabled environment. ```python # %pip install segment-geospatial ``` -------------------------------- ### Install Pixi on Linux/macOS Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Installs Pixi using a curl command. Close and re-open your terminal or reload your shell after installation. ```bash curl -fsSL https://pixi.sh/install.sh | sh ``` ```bash pixi --version ``` -------------------------------- ### Start the API Server Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Start the segment-geospatial API server using the 'samgeo-api' command. Options are available for custom host/port, preloading models, and auto-reloading during development. ```bash samgeo-api ``` ```bash samgeo-api --host 0.0.0.0 --port 8000 # Custom host/port ``` ```bash samgeo-api --preload sam2:sam2-hiera-large # Preload a model at startup ``` ```bash samgeo-api --reload # Auto-reload for development ``` -------------------------------- ### Install Dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/fast_sam.ipynb Install the necessary Python packages for segmenting geospatial data with FastSAM. Uncomment and run this cell to begin. ```python # %pip install segment-geospatial segment-anything-fast ``` -------------------------------- ### Install SAM 3 on Windows with Conda and Pip Source: https://github.com/opengeos/segment-geospatial/blob/main/README.md Specific commands for installing SAM 3 on Windows, including creating a Python 3.12 environment, installing PyTorch with CUDA support, segment-geospatial, and other necessary tools. ```bash conda create -n geo python=3.12 conda activate geo conda install pytorch torchvision pytorch-cuda=12.1 -c pytorch -c nvidia pip install "segment-geospatial[samgeo3]" pip install triton-windows ipykernel jupyterlab ``` -------------------------------- ### Install Segment Geospatial from PyPI Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Use this command to install the library using pip. This is the standard method for most Python projects. ```bash pip install segment-geospatial ``` -------------------------------- ### Install SamGeo Dependencies with Pip Source: https://github.com/opengeos/segment-geospatial/blob/main/qgis-samgeo-plugin/README.md Installs all necessary SamGeo dependencies, including those only available on PyPI, using pip. ```bash pip install -U "segment-geospatial[samgeo3]" ``` -------------------------------- ### Start QGIS with SamGeo Plugin Environment Source: https://github.com/opengeos/segment-geospatial/blob/main/qgis-samgeo-plugin/README.md Commands to activate the conda environment and launch QGIS, making the SamGeo plugin available. ```bash conda activate geo qgis ``` -------------------------------- ### Start Jupyter Lab Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Launches Jupyter Lab using Pixi, providing an environment to use segment-geospatial. ```bash pixi run jupyter lab ``` -------------------------------- ### Example: Detections Output (Geographic-Coordinate Bounding Boxes) Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Use this example to retrieve segmentation results with bounding boxes in geographic coordinates. This format is useful for GIS applications. ```bash curl -X POST http://localhost:8000/segment/text \ -F "file=@image.tif" \ -F "prompt=building" \ -F "output_format=detections" ``` -------------------------------- ### Run Segmentation with Box Prompts (All Similar Objects) Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md This example demonstrates segmenting an image using bounding box coordinates. For SAM3, this will find all similar objects within the image, not just those inside the box. Specify the image file and bounding box coordinates. ```bash curl -X POST http://localhost:8000/segment/predict \ -F "file=@image.tif" \ -F "boxes=[[10, 20, 300, 400]]" \ -F "output_format=geojson" ``` -------------------------------- ### Install segment-geospatial with PyPI Source: https://github.com/opengeos/segment-geospatial/blob/main/README.md Install segment-geospatial with specific dependencies for SAMGeo 3. Other options include [samgeo], [samgeo2], [fast], [hq], [text], [fer], and [api]. ```bash pip install "segment-geospatial[samgeo3]" # Or any other choice of the above ``` -------------------------------- ### Import required libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/AIforGood_2025.ipynb Imports leafmap for interactive mapping and SamGeo2 for segmentation. Ensure these libraries are installed. ```python import leafmap from samgeo import SamGeo2, regularize ``` -------------------------------- ### Install Segment Geospatial from GitHub Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Install the development version directly from the GitHub repository using pip. This is useful for accessing the latest features or contributing to the project. ```bash pip install git+https://github.com/opengeos/segment-geospatial ``` -------------------------------- ### Generate Segmentation Mask and Convert to Vector Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/usage.md This example demonstrates generating a segmentation mask from a satellite image and converting it to a GeoPackage vector file. Ensure you have the SAM checkpoint file downloaded. ```python import os import torch from samgeo import SamGeo from samgeo.common import tms_to_geotiff bbox = [-95.3704, 29.6762, -95.368, 29.6775] image = 'satellite.tif' tms_to_geotiff(output=image, bbox=bbox, zoom=20, source='Satellite') out_dir = os.path.join(os.path.expanduser('~'), 'Downloads') checkpoint = os.path.join(out_dir, 'sam_vit_h_4b8939.pth') device = 'cuda' if torch.cuda.is_available() else 'cpu' sam = SamGeo( checkpoint=checkpoint, model_type='vit_h', device=device, erosion_kernel=(3, 3), mask_multiplier=255, sam_kwargs=None, ) mask = 'segment.tif' sam.generate(image, mask) vector = 'segment.gpkg' sam.tiff_to_gpkg(mask, vector, simplify_tolerance=None) ``` -------------------------------- ### Install Dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_text_prompts.ipynb Installs the necessary Python packages for geospatial image segmentation using SAM 2 and related libraries. Ensure you have a compatible environment. ```python # %pip install segment-geospatial groundingdino-py leafmap localtileserver ``` -------------------------------- ### Install optional Conda dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/README.md Install optional dependencies like groundingdino-py and segment-anything-fast for enhanced functionality within your conda environment. ```bash conda install -c conda-forge groundingdino-py segment-anything-fast ``` -------------------------------- ### Import Segment Geospatial Library Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/usage.md Import the necessary library to start using segment-geospatial. ```python import samgeo ``` -------------------------------- ### Get Bounding Boxes in Pixel Coordinates Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md This example demonstrates how to get bounding boxes in pixel coordinates for non-georeferenced images. It sends a JPEG image and a prompt to the API, expecting a JSON output containing detection details. ```python # Get bounding boxes in pixel coordinates (suitable for non-georeferenced images) with open("image.jpg", "rb") as f: response = requests.post( url, files={"file": ("image.jpg", f, "image/jpeg")}, data={"prompt": "car", "output_format": "json"}, ) result = response.json() for det in result["detections"]: print(f"Object {det['id']}: bbox={det['bbox']}, score={det['score']:.3f}") ``` -------------------------------- ### Import Libraries and Download Video Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_masks.ipynb Import necessary libraries and download a sample video file for demonstration. ```python import os import numpy as np from samgeo import SamGeo3Video, download_file ``` ```python url = "https://github.com/opengeos/datasets/releases/download/videos/cars.mp4" video_path = download_file(url) ``` -------------------------------- ### List Available Models Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Retrieve a list of available model versions and IDs, along with which models are currently loaded in memory, using the GET /models endpoint. ```bash curl http://localhost:8000/models ``` -------------------------------- ### Claude Code Example: Segment Buildings and Export Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/README.md An example of how Claude Code might execute a sequence of cli-anything-samgeo commands to segment buildings and export the results as a GeoPackage. Note the use of `--json` for machine-readable output and the correct order of flags. ```bash cli-anything-samgeo --json project new -n buildings -o project.json -s satellite.tif -t sam2 cli-anything-samgeo --json --project project.json segment automatic -o masks.tif cli-anything-samgeo --json vector convert masks.tif buildings.gpkg ``` -------------------------------- ### Install Optional Conda Dependencies Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Install optional dependencies like groundingdino-py and segment-anything-fast using mamba. These are not included in the default installation. ```bash mamba install -c conda-forge groundingdino-py segment-anything-fast ``` -------------------------------- ### Initialize ImageCaptioner Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/image_captioning.ipynb Create an instance of the ImageCaptioner. Customize BLIP and spaCy models, or specify the device for inference. ```python captioner = ImageCaptioner( blip_model_name="Salesforce/blip-image-captioning-base", spacy_model_name="en_core_web_sm", ) ``` -------------------------------- ### Low-level mask prediction with box prompt Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_point_prompts.ipynb Perform instance segmentation using a bounding box prompt via the `predict_inst` method. This example demonstrates generating a single mask for the specified box. ```python # Box prompt with Python list masks, scores, logits = sam.predict_inst( box=[425, 600, 700, 875], multimask_output=False, ) sam.show_inst_masks(masks, scores, box_coords=[425, 600, 700, 875]) ``` -------------------------------- ### Create a new Pixi project Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Initializes a new Pixi project named 'geo' and navigates into its directory. ```bash pixi init geo cd geo ``` -------------------------------- ### Set Up Model Checkpoint and Output Directory Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/satellite-predictor.ipynb Specify the output directory for results and the local path to the SAM model checkpoint file. ```python out_dir = os.path.join(os.path.expanduser("~"), "Downloads") checkpoint = os.path.join(out_dir, "sam_vit_h_4b8939.pth") ``` -------------------------------- ### Create a New Project Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/README.md Initialize a new segmentation project. Specify a project name, output file for project configuration, and the input satellite image. ```bash cli-anything-samgeo project new -n my-seg -o project.json -s image.tif ``` -------------------------------- ### Run unit tests Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/contributing.md Execute all unit tests for the project by navigating to the root directory and running the discover command. ```bash python -m unittest discover tests/ ``` -------------------------------- ### Install segment-geospatial with conda Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/index.md Installs segment-geospatial and its dependencies from the conda-forge channel into the active conda environment. ```bash conda install -c conda-forge segment-geospatial ``` -------------------------------- ### Install Segment Geospatial with Conda Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Recommended for creating a dedicated environment. This installs segment-geospatial and its dependencies using conda and mamba. ```bash conda create -n geo python conda activate geo conda install -c conda-forge mamba mamba install -c conda-forge segment-geospatial ``` -------------------------------- ### Visualize Sample Image Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/detectree2.ipynb Create a leafmap interactive map and add the downloaded sample tree image as a raster layer. ```python m = leafmap.Map() m.add_raster(image_path, layer_name="Tree Image") m ``` -------------------------------- ### Install segment-geospatial with Conda (GPU PyTorch) Source: https://github.com/opengeos/segment-geospatial/blob/main/README.md If your system has a GPU, use this command to force the installation of the GPU version of PyTorch along with segment-geospatial. ```bash conda install -c conda-forge segment-geospatial "pytorch=*=cuda*" ``` -------------------------------- ### Install segment-geospatial with Conda Source: https://github.com/opengeos/segment-geospatial/blob/main/README.md Create a new conda environment named 'geo', activate it, and install segment-geospatial from conda-forge. This is recommended for managing dependencies. ```bash conda create -n geo python conda activate geo conda install -c conda-forge segment-geospatial ``` -------------------------------- ### Enter Interactive REPL Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/README.md Run the cli-anything-samgeo command without any arguments to enter an interactive Read-Eval-Print Loop (REPL) for command exploration. ```bash cli-anything-samgeo ``` -------------------------------- ### Initialize SamGeo Model Source: https://github.com/opengeos/segment-geospatial/blob/main/qgis-samgeo-plugin/README.md Initializes the SamGeo model with specified backend and configuration. Use 'cuda' for GPU acceleration if available. ```python from samgeo import SamGeo3 # Initialize the model sam = SamGeo3( backend="meta", enable_inst_interactivity=True, confidence_threshold=0.5, ) ``` -------------------------------- ### Create and activate conda environment Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/index.md Recommended for installing segment-geospatial with conda. This creates a new environment named 'geo', installs Python, and then activates the environment. ```bash conda create -n geo python ``` ```bash conda activate geo ``` -------------------------------- ### Download Sample Data Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_video.ipynb Download sample remote sensing data in a zip archive. Ensure all images have the same width and height. ```python url = "https://github.com/opengeos/datasets/releases/download/raster/landsat_ts.zip" leafmap.download_file(url) ``` -------------------------------- ### Initialize Leafmap and Add Raster Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_image_segmentation.ipynb Initialize a leafmap interactive map and add the downloaded satellite image as a raster layer for visualization. ```python m = leafmap.Map() m.add_raster(image_path, layer_name="Satellite image") m ``` -------------------------------- ### Initialize Video Tracker Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_prompts.ipynb Initialize the tracker for the video. This prepares the SamGeo3Video object for point-prompted segmentation and propagation. ```python sam.init_tracker() ``` -------------------------------- ### List Export Formats Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/skills/SKILL.md List all available export formats supported by the tool. ```bash cli-anything-samgeo export formats ``` -------------------------------- ### Download Sample Data Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_tiled_segmentation.ipynb Downloads a sample satellite image (GeoTIFF) for demonstration purposes. Replace `image_path` with your own large GeoTIFF. ```python # Download a sample satellite image url = "https://huggingface.co/datasets/giswqs/geospatial/resolve/main/naip/naip_water_train.tif" image_path = "naip_water_train.tif" if not os.path.exists(image_path): common.download_file(url, image_path) ``` -------------------------------- ### Data Information Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/skills/SKILL.md Get information about a raster data file. ```bash cli-anything-samgeo data info RASTER_PATH ``` -------------------------------- ### Download SAM 3.1 model Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Downloads the SAM 3.1 model from Hugging Face Hub using Pixi. Requires prior authentication. ```bash pixi run hf download facebook/sam3.1 ``` -------------------------------- ### Prepare Training Data Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/detectree2.ipynb Prepare image tiles and corresponding manual crown polygons for training a custom detectree2 model. Includes splitting into training and testing sets. ```python # Prepare training and test data # train_dir, test_dir = prepare_training_data( # image_path="path/to/orthomosaic.tif", # crowns_path="path/to/manual_crowns.gpkg", # output_dir="./training_data", # tile_width=40, # tile_height=40, # buffer=30, # threshold=0.6, # Minimum crown coverage per tile # test_fraction=0.15, # Fraction for testing # ) ``` -------------------------------- ### Get Coordinate Reference System (CRS) Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Extract and print the Coordinate Reference System (CRS) of the raster data. ```python crs = data.rio.crs.to_string() print(crs) ``` -------------------------------- ### Initialize SamGeo3 Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_tiled_segmentation.ipynb Initializes the SamGeo3 object with the 'meta' backend for processing. ```python sam = SamGeo3(backend="meta") ``` -------------------------------- ### Extract Features from Caption Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/image_captioning.ipynb Use the extract_features() method to get noun features from an existing caption, with options for filtering. ```python # Extract features from an existing caption features = captioner.extract_features(caption) print(f"All Features: {features}") aerial_features = captioner.extract_features(caption, include_features="default") print(f"Aerial Features: {aerial_features}") ``` -------------------------------- ### Initialize LangSAM Model Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_text_prompts.ipynb Initializes the `LangSAM` class with the 'sam2-hiera-large' model. This step may take a few minutes as it downloads model weights. ```python sam = LangSAM(model_type="sam2-hiera-large") ``` -------------------------------- ### Get D2S project boundary Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Retrieves the project boundary as a GeoJSON formatted Python dictionary for the selected D2S project. ```python # Get project boundary as Python dictionary in GeoJSON structure project_boundary = project.get_project_boundary() project_boundary ``` -------------------------------- ### Import necessary libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/box_prompts.ipynb Import the leafmap library for interactive mapping, tms_to_geotiff for downloading imagery, and SamGeo for segmentation. ```python import leafmap from samgeo.common import tms_to_geotiff from samgeo import SamGeo ``` -------------------------------- ### Initialize FastSAM Model Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/fast_sam.ipynb Initialize the SamGeo class with a specified FastSAM model. This step may take a few minutes as it downloads model weights. ```python from samgeo.fast_sam import SamGeo sam = SamGeo(model="FastSAM-x.pt") ``` -------------------------------- ### Define Text Prompt Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_text_prompts.ipynb Sets the text prompt to guide the segmentation process. The model will identify objects corresponding to this prompt. ```python text_prompt = "tree" ``` -------------------------------- ### Run segment-geospatial with Docker Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Use this command to start a Docker container for segment-geospatial. It maps port 8888 for Jupyter Notebook access. ```bash docker run -it -p 8888:8888 giswqs/segment-geospatial:latest ``` -------------------------------- ### CLI Syntax Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/skills/SKILL.md Basic syntax for the cli-anything-samgeo command, including global flags for JSON output and project paths. ```bash cli-anything-samgeo [--json] [--project PATH] COMMAND [ARGS...] ``` -------------------------------- ### Get data products from a flight Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Retrieves a collection of data products associated with a specific flight. Iterates through and prints each data product. ```python # Get list of data products from a flight data_products = flight.get_data_products() for data_product in data_products: print(data_product) ``` -------------------------------- ### Download Sample Image Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/detectree2.ipynb Download a sample tree image from a specified URL for testing purposes. ```python image_url = ( "https://github.com/opengeos/datasets/releases/download/samgeo/tree_image.tif" ) image_path = leafmap.download_file(image_url) ``` -------------------------------- ### Initialize SamGeo2 Predictor for Video Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_video.ipynb Initialize the SamGeo2 predictor with a specific model ID and enable video processing. Use a GPU runtime for better performance. ```python predictor = SamGeo2( model_id="sam2-hiera-large", video=True, ) ``` -------------------------------- ### Define Area of Interest Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/satellite-predictor.ipynb Get the bounding box for the area of interest from user interaction on the map, or use a default bounding box. ```python if m.user_roi_bounds() is not None: bbox = m.user_roi_bounds() else: bbox = [-123.0127, 44.9957, -122.9874, 45.0045] ``` -------------------------------- ### Health Check Endpoint Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Check the server status and version using the GET /health endpoint. This is a basic check to ensure the API is running. ```bash curl http://localhost:8000/health ``` ```json {"status": "ok", "version": "1.2.3"} ``` -------------------------------- ### Run Segmentation with Point Prompts Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Use this endpoint to segment an image using point coordinates and labels. Ensure the image file is uploaded correctly and specify the desired output format. ```bash curl -X POST http://localhost:8000/segment/predict \ -F "file=@image.tif" \ -F "point_coords=[[100, 200]]" \ -F "point_labels=[1]" \ -F "output_format=geojson" ``` -------------------------------- ### Get CHM statistics Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Calculates and returns statistics for a Cloud Optimized GeoTIFF (COG) layer, such as min, max, mean, and standard deviation. ```python leafmap.cog_stats(chm_url_202206) ``` -------------------------------- ### Get DSM statistics Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Calculates and returns statistics for a Cloud Optimized GeoTIFF (COG) layer, such as min, max, mean, and standard deviation. ```python leafmap.cog_stats(dsm_url_202206) ``` -------------------------------- ### Get Data Information with JSON Output Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/README.md Obtain detailed information about a geospatial data file in JSON format. This is useful for programmatic access to metadata. ```bash cli-anything-samgeo --json data info image.tif ``` -------------------------------- ### Download and Load Video Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_segmentation.ipynb Download a sample MP4 video file from a URL and set it as the input for the SamGeo3Video predictor. ```python url = "https://github.com/opengeos/datasets/releases/download/videos/cars.mp4" video_path = download_file(url) ``` ```python sam.set_video(video_path) ``` -------------------------------- ### Display Map for Interactive Prompting Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/AIforGood_2025.ipynb Displays the leafmap, allowing users to interactively draw bounding boxes or points on the map to guide the segmentation process. ```python m ``` -------------------------------- ### Filter data products by data type Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Filters a DataProductCollection to include only products of a specified data type. Example shows filtering for 'ortho' data products. ```python # Example of creating new collection of data products with the "ortho" data type ortho_data_products = data_products.filter_by_data_type("ortho") print(ortho_data_products) ``` -------------------------------- ### Initialize SamGeo Model Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/satellite.ipynb Initialize the SamGeo model with a specified model type ('vit_h') and checkpoint file. The checkpoint file should be available in the same directory or a specified path. ```python sam = SamGeo( model_type="vit_h", checkpoint="sam_vit_h_4b8939.pth", sam_kwargs=None, ) ``` -------------------------------- ### Download and Load Video Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_object_tracking.ipynb Download a sample video file from a URL and set it for processing using the SamGeo3Video object. Supports MP4, JPEG frame directories, and GeoTIFF directories. ```python url = "https://huggingface.co/datasets/giswqs/geospatial/resolve/main/basketball.mp4" video_path = download_file(url) ``` ```python sam.set_video(video_path) ``` ```python sam.show_video(video_path) ``` -------------------------------- ### Define Area of Interest (ROI) Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_automatic.ipynb Get the bounding box for the region of interest from user interaction on the map, or use a default bounding box if no ROI is drawn. ```python if m.user_roi_bounds() is not None: bbox = m.user_roi_bounds() else: bbox = [-95.3704, 29.6762, -95.368, 29.6775] ``` -------------------------------- ### Import Libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/detectree2.ipynb Import necessary modules from leafmap and samgeo.detectree2 for tree crown delineation. ```python import leafmap from samgeo.detectree2 import ( TreeCrownDelineator, list_pretrained_models, ) ``` -------------------------------- ### Download SAM 3 model Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Downloads the SAM 3 model from Hugging Face Hub using Pixi. Requires prior authentication. ```bash pixi run hf download facebook/sam3 ``` -------------------------------- ### Define Bounding Box for Image Download Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/fast_sam.ipynb Get the user-defined region of interest (ROI) bounds from the map. If no ROI is drawn, a default bounding box is used. ```python bbox = m.user_roi_bounds() if bbox is None: bbox = [-51.2565, -22.1777, -51.2512, -22.175] ``` -------------------------------- ### Define text prompt Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/text_swimming_pools.ipynb Sets the text prompt to be used for segmenting specific objects in the image. This prompt guides the model to identify features matching the description. ```python text_prompt = "swimming pool" ``` -------------------------------- ### Download Vector File for Box Prompts Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_box_prompts.ipynb Download a sample GeoJSON file containing bounding boxes from a GitHub repository. This file will be used as input for segmentation. ```python url = "https://github.com/opengeos/datasets/releases/download/samgeo/building_bboxes.geojson" geojson = "building_bboxes.geojson" leafmap.download_file(url, geojson) ``` -------------------------------- ### Run segment-geospatial with GPU support via Docker Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md This command starts a Docker container for segment-geospatial with GPU acceleration enabled. It maps port 8888 for Jupyter Notebook access. ```bash docker run -it -p 8888:8888 --gpus=all giswqs/segment-geospatial:latest ``` -------------------------------- ### Initialize SAM Predictor and Perform Segmentation Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/satellite-predictor.ipynb Load the SAM model, initialize the SamGeoPredictor, set the input image, and run the prediction using the defined clipping box. ```python import cv2 img_arr = cv2.imread(image) model_type = "vit_h" sam = sam_model_registry[model_type](checkpoint=checkpoint) predictor = SamGeoPredictor(sam) predictor.set_image(img_arr) masks, _, _ = predictor.predict(src_fp=image, geo_box=clip_box) ``` -------------------------------- ### Download Sample Image Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/fast_sam.ipynb Download a GeoTIFF image for the specified bounding box using tile map services. The image is saved as 'Image.tif'. ```python image = "Image.tif" tms_to_geotiff(output=image, bbox=bbox, zoom=19, source="Satellite", overwrite=True) ``` -------------------------------- ### Add Multiple External Masks at Once Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_masks.ipynb Add multiple external masks simultaneously using the `add_masks_prompt()` method. Object IDs are automatically assigned starting from 100 to prevent conflicts. ```python # Add all masks at once (IDs will be auto-assigned starting from 100) sam.add_masks_prompt(external_masks) ``` -------------------------------- ### Download Sample Video Data Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/AIforGood_2025.ipynb Download a sample MP4 video file for demonstration purposes. This video will be used for object segmentation. ```python url = "https://github.com/opengeos/datasets/releases/download/videos/cars.mp4" ``` -------------------------------- ### Define Bounding Boxes for Segmentation Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_box_prompts.ipynb Define bounding boxes either by user interaction on the map or by using default coordinates. These boxes guide the segmentation process to specific features. ```python if m.user_rois is not None: boxes = m.user_rois else: boxes = [ [-117.5995, 47.6518, -117.5988, 47.652], [-117.5987, 47.6518, -117.5979, 47.652], ] ``` -------------------------------- ### JSON Output Structure for Detections Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md This is an example of the JSON output structure when requesting detections. It includes image dimensions, the number of detections, and a list of detected objects with their bounding boxes and IDs. ```json { "image_width": 2647, "image_height": 1464, "num_detections": 12, "detections": [ {"id": 1, "value": 1, "bbox": [50, 80, 200, 250], "width": 150, "height": 170}, {"id": 2, "value": 2, "bbox": [310, 45, 480, 210], "width": 170, "height": 165} ] } ``` -------------------------------- ### Initialize SAMGeo with custom options Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/automatic_mask_generator.ipynb Re-initialize the SamGeo class, this time passing the custom `sam_kwargs` dictionary to fine-tune the mask generation process. ```python sam = SamGeo( model_type="vit_h", sam_kwargs=sam_kwargs, ) ``` -------------------------------- ### Initialize SAM3 Model Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_batch_segmentation.ipynb Initialize the SamGeo3 model. You can choose the backend ('meta' or 'transformers') and specify device and checkpoint path if needed. `load_from_HF=True` is used for Hugging Face models. ```python sam3 = SamGeo3(backend="meta", device=None, checkpoint_path=None, load_from_HF=True) ``` -------------------------------- ### Get GeoJSON Mask Polygons Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/api.md Use this snippet to send a GeoTIFF image to the API and receive GeoJSON mask polygons for a given prompt. Ensure the image file is opened in binary read mode. ```python import requests url = "http://localhost:8000/segment/text" # Get GeoJSON mask polygons with open("image.tif", "rb") as f: response = requests.post( url, files={"file": ("image.tif", f, "image/tiff")}, data={"prompt": "building", "output_format": "geojson"}, ) geojson = response.json() print(f"Found {len(geojson['features'])} features") ``` -------------------------------- ### Download Sample Image Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/tree_mapping.ipynb Download a satellite image for a specified bounding box. If no bounding box is drawn by the user, a default bounding box is used. The image is saved as 'Image.tif'. ```python bbox = m.user_roi_bounds() if bbox is None: bbox = [-51.2565, -22.1777, -51.2512, -22.175] image = "Image.tif" leafmap.map_tiles_to_geotiff( output=image, bbox=bbox, zoom=19, source="Satellite", overwrite=True ) ``` -------------------------------- ### Download sample image using bounding box Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/box_prompts.ipynb Define a bounding box and download a GeoTIFF image from satellite tiles. If no bounding box is drawn by the user, a default bounding box is used. ```python bbox = m.user_roi_bounds() if bbox is None: bbox = [-51.2565, -22.1777, -51.2512, -22.175] image = "Image.tif" tms_to_geotiff(output=image, bbox=bbox, zoom=19, source="Satellite", overwrite=True) ``` -------------------------------- ### Segment Image Using GeoJSON Bounding Boxes Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_box_prompts.ipynb Perform segmentation using bounding boxes provided in a GeoJSON file. The `multimask_output` parameter is set to `False` to get a single mask per box. ```python output_masks = "building_masks.tif" sam.predict( boxes=geojson, point_crs="EPSG:4326", output=output_masks, dtype="uint8", multimask_output=False, ) ``` -------------------------------- ### Add External Masks Individually Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_masks.ipynb Add extracted external masks to the tracker one by one using `add_mask_prompt()`. Assign new object IDs (starting from 100) to avoid conflicts with any masks generated by text prompts. ```python # Add masks one by one using add_mask_prompt() # Use obj_ids starting from 100 to avoid conflicts with detected objects for i, mask in enumerate(external_masks): sam.add_mask_prompt(mask, obj_id=100 + i, frame_idx=0) ``` -------------------------------- ### Get user region of interest or default bounding box Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/automatic_mask_generator.ipynb Retrieve the bounding box coordinates defined by the user on the map, or use a default bounding box if no user input is provided. This defines the area for image download. ```python if m.user_roi_bounds() is not None: bbox = m.user_roi_bounds() else: bbox = [-122.2659, 37.8682, -122.2521, 37.8741] ``` -------------------------------- ### Download Sample Image Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_automatic.ipynb Download a satellite image tile for the specified bounding box and save it as a GeoTIFF file. This function allows for overwriting existing files. ```python image = "satellite.tif" leafmap.map_tiles_to_geotiff( output=image, bbox=bbox, zoom=20, source="Satellite", overwrite=True ) ``` -------------------------------- ### Add Point Prompts for Segmentation Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_prompts.ipynb Add point prompts to the first frame (frame_idx=0) to guide the segmentation. Positive prompts (label=1) indicate foreground, and negative prompts (label=0) indicate background. Each object is assigned a unique obj_id. ```python sam.add_point_prompts([[300, 200]], [1], obj_id=1, frame_idx=0) ``` ```python sam.add_point_prompts([[420, 200]], [1], obj_id=2, frame_idx=0) ``` -------------------------------- ### Download Sample Data Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/maxar_open_data.ipynb Download a sample satellite image of Derna, Libya from a provided URL. This image will be used for segmentation. ```python url = "https://github.com/opengeos/datasets/releases/download/raster/Derna_sample.tif" leafmap.download_file(url, output="image.tif") ``` -------------------------------- ### Refine Segmentation with Multiple Points Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_segmentation.ipynb Use a combination of positive and negative point prompts to precisely refine segmentation masks. This example refines object 2 to segment only the shirt, excluding the pants, by providing specific point coordinates and labels. ```python # Refine to segment only the shirt (not pants) sam.add_point_prompts( points=[[335, 195], [335, 220]], # detect windshield, not the car labels=[1, 0], # positive, negative obj_id=2, frame_idx=0, ) sam.propagate() sam.show_frames(frame_stride=20, ncols=3) ``` -------------------------------- ### Import Libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_automated_segmentation.ipynb Imports core libraries for leafmap visualization, SAM 3, and image captioning. These are essential for the subsequent steps in the notebook. ```python import leafmap from samgeo import SamGeo3, download_file from samgeo.caption import ImageCaptioner ``` -------------------------------- ### Add Point Prompts for Object Refinement Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_segmentation.ipynb Refine segmentation by adding point prompts. Use positive points (label 1) to include areas and negative points (label 0) to exclude them. This example adds back object 2 using a positive point click on the first frame. ```python # Add back object 2 with a positive point click sam.add_point_prompts( points=[[335, 203]], # [x, y] coordinates labels=[1], # 1=positive, 0=negative obj_id=2, frame_idx=0, ) sam.propagate() sam.show_frame(0) ``` -------------------------------- ### Import Libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_object_tracking.ipynb Import necessary libraries for video segmentation and file handling. ```python import os from samgeo import SamGeo3Video, download_file ``` -------------------------------- ### Run Pytest for cli-anything-samgeo Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/README.md Execute the test suite for the cli-anything-samgeo module. Navigate to the agent-harness directory and run pytest with verbose and capture-off flags. ```bash cd agent-harness python -m pytest cli_anything/samgeo/tests/ -v -s ``` -------------------------------- ### Initialize SAM 3 Video Tracker Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_video_masks.ipynb Initialize the SAM 3 video tracker. This object will be used for segmentation and tracking tasks. ```python # Initialize SAM 3 video predictor sam = SamGeo3Video() ``` -------------------------------- ### Configure SAM2 for Advanced Mask Generation Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_automatic.ipynb Initialize SamGeo2 with advanced parameters to fine-tune automatic mask generation. This includes adjusting sampling density, confidence thresholds, and post-processing options. ```python sam2 = SamGeo2( model_id="sam2-hiera-large", apply_postprocessing=False, points_per_side=32, points_per_batch=64, pred_iou_thresh=0.7, stability_score_thresh=0.92, stability_score_offset=0.7, crop_n_layers=1, box_nms_thresh=0.7, crop_n_points_downscale_factor=2, min_mask_region_area=25.0, use_m2m=True, ) ``` -------------------------------- ### Initialize Tree Crown Delineator Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/detectree2.ipynb Initialize the TreeCrownDelineator with a pre-trained model. The model is downloaded automatically on first use. Configure confidence and NMS thresholds. ```python delineator = TreeCrownDelineator( model_name="default", # Options: 'paracou', 'sepilok', 'danum', 'default' confidence_threshold=0.5, # Minimum confidence for predictions nms_threshold=0.3, # Non-maximum suppression threshold ) ``` -------------------------------- ### Initialize SAM3 Model Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_image_segmentation_jpg.ipynb Initializes the SamGeo3 model, allowing selection of the backend ('meta' or 'transformers') and specifying device and checkpoint path. `load_from_HF=True` is used when using the transformers backend. ```python sam3 = SamGeo3( backend="transformers", device=None, checkpoint_path=None, load_from_HF=True ) ``` -------------------------------- ### Import Libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam3_batch_segmentation.ipynb Import the necessary libraries for using leafmap and the SamGeo3 model. Ensure these are imported before proceeding. ```python import leafmap from samgeo import SamGeo3, download_file ``` -------------------------------- ### Create and Add Layers to Leafmap Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/workshops/IPPN_2024.ipynb Initialize a leafmap and add the original image and bounding box vector layer with custom styling. ```python m = leafmap.Map() m.add_raster(image, layer_name="image") style = { "color": "#ffff00", "weight": 2, "fillColor": "#7c4185", "fillOpacity": 0, } m.add_vector(geojson, style=style, zoom_to_layer=True, layer_name="Bounding boxes") ``` -------------------------------- ### Import necessary libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/automatic_mask_generator.ipynb Import the leafmap, SamGeo, and common utility functions for geospatial operations and SAM integration. ```python import leafmap from samgeo import SamGeo from samgeo.common import overlay_images, tms_to_geotiff ``` -------------------------------- ### Download Sample Video Data Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/sam2_video.ipynb Download a sample MP4 video file for testing video segmentation. ```python url = "https://github.com/opengeos/datasets/releases/download/videos/cars.mp4" video_path = url predictor.set_video(video_path) ``` -------------------------------- ### Initialize SAMGeo class Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/automatic_mask_generator.ipynb Initialize the SamGeo class with a specified model type. If the model checkpoint is not found, it will be downloaded to the current working directory. ```python sam = SamGeo( model_type="vit_h", sam_kwargs=None, ) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/automatic_mask_generator_hq.ipynb Imports the required modules for map creation, SAM model interaction, and geospatial utilities. ```python import leafmap from samgeo.hq_sam import SamGeo from samgeo.common import overlay_images, tms_to_geotiff ``` -------------------------------- ### Download vector file for box prompts Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/box_prompts.ipynb Download a sample GeoJSON file containing bounding boxes from a GitHub URL using leafmap's download utility. ```python url = "https://opengeos.github.io/data/sam/tree_boxes.geojson" geojson = "tree_boxes.geojson" leafmap.download_file(url, geojson) ``` -------------------------------- ### List Available Pre-trained Models Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/examples/detectree2.ipynb Retrieve and print the names and download URLs of available pre-trained models for detectree2. ```python models = list_pretrained_models() for name, url in models.items(): print(f"{name}: {url}") ``` -------------------------------- ### Pixi.toml configuration for CPU Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md TOML configuration for a Pixi project with CPU-only support. Uses pytorch-cpu and includes libopenblas. ```toml [workspace] channels = ["https://prefix.dev/conda-forge"] name = "geo" platforms = ["linux-64", "win-64"] [dependencies] python = "3.12.*" pytorch-cpu = ">=2.7.1,<3" segment-geospatial = ">=1.2.0" sam3 = ">=0.1.0.20251211" jupyterlab = "*" ipykernel = "*" libopenblas = ">=0.3.30" ``` -------------------------------- ### List Basemaps Source: https://github.com/opengeos/segment-geospatial/blob/main/agent-harness/cli_anything/samgeo/skills/SKILL.md List available basemap sources. ```bash cli-anything-samgeo data basemaps [--all] ``` -------------------------------- ### Authenticate with Hugging Face Hub Source: https://github.com/opengeos/segment-geospatial/blob/main/docs/installation.md Logs into the Hugging Face Hub using Pixi. Required before downloading models like SAM 3. ```bash pixi run hf auth login ```