Skip to content

segment module

This module provides functionality for segmenting high-resolution satellite imagery using vision-language models.

BoundingBox dataclass

Represents a bounding box with coordinates.

Source code in geoai/segment.py
32
33
34
35
36
37
38
39
40
41
42
43
@dataclass
class BoundingBox:
    """Represents a bounding box with coordinates."""

    xmin: int
    ymin: int
    xmax: int
    ymax: int

    @property
    def xyxy(self) -> List[float]:
        return [self.xmin, self.ymin, self.xmax, self.ymax]

CLIPSegmentation

A class for segmenting high-resolution satellite imagery using text prompts with CLIP-based models.

This segmenter utilizes the CLIP-Seg model to perform semantic segmentation based on text prompts. It can process large GeoTIFF files by tiling them and handles proper georeferencing in the output.

Parameters:

Name Type Description Default
model_name str

Name of the CLIP-Seg model to use. Defaults to "CIDAS/clipseg-rd64-refined".

'CIDAS/clipseg-rd64-refined'
device str

Device to run the model on ('cuda', 'cpu'). If None, will use CUDA if available.

None
tile_size int

Size of tiles to process the image in chunks. Defaults to 352.

512
overlap int

Overlap between tiles to avoid edge artifacts. Defaults to 16.

32

Attributes:

Name Type Description
processor CLIPSegProcessor

The processor for the CLIP-Seg model.

model CLIPSegForImageSegmentation

The CLIP-Seg model for segmentation.

device str

The device being used ('cuda' or 'cpu').

tile_size int

Size of tiles for processing.

overlap int

Overlap between tiles.

Source code in geoai/segment.py
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
class CLIPSegmentation:
    """
    A class for segmenting high-resolution satellite imagery using text prompts with CLIP-based models.

    This segmenter utilizes the CLIP-Seg model to perform semantic segmentation based on text prompts.
    It can process large GeoTIFF files by tiling them and handles proper georeferencing in the output.

    Args:
        model_name (str): Name of the CLIP-Seg model to use. Defaults to "CIDAS/clipseg-rd64-refined".
        device (str): Device to run the model on ('cuda', 'cpu'). If None, will use CUDA if available.
        tile_size (int): Size of tiles to process the image in chunks. Defaults to 352.
        overlap (int): Overlap between tiles to avoid edge artifacts. Defaults to 16.

    Attributes:
        processor (CLIPSegProcessor): The processor for the CLIP-Seg model.
        model (CLIPSegForImageSegmentation): The CLIP-Seg model for segmentation.
        device (str): The device being used ('cuda' or 'cpu').
        tile_size (int): Size of tiles for processing.
        overlap (int): Overlap between tiles.
    """

    def __init__(
        self,
        model_name: str = "CIDAS/clipseg-rd64-refined",
        device: Optional[str] = None,
        tile_size: int = 512,
        overlap: int = 32,
    ) -> None:
        """
        Initialize the ImageSegmenter with the specified model and settings.

        Args:
            model_name (str): Name of the CLIP-Seg model to use. Defaults to "CIDAS/clipseg-rd64-refined".
            device (str): Device to run the model on ('cuda', 'cpu'). If None, will use CUDA if available.
            tile_size (int): Size of tiles to process the image in chunks. Defaults to 512.
            overlap (int): Overlap between tiles to avoid edge artifacts. Defaults to 32.
        """
        self.tile_size = tile_size
        self.overlap = overlap

        # Set device
        if device is None:
            self.device = "cuda" if torch.cuda.is_available() else "cpu"
        else:
            self.device = device

        # Load model and processor
        self.processor = CLIPSegProcessor.from_pretrained(model_name)
        self.model = CLIPSegForImageSegmentation.from_pretrained(model_name).to(
            self.device
        )

        print(f"Model loaded on {self.device}")

    def segment_image(
        self,
        input_path: str,
        output_path: str,
        text_prompt: str,
        threshold: float = 0.5,
        smoothing_sigma: float = 1.0,
    ) -> str:
        """
        Segment a GeoTIFF image using the provided text prompt.

        The function processes the image in tiles and saves the result as a GeoTIFF with two bands:
        - Band 1: Binary segmentation mask (0 or 1)
        - Band 2: Probability scores (0.0 to 1.0)

        Args:
            input_path (str): Path to the input GeoTIFF file.
            output_path (str): Path where the output GeoTIFF will be saved.
            text_prompt (str): Text description of what to segment (e.g., "water", "buildings").
            threshold (float): Threshold for binary segmentation (0.0 to 1.0). Defaults to 0.5.
            smoothing_sigma (float): Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0.

        Returns:
            str: Path to the saved output file.
        """
        # Open the input GeoTIFF
        with rasterio.open(input_path) as src:
            # Get metadata
            meta = src.meta
            height = src.height
            width = src.width

            # Create output metadata
            out_meta = meta.copy()
            out_meta.update({"count": 2, "dtype": "float32", "nodata": None})

            # Create arrays for results
            segmentation = np.zeros((height, width), dtype=np.float32)
            probabilities = np.zeros((height, width), dtype=np.float32)

            # Calculate effective tile size (accounting for overlap)
            effective_tile_size = self.tile_size - 2 * self.overlap

            # Calculate number of tiles
            n_tiles_x = max(1, int(np.ceil(width / effective_tile_size)))
            n_tiles_y = max(1, int(np.ceil(height / effective_tile_size)))
            total_tiles = n_tiles_x * n_tiles_y

            # Process tiles with tqdm progress bar
            with tqdm(total=total_tiles, desc="Processing tiles") as pbar:
                # Iterate through tiles
                for y in range(n_tiles_y):
                    for x in range(n_tiles_x):
                        # Calculate tile coordinates with overlap
                        x_start = max(0, x * effective_tile_size - self.overlap)
                        y_start = max(0, y * effective_tile_size - self.overlap)
                        x_end = min(width, (x + 1) * effective_tile_size + self.overlap)
                        y_end = min(
                            height, (y + 1) * effective_tile_size + self.overlap
                        )

                        tile_width = x_end - x_start
                        tile_height = y_end - y_start

                        # Read the tile
                        window = Window(x_start, y_start, tile_width, tile_height)
                        tile_data = src.read(window=window)

                        # Process the tile
                        try:
                            # Convert to RGB if necessary (handling different satellite bands)
                            if tile_data.shape[0] > 3:
                                # Use first three bands for RGB representation
                                rgb_tile = tile_data[:3].transpose(1, 2, 0)
                                # Normalize data to 0-255 range if needed
                                if rgb_tile.max() > 0:
                                    rgb_tile = (
                                        (rgb_tile - rgb_tile.min())
                                        / (rgb_tile.max() - rgb_tile.min())
                                        * 255
                                    ).astype(np.uint8)
                            elif tile_data.shape[0] == 1:
                                # Create RGB from grayscale
                                rgb_tile = np.repeat(
                                    tile_data[0][:, :, np.newaxis], 3, axis=2
                                )
                                # Normalize if needed
                                if rgb_tile.max() > 0:
                                    rgb_tile = (
                                        (rgb_tile - rgb_tile.min())
                                        / (rgb_tile.max() - rgb_tile.min())
                                        * 255
                                    ).astype(np.uint8)
                            else:
                                # Already 3-channel, assume RGB
                                rgb_tile = tile_data.transpose(1, 2, 0)
                                # Normalize if needed
                                if rgb_tile.max() > 0:
                                    rgb_tile = (
                                        (rgb_tile - rgb_tile.min())
                                        / (rgb_tile.max() - rgb_tile.min())
                                        * 255
                                    ).astype(np.uint8)

                            # Convert to PIL Image
                            pil_image = Image.fromarray(rgb_tile)

                            # Resize if needed to match model's requirements
                            if (
                                pil_image.width > self.tile_size
                                or pil_image.height > self.tile_size
                            ):
                                # Keep aspect ratio - use LANCZOS resampling instead of deprecated constant
                                pil_image.thumbnail(
                                    (self.tile_size, self.tile_size),
                                    Image.Resampling.LANCZOS,
                                )

                            # Process with CLIP-Seg
                            inputs = self.processor(
                                text=text_prompt, images=pil_image, return_tensors="pt"
                            ).to(self.device)

                            # Forward pass
                            with torch.no_grad():
                                outputs = self.model(**inputs)

                            # Get logits and resize to original tile size
                            logits = outputs.logits[0]

                            # Convert logits to probabilities with sigmoid
                            probs = torch.sigmoid(logits).cpu().numpy()

                            # Resize back to original tile size if needed
                            if probs.shape != (tile_height, tile_width):
                                # Use bicubic interpolation for smoother results
                                probs_resized = np.array(
                                    Image.fromarray(probs).resize(
                                        (tile_width, tile_height),
                                        Image.Resampling.BICUBIC,
                                    )
                                )
                            else:
                                probs_resized = probs

                            # Apply gaussian blur to reduce blockiness
                            try:
                                from scipy.ndimage import gaussian_filter

                                probs_resized = gaussian_filter(
                                    probs_resized, sigma=smoothing_sigma
                                )
                            except ImportError:
                                pass  # Continue without smoothing if scipy is not available

                            # Store results in the full arrays
                            # Only store the non-overlapping part (except at edges)
                            valid_x_start = self.overlap if x > 0 else 0
                            valid_y_start = self.overlap if y > 0 else 0
                            valid_x_end = (
                                tile_width - self.overlap
                                if x < n_tiles_x - 1
                                else tile_width
                            )
                            valid_y_end = (
                                tile_height - self.overlap
                                if y < n_tiles_y - 1
                                else tile_height
                            )

                            dest_x_start = x_start + valid_x_start
                            dest_y_start = y_start + valid_y_start
                            dest_x_end = x_start + valid_x_end
                            dest_y_end = y_start + valid_y_end

                            # Store probabilities
                            probabilities[
                                dest_y_start:dest_y_end, dest_x_start:dest_x_end
                            ] = probs_resized[
                                valid_y_start:valid_y_end, valid_x_start:valid_x_end
                            ]

                        except Exception as e:
                            print(f"Error processing tile at ({x}, {y}): {str(e)}")
                            # Continue with next tile

                        # Update progress bar
                        pbar.update(1)

            # Create binary segmentation from probabilities
            segmentation = (probabilities >= threshold).astype(np.float32)

            # Write the output GeoTIFF
            with rasterio.open(output_path, "w", **out_meta) as dst:
                dst.write(segmentation, 1)
                dst.write(probabilities, 2)

                # Add descriptions to bands
                dst.set_band_description(1, "Binary Segmentation")
                dst.set_band_description(2, "Probability Scores")

            print(f"Segmentation saved to {output_path}")
            return output_path

    def segment_image_batch(
        self,
        input_paths: List[str],
        output_dir: str,
        text_prompt: str,
        threshold: float = 0.5,
        smoothing_sigma: float = 1.0,
        suffix: str = "_segmented",
    ) -> List[str]:
        """
        Segment multiple GeoTIFF images using the provided text prompt.

        Args:
            input_paths (list): List of paths to input GeoTIFF files.
            output_dir (str): Directory where output GeoTIFFs will be saved.
            text_prompt (str): Text description of what to segment.
            threshold (float): Threshold for binary segmentation. Defaults to 0.5.
            smoothing_sigma (float): Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0.
            suffix (str): Suffix to add to output filenames. Defaults to "_segmented".

        Returns:
            list: Paths to all saved output files.
        """
        # Create output directory if it doesn't exist
        os.makedirs(output_dir, exist_ok=True)

        output_paths = []

        # Process each input file
        for input_path in tqdm(input_paths, desc="Processing files"):
            # Generate output path
            filename = os.path.basename(input_path)
            base_name, ext = os.path.splitext(filename)
            output_path = os.path.join(output_dir, f"{base_name}{suffix}{ext}")

            # Segment the image
            result_path = self.segment_image(
                input_path, output_path, text_prompt, threshold, smoothing_sigma
            )
            output_paths.append(result_path)

        return output_paths

__init__(model_name='CIDAS/clipseg-rd64-refined', device=None, tile_size=512, overlap=32)

Initialize the ImageSegmenter with the specified model and settings.

Parameters:

Name Type Description Default
model_name str

Name of the CLIP-Seg model to use. Defaults to "CIDAS/clipseg-rd64-refined".

'CIDAS/clipseg-rd64-refined'
device str

Device to run the model on ('cuda', 'cpu'). If None, will use CUDA if available.

None
tile_size int

Size of tiles to process the image in chunks. Defaults to 512.

512
overlap int

Overlap between tiles to avoid edge artifacts. Defaults to 32.

32
Source code in geoai/segment.py
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def __init__(
    self,
    model_name: str = "CIDAS/clipseg-rd64-refined",
    device: Optional[str] = None,
    tile_size: int = 512,
    overlap: int = 32,
) -> None:
    """
    Initialize the ImageSegmenter with the specified model and settings.

    Args:
        model_name (str): Name of the CLIP-Seg model to use. Defaults to "CIDAS/clipseg-rd64-refined".
        device (str): Device to run the model on ('cuda', 'cpu'). If None, will use CUDA if available.
        tile_size (int): Size of tiles to process the image in chunks. Defaults to 512.
        overlap (int): Overlap between tiles to avoid edge artifacts. Defaults to 32.
    """
    self.tile_size = tile_size
    self.overlap = overlap

    # Set device
    if device is None:
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
    else:
        self.device = device

    # Load model and processor
    self.processor = CLIPSegProcessor.from_pretrained(model_name)
    self.model = CLIPSegForImageSegmentation.from_pretrained(model_name).to(
        self.device
    )

    print(f"Model loaded on {self.device}")

segment_image(input_path, output_path, text_prompt, threshold=0.5, smoothing_sigma=1.0)

Segment a GeoTIFF image using the provided text prompt.

The function processes the image in tiles and saves the result as a GeoTIFF with two bands: - Band 1: Binary segmentation mask (0 or 1) - Band 2: Probability scores (0.0 to 1.0)

Parameters:

Name Type Description Default
input_path str

Path to the input GeoTIFF file.

required
output_path str

Path where the output GeoTIFF will be saved.

required
text_prompt str

Text description of what to segment (e.g., "water", "buildings").

required
threshold float

Threshold for binary segmentation (0.0 to 1.0). Defaults to 0.5.

0.5
smoothing_sigma float

Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0.

1.0

Returns:

Name Type Description
str str

Path to the saved output file.

Source code in geoai/segment.py
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
def segment_image(
    self,
    input_path: str,
    output_path: str,
    text_prompt: str,
    threshold: float = 0.5,
    smoothing_sigma: float = 1.0,
) -> str:
    """
    Segment a GeoTIFF image using the provided text prompt.

    The function processes the image in tiles and saves the result as a GeoTIFF with two bands:
    - Band 1: Binary segmentation mask (0 or 1)
    - Band 2: Probability scores (0.0 to 1.0)

    Args:
        input_path (str): Path to the input GeoTIFF file.
        output_path (str): Path where the output GeoTIFF will be saved.
        text_prompt (str): Text description of what to segment (e.g., "water", "buildings").
        threshold (float): Threshold for binary segmentation (0.0 to 1.0). Defaults to 0.5.
        smoothing_sigma (float): Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0.

    Returns:
        str: Path to the saved output file.
    """
    # Open the input GeoTIFF
    with rasterio.open(input_path) as src:
        # Get metadata
        meta = src.meta
        height = src.height
        width = src.width

        # Create output metadata
        out_meta = meta.copy()
        out_meta.update({"count": 2, "dtype": "float32", "nodata": None})

        # Create arrays for results
        segmentation = np.zeros((height, width), dtype=np.float32)
        probabilities = np.zeros((height, width), dtype=np.float32)

        # Calculate effective tile size (accounting for overlap)
        effective_tile_size = self.tile_size - 2 * self.overlap

        # Calculate number of tiles
        n_tiles_x = max(1, int(np.ceil(width / effective_tile_size)))
        n_tiles_y = max(1, int(np.ceil(height / effective_tile_size)))
        total_tiles = n_tiles_x * n_tiles_y

        # Process tiles with tqdm progress bar
        with tqdm(total=total_tiles, desc="Processing tiles") as pbar:
            # Iterate through tiles
            for y in range(n_tiles_y):
                for x in range(n_tiles_x):
                    # Calculate tile coordinates with overlap
                    x_start = max(0, x * effective_tile_size - self.overlap)
                    y_start = max(0, y * effective_tile_size - self.overlap)
                    x_end = min(width, (x + 1) * effective_tile_size + self.overlap)
                    y_end = min(
                        height, (y + 1) * effective_tile_size + self.overlap
                    )

                    tile_width = x_end - x_start
                    tile_height = y_end - y_start

                    # Read the tile
                    window = Window(x_start, y_start, tile_width, tile_height)
                    tile_data = src.read(window=window)

                    # Process the tile
                    try:
                        # Convert to RGB if necessary (handling different satellite bands)
                        if tile_data.shape[0] > 3:
                            # Use first three bands for RGB representation
                            rgb_tile = tile_data[:3].transpose(1, 2, 0)
                            # Normalize data to 0-255 range if needed
                            if rgb_tile.max() > 0:
                                rgb_tile = (
                                    (rgb_tile - rgb_tile.min())
                                    / (rgb_tile.max() - rgb_tile.min())
                                    * 255
                                ).astype(np.uint8)
                        elif tile_data.shape[0] == 1:
                            # Create RGB from grayscale
                            rgb_tile = np.repeat(
                                tile_data[0][:, :, np.newaxis], 3, axis=2
                            )
                            # Normalize if needed
                            if rgb_tile.max() > 0:
                                rgb_tile = (
                                    (rgb_tile - rgb_tile.min())
                                    / (rgb_tile.max() - rgb_tile.min())
                                    * 255
                                ).astype(np.uint8)
                        else:
                            # Already 3-channel, assume RGB
                            rgb_tile = tile_data.transpose(1, 2, 0)
                            # Normalize if needed
                            if rgb_tile.max() > 0:
                                rgb_tile = (
                                    (rgb_tile - rgb_tile.min())
                                    / (rgb_tile.max() - rgb_tile.min())
                                    * 255
                                ).astype(np.uint8)

                        # Convert to PIL Image
                        pil_image = Image.fromarray(rgb_tile)

                        # Resize if needed to match model's requirements
                        if (
                            pil_image.width > self.tile_size
                            or pil_image.height > self.tile_size
                        ):
                            # Keep aspect ratio - use LANCZOS resampling instead of deprecated constant
                            pil_image.thumbnail(
                                (self.tile_size, self.tile_size),
                                Image.Resampling.LANCZOS,
                            )

                        # Process with CLIP-Seg
                        inputs = self.processor(
                            text=text_prompt, images=pil_image, return_tensors="pt"
                        ).to(self.device)

                        # Forward pass
                        with torch.no_grad():
                            outputs = self.model(**inputs)

                        # Get logits and resize to original tile size
                        logits = outputs.logits[0]

                        # Convert logits to probabilities with sigmoid
                        probs = torch.sigmoid(logits).cpu().numpy()

                        # Resize back to original tile size if needed
                        if probs.shape != (tile_height, tile_width):
                            # Use bicubic interpolation for smoother results
                            probs_resized = np.array(
                                Image.fromarray(probs).resize(
                                    (tile_width, tile_height),
                                    Image.Resampling.BICUBIC,
                                )
                            )
                        else:
                            probs_resized = probs

                        # Apply gaussian blur to reduce blockiness
                        try:
                            from scipy.ndimage import gaussian_filter

                            probs_resized = gaussian_filter(
                                probs_resized, sigma=smoothing_sigma
                            )
                        except ImportError:
                            pass  # Continue without smoothing if scipy is not available

                        # Store results in the full arrays
                        # Only store the non-overlapping part (except at edges)
                        valid_x_start = self.overlap if x > 0 else 0
                        valid_y_start = self.overlap if y > 0 else 0
                        valid_x_end = (
                            tile_width - self.overlap
                            if x < n_tiles_x - 1
                            else tile_width
                        )
                        valid_y_end = (
                            tile_height - self.overlap
                            if y < n_tiles_y - 1
                            else tile_height
                        )

                        dest_x_start = x_start + valid_x_start
                        dest_y_start = y_start + valid_y_start
                        dest_x_end = x_start + valid_x_end
                        dest_y_end = y_start + valid_y_end

                        # Store probabilities
                        probabilities[
                            dest_y_start:dest_y_end, dest_x_start:dest_x_end
                        ] = probs_resized[
                            valid_y_start:valid_y_end, valid_x_start:valid_x_end
                        ]

                    except Exception as e:
                        print(f"Error processing tile at ({x}, {y}): {str(e)}")
                        # Continue with next tile

                    # Update progress bar
                    pbar.update(1)

        # Create binary segmentation from probabilities
        segmentation = (probabilities >= threshold).astype(np.float32)

        # Write the output GeoTIFF
        with rasterio.open(output_path, "w", **out_meta) as dst:
            dst.write(segmentation, 1)
            dst.write(probabilities, 2)

            # Add descriptions to bands
            dst.set_band_description(1, "Binary Segmentation")
            dst.set_band_description(2, "Probability Scores")

        print(f"Segmentation saved to {output_path}")
        return output_path

segment_image_batch(input_paths, output_dir, text_prompt, threshold=0.5, smoothing_sigma=1.0, suffix='_segmented')

Segment multiple GeoTIFF images using the provided text prompt.

Parameters:

Name Type Description Default
input_paths list

List of paths to input GeoTIFF files.

required
output_dir str

Directory where output GeoTIFFs will be saved.

required
text_prompt str

Text description of what to segment.

required
threshold float

Threshold for binary segmentation. Defaults to 0.5.

0.5
smoothing_sigma float

Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0.

1.0
suffix str

Suffix to add to output filenames. Defaults to "_segmented".

'_segmented'

Returns:

Name Type Description
list List[str]

Paths to all saved output files.

Source code in geoai/segment.py
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
def segment_image_batch(
    self,
    input_paths: List[str],
    output_dir: str,
    text_prompt: str,
    threshold: float = 0.5,
    smoothing_sigma: float = 1.0,
    suffix: str = "_segmented",
) -> List[str]:
    """
    Segment multiple GeoTIFF images using the provided text prompt.

    Args:
        input_paths (list): List of paths to input GeoTIFF files.
        output_dir (str): Directory where output GeoTIFFs will be saved.
        text_prompt (str): Text description of what to segment.
        threshold (float): Threshold for binary segmentation. Defaults to 0.5.
        smoothing_sigma (float): Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0.
        suffix (str): Suffix to add to output filenames. Defaults to "_segmented".

    Returns:
        list: Paths to all saved output files.
    """
    # Create output directory if it doesn't exist
    os.makedirs(output_dir, exist_ok=True)

    output_paths = []

    # Process each input file
    for input_path in tqdm(input_paths, desc="Processing files"):
        # Generate output path
        filename = os.path.basename(input_path)
        base_name, ext = os.path.splitext(filename)
        output_path = os.path.join(output_dir, f"{base_name}{suffix}{ext}")

        # Segment the image
        result_path = self.segment_image(
            input_path, output_path, text_prompt, threshold, smoothing_sigma
        )
        output_paths.append(result_path)

    return output_paths

DetectionResult dataclass

Represents a detection result with score, label, bounding box, and optional mask.

Source code in geoai/segment.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass
class DetectionResult:
    """Represents a detection result with score, label, bounding box, and optional mask."""

    score: float
    label: str
    box: BoundingBox
    mask: Optional[np.array] = None

    @classmethod
    def from_dict(cls, detection_dict: Dict) -> "DetectionResult":
        return cls(
            score=detection_dict["score"],
            label=detection_dict["label"],
            box=BoundingBox(
                xmin=detection_dict["box"]["xmin"],
                ymin=detection_dict["box"]["ymin"],
                xmax=detection_dict["box"]["xmax"],
                ymax=detection_dict["box"]["ymax"],
            ),
        )

GroundedSAM

A class for segmenting remote sensing imagery using text prompts with Grounding DINO + SAM.

This class combines Grounding DINO for object detection and Segment Anything Model (SAM) for precise segmentation based on text prompts. It can process large GeoTIFF files by tiling them and handles proper georeferencing in the outputs.

Parameters:

Name Type Description Default
detector_id str

Hugging Face model ID for Grounding DINO. Defaults to "IDEA-Research/grounding-dino-tiny".

'IDEA-Research/grounding-dino-tiny'
segmenter_id str

Hugging Face model ID for SAM. Defaults to "facebook/sam-vit-base".

'facebook/sam-vit-base'
device str

Device to run the models on ('cuda', 'cpu'). If None, will use CUDA if available.

None
tile_size int

Size of tiles to process the image in chunks. Defaults to 1024.

1024
overlap int

Overlap between tiles to avoid edge artifacts. Defaults to 128.

128
threshold float

Detection threshold for Grounding DINO. Defaults to 0.3.

0.3

Attributes:

Name Type Description
detector_id str

The Grounding DINO model ID.

segmenter_id str

The SAM model ID.

device str

The device being used ('cuda' or 'cpu').

tile_size int

Size of tiles for processing.

overlap int

Overlap between tiles.

threshold float

Detection threshold.

object_detector float

The Grounding DINO pipeline.

segmentator float

The SAM model.

processor float

The SAM processor.

Source code in geoai/segment.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
class GroundedSAM:
    """
    A class for segmenting remote sensing imagery using text prompts with Grounding DINO + SAM.

    This class combines Grounding DINO for object detection and Segment Anything Model (SAM) for
    precise segmentation based on text prompts. It can process large GeoTIFF files by tiling them
    and handles proper georeferencing in the outputs.

    Args:
        detector_id (str): Hugging Face model ID for Grounding DINO. Defaults to "IDEA-Research/grounding-dino-tiny".
        segmenter_id (str): Hugging Face model ID for SAM. Defaults to "facebook/sam-vit-base".
        device (str): Device to run the models on ('cuda', 'cpu'). If None, will use CUDA if available.
        tile_size (int): Size of tiles to process the image in chunks. Defaults to 1024.
        overlap (int): Overlap between tiles to avoid edge artifacts. Defaults to 128.
        threshold (float): Detection threshold for Grounding DINO. Defaults to 0.3.

    Attributes:
        detector_id (str): The Grounding DINO model ID.
        segmenter_id (str): The SAM model ID.
        device (str): The device being used ('cuda' or 'cpu').
        tile_size (int): Size of tiles for processing.
        overlap (int): Overlap between tiles.
        threshold (float): Detection threshold.
        object_detector: The Grounding DINO pipeline.
        segmentator: The SAM model.
        processor: The SAM processor.
    """

    def __init__(
        self,
        detector_id: str = "IDEA-Research/grounding-dino-tiny",
        segmenter_id: str = "facebook/sam-vit-base",
        device: Optional[str] = None,
        tile_size: int = 1024,
        overlap: int = 128,
        threshold: float = 0.3,
    ) -> None:
        """
        Initialize the GroundedSAM with the specified models and settings.

        Args:
            detector_id (str): Hugging Face model ID for Grounding DINO.
            segmenter_id (str): Hugging Face model ID for SAM.
            device (str): Device to run the models on ('cuda', 'cpu').
            tile_size (int): Size of tiles to process the image in chunks.
            overlap (int): Overlap between tiles to avoid edge artifacts.
            threshold (float): Detection threshold for Grounding DINO.
        """
        self.detector_id = detector_id
        self.segmenter_id = segmenter_id
        self.tile_size = tile_size
        self.overlap = overlap
        self.threshold = threshold

        # Set device
        if device is None:
            self.device = "cuda" if torch.cuda.is_available() else "cpu"
        else:
            self.device = device

        # Load models
        self._load_models()

        print(f"GroundedSAM initialized on {self.device}")

    def _load_models(self) -> None:
        """Load the Grounding DINO and SAM models."""
        # Load Grounding DINO
        self.object_detector = pipeline(
            model=self.detector_id,
            task="zero-shot-object-detection",
            device=self.device,
        )

        # Load SAM
        self.segmentator = AutoModelForMaskGeneration.from_pretrained(
            self.segmenter_id
        ).to(self.device)
        self.processor = AutoProcessor.from_pretrained(self.segmenter_id)

    def _detect(self, image: Image.Image, labels: List[str]) -> List[DetectionResult]:
        """
        Use Grounding DINO to detect objects in an image.

        Args:
            image (Image.Image): PIL image to detect objects in.
            labels (List[str]): List of text labels to detect.

        Returns:
            List[DetectionResult]: List of detection results.
        """
        # Ensure labels end with periods
        labels = [label if label.endswith(".") else label + "." for label in labels]

        results = self.object_detector(
            image, candidate_labels=labels, threshold=self.threshold
        )
        results = [DetectionResult.from_dict(result) for result in results]

        return results

    def _apply_nms(
        self, detections: List[DetectionResult], iou_threshold: float = 0.5
    ) -> List[DetectionResult]:
        """
        Apply Non-Maximum Suppression to remove overlapping detections.

        Args:
            detections (List[DetectionResult]): List of detection results.
            iou_threshold (float): IoU threshold for NMS.

        Returns:
            List[DetectionResult]: Filtered detection results.
        """
        import cv2  # Lazy import to avoid QGIS opencv conflicts

        if not detections:
            return detections

        # Convert to format for NMS
        boxes = []
        scores = []

        for detection in detections:
            boxes.append(
                [
                    detection.box.xmin,
                    detection.box.ymin,
                    detection.box.xmax,
                    detection.box.ymax,
                ]
            )
            scores.append(detection.score)

        boxes = np.array(boxes, dtype=np.float32)
        scores = np.array(scores, dtype=np.float32)

        # Apply NMS using OpenCV
        indices = cv2.dnn.NMSBoxes(boxes, scores, self.threshold, iou_threshold)

        if len(indices) > 0:
            indices = indices.flatten()
            return [detections[i] for i in indices]
        else:
            return []

    def _get_boxes(self, results: List[DetectionResult]) -> List[List[List[float]]]:
        """Extract bounding boxes from detection results."""
        boxes = []
        for result in results:
            xyxy = result.box.xyxy
            boxes.append(xyxy)
        return [boxes]

    def _refine_masks(
        self, masks: torch.BoolTensor, polygon_refinement: bool = False
    ) -> List[np.ndarray]:
        """Refine masks from SAM output."""
        masks = masks.cpu().float()
        masks = masks.permute(0, 2, 3, 1)
        masks = masks.mean(axis=-1)
        masks = (masks > 0).int()
        masks = masks.numpy().astype(np.uint8)
        masks = list(masks)

        if polygon_refinement:
            for idx, mask in enumerate(masks):
                shape = mask.shape
                polygon = self._mask_to_polygon(mask)
                if polygon:
                    mask = self._polygon_to_mask(polygon, shape)
                    masks[idx] = mask

        return masks

    def _mask_to_polygon(self, mask: np.ndarray) -> List[List[int]]:
        """Convert mask to polygon coordinates."""
        import cv2  # Lazy import to avoid QGIS opencv conflicts

        # Find contours in the binary mask
        contours, _ = cv2.findContours(
            mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
        )

        if not contours:
            return []

        # Find the contour with the largest area
        largest_contour = max(contours, key=cv2.contourArea)

        # Extract the vertices of the contour
        polygon = largest_contour.reshape(-1, 2).tolist()

        return polygon

    def _polygon_to_mask(
        self, polygon: List[Tuple[int, int]], image_shape: Tuple[int, int]
    ) -> np.ndarray:
        """Convert polygon to mask."""
        import cv2  # Lazy import to avoid QGIS opencv conflicts

        # Create an empty mask
        mask = np.zeros(image_shape, dtype=np.uint8)

        # Convert polygon to an array of points
        pts = np.array(polygon, dtype=np.int32)

        # Fill the polygon with white color (255)
        cv2.fillPoly(mask, [pts], color=(255,))

        return mask

    def _separate_instances(
        self, mask: np.ndarray, min_area: int = 50
    ) -> List[np.ndarray]:
        """
        Separate individual instances from a combined mask using connected components.

        Args:
            mask (np.ndarray): Combined binary mask.
            min_area (int): Minimum area threshold for valid instances.

        Returns:
            List[np.ndarray]: List of individual instance masks.
        """
        import cv2  # Lazy import to avoid QGIS opencv conflicts

        # Find connected components
        num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(
            mask.astype(np.uint8), connectivity=8
        )

        instances = []
        for i in range(1, num_labels):  # Skip background (label 0)
            # Get area of the component
            area = stats[i, cv2.CC_STAT_AREA]

            # Filter by minimum area
            if area >= min_area:
                # Create mask for this instance
                instance_mask = (labels == i).astype(np.uint8) * 255
                instances.append(instance_mask)

        return instances

    def _mask_to_polygons(
        self,
        mask: np.ndarray,
        transform,
        x_offset: int = 0,
        y_offset: int = 0,
        min_area: int = 50,
        simplify_tolerance: float = 1.0,
    ) -> List[Dict]:
        """
        Convert mask to individual polygons with geospatial coordinates.

        Args:
            mask (np.ndarray): Binary mask.
            transform: Rasterio transform object.
            x_offset (int): X offset for tile position.
            y_offset (int): Y offset for tile position.
            min_area (int): Minimum area threshold for valid polygons.
            simplify_tolerance (float): Tolerance for polygon simplification.

        Returns:
            List[Dict]: List of polygon dictionaries with geometry and properties.
        """
        import cv2  # Lazy import to avoid QGIS opencv conflicts

        polygons = []

        # Get individual instances
        instances = self._separate_instances(mask, min_area)

        for instance_mask in instances:
            # Find contours
            contours, _ = cv2.findContours(
                instance_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
            )

            for contour in contours:
                # Filter by minimum area
                area = cv2.contourArea(contour)
                if area < min_area:
                    continue

                # Simplify contour
                epsilon = simplify_tolerance
                simplified_contour = cv2.approxPolyDP(contour, epsilon, True)

                # Convert to pixel coordinates (add offsets)
                pixel_coords = simplified_contour.reshape(-1, 2)
                pixel_coords = pixel_coords + [x_offset, y_offset]

                # Convert to geographic coordinates
                geo_coords = []
                for x, y in pixel_coords:
                    geo_x, geo_y = transform * (x, y)
                    geo_coords.append([geo_x, geo_y])

                # Close the polygon if needed
                if len(geo_coords) > 2:
                    if geo_coords[0] != geo_coords[-1]:
                        geo_coords.append(geo_coords[0])

                    # Create Shapely polygon
                    try:
                        polygon = Polygon(geo_coords)
                        if polygon.is_valid and polygon.area > 0:
                            polygons.append({"geometry": polygon, "area_pixels": area})
                    except Exception as e:
                        print(f"Error creating polygon: {e}")
                        continue

        return polygons

    def _segment(
        self,
        image: Image.Image,
        detection_results: List[DetectionResult],
        polygon_refinement: bool = False,
    ) -> List[DetectionResult]:
        """
        Use SAM to generate masks for detected objects.

        Args:
            image (Image.Image): PIL image.
            detection_results (List[DetectionResult]): Detection results from Grounding DINO.
            polygon_refinement (bool): Whether to refine masks using polygon fitting.

        Returns:
            List[DetectionResult]: Detection results with masks.
        """
        if not detection_results:
            return detection_results

        boxes = self._get_boxes(detection_results)
        inputs = self.processor(
            images=image, input_boxes=boxes, return_tensors="pt"
        ).to(self.device)

        outputs = self.segmentator(**inputs)
        masks = self.processor.post_process_masks(
            masks=outputs.pred_masks,
            original_sizes=inputs.original_sizes,
            reshaped_input_sizes=inputs.reshaped_input_sizes,
        )[0]

        masks = self._refine_masks(masks, polygon_refinement)

        for detection_result, mask in zip(detection_results, masks):
            detection_result.mask = mask

        return detection_results

    def segment_image(
        self,
        input_path: str,
        output_path: str,
        text_prompts: Union[str, List[str]],
        polygon_refinement: bool = False,
        export_boxes: bool = False,
        export_polygons: bool = True,
        smoothing_sigma: float = 1.0,
        nms_threshold: float = 0.5,
        min_polygon_area: int = 50,
        simplify_tolerance: float = 2.0,
    ) -> str:
        """
        Segment a GeoTIFF image using text prompts with improved instance segmentation.

        Args:
            input_path (str): Path to the input GeoTIFF file.
            output_path (str): Path where the output GeoTIFF will be saved.
            text_prompts (Union[str, List[str]]): Text prompt(s) describing what to segment.
            polygon_refinement (bool): Whether to refine masks using polygon fitting.
            export_boxes (bool): Whether to export bounding boxes as a separate vector file.
            export_polygons (bool): Whether to export segmentation polygons as vector file.
            smoothing_sigma (float): Sigma value for Gaussian smoothing to reduce blockiness.
            nms_threshold (float): Non-maximum suppression threshold for removing overlapping detections.
            min_polygon_area (int): Minimum area in pixels for valid polygons.
            simplify_tolerance (float): Tolerance for polygon simplification.

        Returns:
            Dict: Dictionary containing paths to output files.
        """
        if isinstance(text_prompts, str):
            text_prompts = [text_prompts]

        # Open the input GeoTIFF
        with rasterio.open(input_path) as src:
            # Get metadata
            meta = src.meta
            height = src.height
            width = src.width
            transform = src.transform
            crs = src.crs

            # Create output metadata for segmentation masks
            out_meta = meta.copy()
            out_meta.update(
                {"count": len(text_prompts) + 1, "dtype": "uint8", "nodata": 0}
            )

            # Create arrays for results
            all_masks = np.zeros((len(text_prompts), height, width), dtype=np.uint8)
            all_boxes = []
            all_polygons = []

            # Calculate effective tile size (accounting for overlap)
            effective_tile_size = self.tile_size - 2 * self.overlap

            # Calculate number of tiles
            n_tiles_x = max(1, int(np.ceil(width / effective_tile_size)))
            n_tiles_y = max(1, int(np.ceil(height / effective_tile_size)))
            total_tiles = n_tiles_x * n_tiles_y

            print(f"Processing {total_tiles} tiles ({n_tiles_x}x{n_tiles_y})")

            # Process tiles with tqdm progress bar
            with tqdm(total=total_tiles, desc="Processing tiles") as pbar:
                # Iterate through tiles
                for y in range(n_tiles_y):
                    for x in range(n_tiles_x):
                        # Calculate tile coordinates with overlap
                        x_start = max(0, x * effective_tile_size - self.overlap)
                        y_start = max(0, y * effective_tile_size - self.overlap)
                        x_end = min(width, (x + 1) * effective_tile_size + self.overlap)
                        y_end = min(
                            height, (y + 1) * effective_tile_size + self.overlap
                        )

                        tile_width = x_end - x_start
                        tile_height = y_end - y_start

                        # Read the tile
                        window = Window(x_start, y_start, tile_width, tile_height)
                        tile_data = src.read(window=window)

                        # Process the tile
                        try:
                            # Convert to RGB format for processing
                            if tile_data.shape[0] >= 3:
                                # Use first three bands for RGB representation
                                rgb_tile = tile_data[:3].transpose(1, 2, 0)
                            elif tile_data.shape[0] == 1:
                                # Create RGB from grayscale
                                rgb_tile = np.repeat(
                                    tile_data[0][:, :, np.newaxis], 3, axis=2
                                )
                            else:
                                print(
                                    f"Unsupported number of bands: {tile_data.shape[0]}"
                                )
                                continue

                            # Normalize to 0-255 range if needed
                            if rgb_tile.max() > 0:
                                rgb_tile = (
                                    (rgb_tile - rgb_tile.min())
                                    / (rgb_tile.max() - rgb_tile.min())
                                    * 255
                                ).astype(np.uint8)

                            # Convert to PIL Image
                            pil_image = Image.fromarray(rgb_tile)

                            # Detect objects
                            detections = self._detect(pil_image, text_prompts)

                            if detections:
                                # Apply Non-Maximum Suppression to reduce overlapping detections
                                detections = self._apply_nms(detections, nms_threshold)

                                if detections:
                                    # Segment objects
                                    detections = self._segment(
                                        pil_image, detections, polygon_refinement
                                    )

                                    # Process results
                                    for i, prompt in enumerate(text_prompts):
                                        prompt_polygons = []
                                        prompt_mask = np.zeros(
                                            (tile_height, tile_width), dtype=np.uint8
                                        )

                                        for detection in detections:
                                            if (
                                                detection.label.replace(".", "")
                                                .strip()
                                                .lower()
                                                == prompt.lower()
                                            ):
                                                if detection.mask is not None:
                                                    # Apply gaussian blur to reduce blockiness
                                                    try:
                                                        from scipy.ndimage import (
                                                            gaussian_filter,
                                                        )

                                                        smoothed_mask = gaussian_filter(
                                                            detection.mask.astype(
                                                                float
                                                            ),
                                                            sigma=smoothing_sigma,
                                                        )
                                                        detection.mask = (
                                                            smoothed_mask > 0.5
                                                        ).astype(np.uint8)
                                                    except ImportError:
                                                        pass

                                                    # Add to combined mask for this prompt
                                                    prompt_mask = np.maximum(
                                                        prompt_mask, detection.mask
                                                    )

                                                # Store bounding box with geospatial coordinates
                                                if export_boxes:
                                                    bbox = detection.box
                                                    x_geo_min, y_geo_min = transform * (
                                                        x_start + bbox.xmin,
                                                        y_start + bbox.ymin,
                                                    )
                                                    x_geo_max, y_geo_max = transform * (
                                                        x_start + bbox.xmax,
                                                        y_start + bbox.ymax,
                                                    )

                                                    geo_box = {
                                                        "label": detection.label,
                                                        "score": detection.score,
                                                        "prompt": prompt,
                                                        "geometry": box(
                                                            x_geo_min,
                                                            y_geo_max,
                                                            x_geo_max,
                                                            y_geo_min,
                                                        ),
                                                    }
                                                    all_boxes.append(geo_box)

                                        # Convert masks to individual polygons
                                        if export_polygons and np.any(prompt_mask):
                                            tile_polygons = self._mask_to_polygons(
                                                prompt_mask,
                                                transform,
                                                x_start,
                                                y_start,
                                                min_polygon_area,
                                                simplify_tolerance,
                                            )

                                            # Add metadata to polygons
                                            for poly_data in tile_polygons:
                                                poly_data.update(
                                                    {
                                                        "label": prompt,
                                                        "score": max(
                                                            [
                                                                d.score
                                                                for d in detections
                                                                if d.label.replace(
                                                                    ".", ""
                                                                )
                                                                .strip()
                                                                .lower()
                                                                == prompt.lower()
                                                            ],
                                                            default=0.0,
                                                        ),
                                                        "tile_x": x,
                                                        "tile_y": y,
                                                    }
                                                )
                                                all_polygons.append(poly_data)

                                        # Store mask in the global array
                                        valid_x_start = self.overlap if x > 0 else 0
                                        valid_y_start = self.overlap if y > 0 else 0
                                        valid_x_end = (
                                            tile_width - self.overlap
                                            if x < n_tiles_x - 1
                                            else tile_width
                                        )
                                        valid_y_end = (
                                            tile_height - self.overlap
                                            if y < n_tiles_y - 1
                                            else tile_height
                                        )

                                        dest_x_start = x_start + valid_x_start
                                        dest_y_start = y_start + valid_y_start
                                        dest_x_end = x_start + valid_x_end
                                        dest_y_end = y_start + valid_y_end

                                        mask_slice = prompt_mask[
                                            valid_y_start:valid_y_end,
                                            valid_x_start:valid_x_end,
                                        ]
                                        all_masks[
                                            i,
                                            dest_y_start:dest_y_end,
                                            dest_x_start:dest_x_end,
                                        ] = np.maximum(
                                            all_masks[
                                                i,
                                                dest_y_start:dest_y_end,
                                                dest_x_start:dest_x_end,
                                            ],
                                            mask_slice,
                                        )

                        except Exception as e:
                            print(f"Error processing tile at ({x}, {y}): {str(e)}")
                            continue

                        # Update progress bar
                        pbar.update(1)

            # Create combined mask (union of all individual masks)
            combined_mask = np.any(all_masks, axis=0).astype(np.uint8)

            # Write the output GeoTIFF
            with rasterio.open(output_path, "w", **out_meta) as dst:
                # Write combined mask as first band
                dst.write(combined_mask, 1)

                # Write individual masks for each prompt
                for i, mask in enumerate(all_masks):
                    dst.write(mask, i + 2)

                # Add descriptions to bands
                dst.set_band_description(1, "Combined Segmentation")
                for i, prompt in enumerate(text_prompts):
                    dst.set_band_description(i + 2, f"Segmentation: {prompt}")

            result_files = {"segmentation": output_path}

            # Export bounding boxes if requested
            if export_boxes and all_boxes:
                boxes_path = output_path.replace(".tif", "_boxes.geojson")
                gdf = gpd.GeoDataFrame(all_boxes, crs=crs)
                gdf.to_file(boxes_path, driver="GeoJSON")
                result_files["boxes"] = boxes_path
                print(f"Exported {len(all_boxes)} bounding boxes to {boxes_path}")

            # Export instance polygons if requested
            if export_polygons and all_polygons:
                polygons_path = output_path.replace(".tif", "_polygons.geojson")
                gdf = gpd.GeoDataFrame(all_polygons, crs=crs)
                gdf.to_file(polygons_path, driver="GeoJSON")
                result_files["polygons"] = polygons_path
                print(
                    f"Exported {len(all_polygons)} instance polygons to {polygons_path}"
                )

            print(f"Segmentation saved to {output_path}")
            print(
                f"Found {len(all_polygons)} individual building instances"
                if export_polygons
                else ""
            )

            return result_files

__init__(detector_id='IDEA-Research/grounding-dino-tiny', segmenter_id='facebook/sam-vit-base', device=None, tile_size=1024, overlap=128, threshold=0.3)

Initialize the GroundedSAM with the specified models and settings.

Parameters:

Name Type Description Default
detector_id str

Hugging Face model ID for Grounding DINO.

'IDEA-Research/grounding-dino-tiny'
segmenter_id str

Hugging Face model ID for SAM.

'facebook/sam-vit-base'
device str

Device to run the models on ('cuda', 'cpu').

None
tile_size int

Size of tiles to process the image in chunks.

1024
overlap int

Overlap between tiles to avoid edge artifacts.

128
threshold float

Detection threshold for Grounding DINO.

0.3
Source code in geoai/segment.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def __init__(
    self,
    detector_id: str = "IDEA-Research/grounding-dino-tiny",
    segmenter_id: str = "facebook/sam-vit-base",
    device: Optional[str] = None,
    tile_size: int = 1024,
    overlap: int = 128,
    threshold: float = 0.3,
) -> None:
    """
    Initialize the GroundedSAM with the specified models and settings.

    Args:
        detector_id (str): Hugging Face model ID for Grounding DINO.
        segmenter_id (str): Hugging Face model ID for SAM.
        device (str): Device to run the models on ('cuda', 'cpu').
        tile_size (int): Size of tiles to process the image in chunks.
        overlap (int): Overlap between tiles to avoid edge artifacts.
        threshold (float): Detection threshold for Grounding DINO.
    """
    self.detector_id = detector_id
    self.segmenter_id = segmenter_id
    self.tile_size = tile_size
    self.overlap = overlap
    self.threshold = threshold

    # Set device
    if device is None:
        self.device = "cuda" if torch.cuda.is_available() else "cpu"
    else:
        self.device = device

    # Load models
    self._load_models()

    print(f"GroundedSAM initialized on {self.device}")

segment_image(input_path, output_path, text_prompts, polygon_refinement=False, export_boxes=False, export_polygons=True, smoothing_sigma=1.0, nms_threshold=0.5, min_polygon_area=50, simplify_tolerance=2.0)

Segment a GeoTIFF image using text prompts with improved instance segmentation.

Parameters:

Name Type Description Default
input_path str

Path to the input GeoTIFF file.

required
output_path str

Path where the output GeoTIFF will be saved.

required
text_prompts Union[str, List[str]]

Text prompt(s) describing what to segment.

required
polygon_refinement bool

Whether to refine masks using polygon fitting.

False
export_boxes bool

Whether to export bounding boxes as a separate vector file.

False
export_polygons bool

Whether to export segmentation polygons as vector file.

True
smoothing_sigma float

Sigma value for Gaussian smoothing to reduce blockiness.

1.0
nms_threshold float

Non-maximum suppression threshold for removing overlapping detections.

0.5
min_polygon_area int

Minimum area in pixels for valid polygons.

50
simplify_tolerance float

Tolerance for polygon simplification.

2.0

Returns:

Name Type Description
Dict str

Dictionary containing paths to output files.

Source code in geoai/segment.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def segment_image(
    self,
    input_path: str,
    output_path: str,
    text_prompts: Union[str, List[str]],
    polygon_refinement: bool = False,
    export_boxes: bool = False,
    export_polygons: bool = True,
    smoothing_sigma: float = 1.0,
    nms_threshold: float = 0.5,
    min_polygon_area: int = 50,
    simplify_tolerance: float = 2.0,
) -> str:
    """
    Segment a GeoTIFF image using text prompts with improved instance segmentation.

    Args:
        input_path (str): Path to the input GeoTIFF file.
        output_path (str): Path where the output GeoTIFF will be saved.
        text_prompts (Union[str, List[str]]): Text prompt(s) describing what to segment.
        polygon_refinement (bool): Whether to refine masks using polygon fitting.
        export_boxes (bool): Whether to export bounding boxes as a separate vector file.
        export_polygons (bool): Whether to export segmentation polygons as vector file.
        smoothing_sigma (float): Sigma value for Gaussian smoothing to reduce blockiness.
        nms_threshold (float): Non-maximum suppression threshold for removing overlapping detections.
        min_polygon_area (int): Minimum area in pixels for valid polygons.
        simplify_tolerance (float): Tolerance for polygon simplification.

    Returns:
        Dict: Dictionary containing paths to output files.
    """
    if isinstance(text_prompts, str):
        text_prompts = [text_prompts]

    # Open the input GeoTIFF
    with rasterio.open(input_path) as src:
        # Get metadata
        meta = src.meta
        height = src.height
        width = src.width
        transform = src.transform
        crs = src.crs

        # Create output metadata for segmentation masks
        out_meta = meta.copy()
        out_meta.update(
            {"count": len(text_prompts) + 1, "dtype": "uint8", "nodata": 0}
        )

        # Create arrays for results
        all_masks = np.zeros((len(text_prompts), height, width), dtype=np.uint8)
        all_boxes = []
        all_polygons = []

        # Calculate effective tile size (accounting for overlap)
        effective_tile_size = self.tile_size - 2 * self.overlap

        # Calculate number of tiles
        n_tiles_x = max(1, int(np.ceil(width / effective_tile_size)))
        n_tiles_y = max(1, int(np.ceil(height / effective_tile_size)))
        total_tiles = n_tiles_x * n_tiles_y

        print(f"Processing {total_tiles} tiles ({n_tiles_x}x{n_tiles_y})")

        # Process tiles with tqdm progress bar
        with tqdm(total=total_tiles, desc="Processing tiles") as pbar:
            # Iterate through tiles
            for y in range(n_tiles_y):
                for x in range(n_tiles_x):
                    # Calculate tile coordinates with overlap
                    x_start = max(0, x * effective_tile_size - self.overlap)
                    y_start = max(0, y * effective_tile_size - self.overlap)
                    x_end = min(width, (x + 1) * effective_tile_size + self.overlap)
                    y_end = min(
                        height, (y + 1) * effective_tile_size + self.overlap
                    )

                    tile_width = x_end - x_start
                    tile_height = y_end - y_start

                    # Read the tile
                    window = Window(x_start, y_start, tile_width, tile_height)
                    tile_data = src.read(window=window)

                    # Process the tile
                    try:
                        # Convert to RGB format for processing
                        if tile_data.shape[0] >= 3:
                            # Use first three bands for RGB representation
                            rgb_tile = tile_data[:3].transpose(1, 2, 0)
                        elif tile_data.shape[0] == 1:
                            # Create RGB from grayscale
                            rgb_tile = np.repeat(
                                tile_data[0][:, :, np.newaxis], 3, axis=2
                            )
                        else:
                            print(
                                f"Unsupported number of bands: {tile_data.shape[0]}"
                            )
                            continue

                        # Normalize to 0-255 range if needed
                        if rgb_tile.max() > 0:
                            rgb_tile = (
                                (rgb_tile - rgb_tile.min())
                                / (rgb_tile.max() - rgb_tile.min())
                                * 255
                            ).astype(np.uint8)

                        # Convert to PIL Image
                        pil_image = Image.fromarray(rgb_tile)

                        # Detect objects
                        detections = self._detect(pil_image, text_prompts)

                        if detections:
                            # Apply Non-Maximum Suppression to reduce overlapping detections
                            detections = self._apply_nms(detections, nms_threshold)

                            if detections:
                                # Segment objects
                                detections = self._segment(
                                    pil_image, detections, polygon_refinement
                                )

                                # Process results
                                for i, prompt in enumerate(text_prompts):
                                    prompt_polygons = []
                                    prompt_mask = np.zeros(
                                        (tile_height, tile_width), dtype=np.uint8
                                    )

                                    for detection in detections:
                                        if (
                                            detection.label.replace(".", "")
                                            .strip()
                                            .lower()
                                            == prompt.lower()
                                        ):
                                            if detection.mask is not None:
                                                # Apply gaussian blur to reduce blockiness
                                                try:
                                                    from scipy.ndimage import (
                                                        gaussian_filter,
                                                    )

                                                    smoothed_mask = gaussian_filter(
                                                        detection.mask.astype(
                                                            float
                                                        ),
                                                        sigma=smoothing_sigma,
                                                    )
                                                    detection.mask = (
                                                        smoothed_mask > 0.5
                                                    ).astype(np.uint8)
                                                except ImportError:
                                                    pass

                                                # Add to combined mask for this prompt
                                                prompt_mask = np.maximum(
                                                    prompt_mask, detection.mask
                                                )

                                            # Store bounding box with geospatial coordinates
                                            if export_boxes:
                                                bbox = detection.box
                                                x_geo_min, y_geo_min = transform * (
                                                    x_start + bbox.xmin,
                                                    y_start + bbox.ymin,
                                                )
                                                x_geo_max, y_geo_max = transform * (
                                                    x_start + bbox.xmax,
                                                    y_start + bbox.ymax,
                                                )

                                                geo_box = {
                                                    "label": detection.label,
                                                    "score": detection.score,
                                                    "prompt": prompt,
                                                    "geometry": box(
                                                        x_geo_min,
                                                        y_geo_max,
                                                        x_geo_max,
                                                        y_geo_min,
                                                    ),
                                                }
                                                all_boxes.append(geo_box)

                                    # Convert masks to individual polygons
                                    if export_polygons and np.any(prompt_mask):
                                        tile_polygons = self._mask_to_polygons(
                                            prompt_mask,
                                            transform,
                                            x_start,
                                            y_start,
                                            min_polygon_area,
                                            simplify_tolerance,
                                        )

                                        # Add metadata to polygons
                                        for poly_data in tile_polygons:
                                            poly_data.update(
                                                {
                                                    "label": prompt,
                                                    "score": max(
                                                        [
                                                            d.score
                                                            for d in detections
                                                            if d.label.replace(
                                                                ".", ""
                                                            )
                                                            .strip()
                                                            .lower()
                                                            == prompt.lower()
                                                        ],
                                                        default=0.0,
                                                    ),
                                                    "tile_x": x,
                                                    "tile_y": y,
                                                }
                                            )
                                            all_polygons.append(poly_data)

                                    # Store mask in the global array
                                    valid_x_start = self.overlap if x > 0 else 0
                                    valid_y_start = self.overlap if y > 0 else 0
                                    valid_x_end = (
                                        tile_width - self.overlap
                                        if x < n_tiles_x - 1
                                        else tile_width
                                    )
                                    valid_y_end = (
                                        tile_height - self.overlap
                                        if y < n_tiles_y - 1
                                        else tile_height
                                    )

                                    dest_x_start = x_start + valid_x_start
                                    dest_y_start = y_start + valid_y_start
                                    dest_x_end = x_start + valid_x_end
                                    dest_y_end = y_start + valid_y_end

                                    mask_slice = prompt_mask[
                                        valid_y_start:valid_y_end,
                                        valid_x_start:valid_x_end,
                                    ]
                                    all_masks[
                                        i,
                                        dest_y_start:dest_y_end,
                                        dest_x_start:dest_x_end,
                                    ] = np.maximum(
                                        all_masks[
                                            i,
                                            dest_y_start:dest_y_end,
                                            dest_x_start:dest_x_end,
                                        ],
                                        mask_slice,
                                    )

                    except Exception as e:
                        print(f"Error processing tile at ({x}, {y}): {str(e)}")
                        continue

                    # Update progress bar
                    pbar.update(1)

        # Create combined mask (union of all individual masks)
        combined_mask = np.any(all_masks, axis=0).astype(np.uint8)

        # Write the output GeoTIFF
        with rasterio.open(output_path, "w", **out_meta) as dst:
            # Write combined mask as first band
            dst.write(combined_mask, 1)

            # Write individual masks for each prompt
            for i, mask in enumerate(all_masks):
                dst.write(mask, i + 2)

            # Add descriptions to bands
            dst.set_band_description(1, "Combined Segmentation")
            for i, prompt in enumerate(text_prompts):
                dst.set_band_description(i + 2, f"Segmentation: {prompt}")

        result_files = {"segmentation": output_path}

        # Export bounding boxes if requested
        if export_boxes and all_boxes:
            boxes_path = output_path.replace(".tif", "_boxes.geojson")
            gdf = gpd.GeoDataFrame(all_boxes, crs=crs)
            gdf.to_file(boxes_path, driver="GeoJSON")
            result_files["boxes"] = boxes_path
            print(f"Exported {len(all_boxes)} bounding boxes to {boxes_path}")

        # Export instance polygons if requested
        if export_polygons and all_polygons:
            polygons_path = output_path.replace(".tif", "_polygons.geojson")
            gdf = gpd.GeoDataFrame(all_polygons, crs=crs)
            gdf.to_file(polygons_path, driver="GeoJSON")
            result_files["polygons"] = polygons_path
            print(
                f"Exported {len(all_polygons)} instance polygons to {polygons_path}"
            )

        print(f"Segmentation saved to {output_path}")
        print(
            f"Found {len(all_polygons)} individual building instances"
            if export_polygons
            else ""
        )

        return result_files