Skip to content

auto module

Auto classes for geospatial model inference with GeoTIFF support.

This module provides AutoGeoModel and AutoGeoImageProcessor that extend Hugging Face transformers' AutoModel and AutoImageProcessor to support processing geospatial data (GeoTIFF) and saving outputs as GeoTIFF or vector data.

Supported tasks
  • Semantic segmentation (e.g., SegFormer, Mask2Former)
  • Image classification (e.g., ViT, ResNet)
  • Object detection (e.g., DETR, YOLOS)
  • Zero-shot object detection (e.g., Grounding DINO, OWL-ViT)
  • Depth estimation (e.g., Depth Anything, DPT)
  • Mask generation (e.g., SAM)
Example

from geoai import AutoGeoModel model = AutoGeoModel.from_pretrained( ... "nvidia/segformer-b0-finetuned-ade-512-512", ... task="semantic-segmentation" ... ) result = model.predict("input.tif", output_path="output.tif")

AutoGeoImageProcessor

Image processor for geospatial data that wraps AutoImageProcessor.

This class provides functionality to load and preprocess GeoTIFF images while preserving geospatial metadata (CRS, transform, bounds). It wraps Hugging Face's AutoImageProcessor and adds geospatial capabilities.

Use from_pretrained to instantiate this class, following the transformers pattern.

Attributes:

Name Type Description
processor

The underlying AutoImageProcessor instance.

device str

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

Example

processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base") data, metadata = processor.load_geotiff("input.tif") inputs = processor(data)

Source code in geoai/auto.py
 61
 62
 63
 64
 65
 66
 67
 68
 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
class AutoGeoImageProcessor:
    """
    Image processor for geospatial data that wraps AutoImageProcessor.

    This class provides functionality to load and preprocess GeoTIFF images
    while preserving geospatial metadata (CRS, transform, bounds). It wraps
    Hugging Face's AutoImageProcessor and adds geospatial capabilities.

    Use `from_pretrained` to instantiate this class, following the transformers pattern.

    Attributes:
        processor: The underlying AutoImageProcessor instance.
        device (str): The device being used ('cuda' or 'cpu').

    Example:
        >>> processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base")
        >>> data, metadata = processor.load_geotiff("input.tif")
        >>> inputs = processor(data)
    """

    def __init__(
        self,
        processor: "AutoImageProcessor",
        processor_name: Optional[str] = None,
        device: Optional[str] = None,
    ) -> None:
        """Initialize the AutoGeoImageProcessor with an existing processor.

        Note: Use `from_pretrained` class method to load from Hugging Face Hub.

        Args:
            processor: An AutoImageProcessor instance.
            processor_name: Name or path of the processor (for reference).
            device: Device to use ('cuda', 'cpu'). If None, auto-detect.
        """
        self.processor = processor
        self.processor_name = processor_name

        if device is None:
            self.device = get_device()
        else:
            self.device = device

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: str,
        device: Optional[str] = None,
        use_full_processor: bool = False,
        **kwargs: Any,
    ) -> "AutoGeoImageProcessor":
        """Load an AutoGeoImageProcessor from a pretrained processor.

        This method wraps AutoImageProcessor.from_pretrained and adds
        geospatial capabilities for processing GeoTIFF files.

        Args:
            pretrained_model_name_or_path: Hugging Face model/processor name or local path.
                Can be a model ID from huggingface.co or a local directory path.
            device: Device to use ('cuda', 'cpu'). If None, auto-detect.
            use_full_processor: If True, use AutoProcessor instead of AutoImageProcessor.
                Required for models that need text inputs (e.g., Grounding DINO).
            **kwargs: Additional arguments passed to AutoImageProcessor.from_pretrained.
                Common options include:
                - trust_remote_code (bool): Whether to trust remote code.
                - revision (str): Specific model version to use.
                - use_fast (bool): Whether to use fast tokenizer.

        Returns:
            AutoGeoImageProcessor instance with geospatial support.

        Example:
            >>> processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base")
            >>> processor = AutoGeoImageProcessor.from_pretrained(
            ...     "nvidia/segformer-b0-finetuned-ade-512-512",
            ...     device="cuda"
            ... )
        """
        # Check if this is a model that needs the full processor (text + image)
        model_name_lower = pretrained_model_name_or_path.lower()
        needs_full_processor = use_full_processor or any(
            name in model_name_lower
            for name in ["grounding-dino", "owl", "clip", "blip"]
        )

        if needs_full_processor:
            processor = AutoProcessor.from_pretrained(
                pretrained_model_name_or_path, **kwargs
            )
        else:
            try:
                processor = AutoImageProcessor.from_pretrained(
                    pretrained_model_name_or_path, **kwargs
                )
            except Exception:
                processor = AutoProcessor.from_pretrained(
                    pretrained_model_name_or_path, **kwargs
                )
        return cls(
            processor=processor,
            processor_name=pretrained_model_name_or_path,
            device=device,
        )

    def load_geotiff(
        self,
        source: Union[str, "rasterio.DatasetReader"],
        window: Optional[Window] = None,
        bands: Optional[List[int]] = None,
    ) -> Tuple[np.ndarray, Dict]:
        """Load a GeoTIFF file and return data with metadata.

        Args:
            source: Path to GeoTIFF file or open rasterio DatasetReader.
            window: Optional rasterio Window for reading a subset.
            bands: List of band indices to read (1-indexed). If None, read all bands.

        Returns:
            Tuple of (image array in CHW format, metadata dict).

        Example:
            >>> processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base")
            >>> data, metadata = processor.load_geotiff("input.tif")
            >>> print(data.shape)  # (C, H, W)
            >>> print(metadata['crs'])  # CRS info
        """
        should_close = False
        if isinstance(source, str):
            src = rasterio.open(source)
            should_close = True
        else:
            src = source

        try:
            # Read specified bands or all bands
            if bands:
                data = src.read(bands, window=window)
            else:
                data = src.read(window=window)

            # Get profile and update for window
            profile = src.profile.copy()
            if window:
                profile.update(
                    {
                        "height": window.height,
                        "width": window.width,
                        "transform": src.window_transform(window),
                    }
                )

            metadata = {
                "profile": profile,
                "crs": src.crs,
                "transform": profile["transform"],
                "bounds": (
                    src.bounds
                    if not window
                    else rasterio.windows.bounds(window, src.transform)
                ),
                "width": profile["width"],
                "height": profile["height"],
                "count": data.shape[0],
            }

        finally:
            if should_close:
                src.close()

        return data, metadata

    def load_image(
        self,
        source: Union[str, np.ndarray, Image.Image],
        window: Optional[Window] = None,
        bands: Optional[List[int]] = None,
    ) -> Tuple[np.ndarray, Optional[Dict]]:
        """Load an image from various sources.

        Args:
            source: Path to image file, numpy array, or PIL Image.
            window: Optional rasterio Window (only for GeoTIFF).
            bands: List of band indices (only for GeoTIFF, 1-indexed).

        Returns:
            Tuple of (image array in CHW format, metadata dict or None).
        """
        if isinstance(source, str):
            # Check if GeoTIFF
            try:
                with rasterio.open(source) as src:
                    if src.crs is not None or source.lower().endswith(
                        (".tif", ".tiff")
                    ):
                        return self.load_geotiff(source, window, bands)
            except (rasterio.RasterioIOError, rasterio.errors.RasterioIOError):
                # If opening as GeoTIFF fails, fall back to loading as a regular image.
                pass

            # Load as regular image
            image = Image.open(source).convert("RGB")
            data = np.array(image).transpose(2, 0, 1)  # HWC -> CHW
            return data, None

        elif isinstance(source, np.ndarray):
            # Ensure CHW format
            if source.ndim == 2:
                source = source[np.newaxis, :, :]
            elif source.ndim == 3 and source.shape[2] in [1, 3, 4]:
                source = source.transpose(2, 0, 1)
            return source, None

        elif isinstance(source, Image.Image):
            data = np.array(source.convert("RGB")).transpose(2, 0, 1)
            return data, None

        else:
            raise TypeError(f"Unsupported source type: {type(source)}")

    def prepare_for_model(
        self,
        data: np.ndarray,
        normalize: bool = True,
        to_rgb: bool = True,
        percentile_clip: bool = True,
        return_tensors: str = "pt",
    ) -> Dict[str, Any]:
        """Prepare image data for model input.

        Args:
            data: Image array in CHW format.
            normalize: Whether to normalize pixel values.
            to_rgb: Whether to convert to 3-channel RGB.
            percentile_clip: Whether to use percentile clipping for normalization.
            return_tensors: Return format ('pt' for PyTorch, 'np' for numpy).

        Returns:
            Dictionary with processed inputs ready for model.
        """
        # Convert to HWC format
        if data.ndim == 3:
            img = data.transpose(1, 2, 0)  # CHW -> HWC
        else:
            img = data

        # Handle different band counts
        if img.ndim == 2:
            img = np.stack([img] * 3, axis=-1)
        elif img.shape[-1] == 1:
            img = np.repeat(img, 3, axis=-1)
        elif img.shape[-1] > 3:
            img = img[..., :3]

        # Normalize
        if normalize:
            if percentile_clip:
                for i in range(img.shape[-1]):
                    band = img[..., i]
                    p2, p98 = np.percentile(band, [2, 98])
                    if p98 > p2:
                        img[..., i] = np.clip((band - p2) / (p98 - p2), 0, 1)
                    else:
                        img[..., i] = 0
                img = (img * 255).astype(np.uint8)
            elif img.dtype != np.uint8:
                img = ((img - img.min()) / (img.max() - img.min()) * 255).astype(
                    np.uint8
                )

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

        # Process with transformers processor
        inputs = self.processor(images=pil_image, return_tensors=return_tensors)

        return inputs

    def __call__(
        self,
        images: Union[str, np.ndarray, Image.Image, List],
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Process images for model input.

        Args:
            images: Single image or list of images (paths, arrays, or PIL Images).
            **kwargs: Additional arguments passed to the processor.

        Returns:
            Processed inputs ready for model.
        """
        if isinstance(images, (str, np.ndarray, Image.Image)):
            images = [images]

        all_pil_images = []
        for img in images:
            if isinstance(img, str):
                data, _ = self.load_image(img)
            elif isinstance(img, np.ndarray):
                data = img
                if data.ndim == 3 and data.shape[2] in [1, 3, 4]:
                    data = data.transpose(2, 0, 1)
            else:
                data = np.array(img.convert("RGB")).transpose(2, 0, 1)

            # Prepare PIL image
            if data.ndim == 3:
                img_arr = data.transpose(1, 2, 0)
            else:
                img_arr = data

            if img_arr.ndim == 2:
                img_arr = np.stack([img_arr] * 3, axis=-1)
            elif img_arr.shape[-1] == 1:
                img_arr = np.repeat(img_arr, 3, axis=-1)
            elif img_arr.shape[-1] > 3:
                img_arr = img_arr[..., :3]

            # Normalize to uint8 if needed
            if img_arr.dtype != np.uint8:
                for i in range(img_arr.shape[-1]):
                    band = img_arr[..., i]
                    p2, p98 = np.percentile(band, [2, 98])
                    if p98 > p2:
                        img_arr[..., i] = np.clip((band - p2) / (p98 - p2), 0, 1)
                    else:
                        img_arr[..., i] = 0
                img_arr = (img_arr * 255).astype(np.uint8)

            all_pil_images.append(Image.fromarray(img_arr))

        return self.processor(images=all_pil_images, **kwargs)

    def save_geotiff(
        self,
        data: np.ndarray,
        output_path: str,
        metadata: Dict,
        dtype: Optional[str] = None,
        compress: str = "lzw",
        nodata: Optional[float] = None,
    ) -> str:
        """Save array as GeoTIFF with geospatial metadata.

        Args:
            data: Array to save (2D or 3D in CHW format).
            output_path: Output file path.
            metadata: Metadata dictionary from load_geotiff.
            dtype: Output data type. If None, infer from data.
            compress: Compression method.
            nodata: NoData value.

        Returns:
            Path to saved file.
        """
        profile = metadata["profile"].copy()

        if dtype is None:
            dtype = str(data.dtype)

        # Handle 2D vs 3D arrays
        if data.ndim == 2:
            count = 1
            height, width = data.shape
        else:
            count = data.shape[0]
            height, width = data.shape[1], data.shape[2]

        profile.update(
            {
                "dtype": dtype,
                "count": count,
                "height": height,
                "width": width,
                "compress": compress,
            }
        )

        if nodata is not None:
            profile["nodata"] = nodata

        os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)

        with rasterio.open(output_path, "w", **profile) as dst:
            if data.ndim == 2:
                dst.write(data, 1)
            else:
                dst.write(data)

        return output_path

__call__(images, **kwargs)

Process images for model input.

Parameters:

Name Type Description Default
images Union[str, ndarray, Image, List]

Single image or list of images (paths, arrays, or PIL Images).

required
**kwargs Any

Additional arguments passed to the processor.

{}

Returns:

Type Description
Dict[str, Any]

Processed inputs ready for model.

Source code in geoai/auto.py
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
def __call__(
    self,
    images: Union[str, np.ndarray, Image.Image, List],
    **kwargs: Any,
) -> Dict[str, Any]:
    """Process images for model input.

    Args:
        images: Single image or list of images (paths, arrays, or PIL Images).
        **kwargs: Additional arguments passed to the processor.

    Returns:
        Processed inputs ready for model.
    """
    if isinstance(images, (str, np.ndarray, Image.Image)):
        images = [images]

    all_pil_images = []
    for img in images:
        if isinstance(img, str):
            data, _ = self.load_image(img)
        elif isinstance(img, np.ndarray):
            data = img
            if data.ndim == 3 and data.shape[2] in [1, 3, 4]:
                data = data.transpose(2, 0, 1)
        else:
            data = np.array(img.convert("RGB")).transpose(2, 0, 1)

        # Prepare PIL image
        if data.ndim == 3:
            img_arr = data.transpose(1, 2, 0)
        else:
            img_arr = data

        if img_arr.ndim == 2:
            img_arr = np.stack([img_arr] * 3, axis=-1)
        elif img_arr.shape[-1] == 1:
            img_arr = np.repeat(img_arr, 3, axis=-1)
        elif img_arr.shape[-1] > 3:
            img_arr = img_arr[..., :3]

        # Normalize to uint8 if needed
        if img_arr.dtype != np.uint8:
            for i in range(img_arr.shape[-1]):
                band = img_arr[..., i]
                p2, p98 = np.percentile(band, [2, 98])
                if p98 > p2:
                    img_arr[..., i] = np.clip((band - p2) / (p98 - p2), 0, 1)
                else:
                    img_arr[..., i] = 0
            img_arr = (img_arr * 255).astype(np.uint8)

        all_pil_images.append(Image.fromarray(img_arr))

    return self.processor(images=all_pil_images, **kwargs)

__init__(processor, processor_name=None, device=None)

Initialize the AutoGeoImageProcessor with an existing processor.

Note: Use from_pretrained class method to load from Hugging Face Hub.

Parameters:

Name Type Description Default
processor AutoImageProcessor

An AutoImageProcessor instance.

required
processor_name Optional[str]

Name or path of the processor (for reference).

None
device Optional[str]

Device to use ('cuda', 'cpu'). If None, auto-detect.

None
Source code in geoai/auto.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def __init__(
    self,
    processor: "AutoImageProcessor",
    processor_name: Optional[str] = None,
    device: Optional[str] = None,
) -> None:
    """Initialize the AutoGeoImageProcessor with an existing processor.

    Note: Use `from_pretrained` class method to load from Hugging Face Hub.

    Args:
        processor: An AutoImageProcessor instance.
        processor_name: Name or path of the processor (for reference).
        device: Device to use ('cuda', 'cpu'). If None, auto-detect.
    """
    self.processor = processor
    self.processor_name = processor_name

    if device is None:
        self.device = get_device()
    else:
        self.device = device

from_pretrained(pretrained_model_name_or_path, device=None, use_full_processor=False, **kwargs) classmethod

Load an AutoGeoImageProcessor from a pretrained processor.

This method wraps AutoImageProcessor.from_pretrained and adds geospatial capabilities for processing GeoTIFF files.

Parameters:

Name Type Description Default
pretrained_model_name_or_path str

Hugging Face model/processor name or local path. Can be a model ID from huggingface.co or a local directory path.

required
device Optional[str]

Device to use ('cuda', 'cpu'). If None, auto-detect.

None
use_full_processor bool

If True, use AutoProcessor instead of AutoImageProcessor. Required for models that need text inputs (e.g., Grounding DINO).

False
**kwargs Any

Additional arguments passed to AutoImageProcessor.from_pretrained. Common options include: - trust_remote_code (bool): Whether to trust remote code. - revision (str): Specific model version to use. - use_fast (bool): Whether to use fast tokenizer.

{}

Returns:

Type Description
AutoGeoImageProcessor

AutoGeoImageProcessor instance with geospatial support.

Example

processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base") processor = AutoGeoImageProcessor.from_pretrained( ... "nvidia/segformer-b0-finetuned-ade-512-512", ... device="cuda" ... )

Source code in geoai/auto.py
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
@classmethod
def from_pretrained(
    cls,
    pretrained_model_name_or_path: str,
    device: Optional[str] = None,
    use_full_processor: bool = False,
    **kwargs: Any,
) -> "AutoGeoImageProcessor":
    """Load an AutoGeoImageProcessor from a pretrained processor.

    This method wraps AutoImageProcessor.from_pretrained and adds
    geospatial capabilities for processing GeoTIFF files.

    Args:
        pretrained_model_name_or_path: Hugging Face model/processor name or local path.
            Can be a model ID from huggingface.co or a local directory path.
        device: Device to use ('cuda', 'cpu'). If None, auto-detect.
        use_full_processor: If True, use AutoProcessor instead of AutoImageProcessor.
            Required for models that need text inputs (e.g., Grounding DINO).
        **kwargs: Additional arguments passed to AutoImageProcessor.from_pretrained.
            Common options include:
            - trust_remote_code (bool): Whether to trust remote code.
            - revision (str): Specific model version to use.
            - use_fast (bool): Whether to use fast tokenizer.

    Returns:
        AutoGeoImageProcessor instance with geospatial support.

    Example:
        >>> processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base")
        >>> processor = AutoGeoImageProcessor.from_pretrained(
        ...     "nvidia/segformer-b0-finetuned-ade-512-512",
        ...     device="cuda"
        ... )
    """
    # Check if this is a model that needs the full processor (text + image)
    model_name_lower = pretrained_model_name_or_path.lower()
    needs_full_processor = use_full_processor or any(
        name in model_name_lower
        for name in ["grounding-dino", "owl", "clip", "blip"]
    )

    if needs_full_processor:
        processor = AutoProcessor.from_pretrained(
            pretrained_model_name_or_path, **kwargs
        )
    else:
        try:
            processor = AutoImageProcessor.from_pretrained(
                pretrained_model_name_or_path, **kwargs
            )
        except Exception:
            processor = AutoProcessor.from_pretrained(
                pretrained_model_name_or_path, **kwargs
            )
    return cls(
        processor=processor,
        processor_name=pretrained_model_name_or_path,
        device=device,
    )

load_geotiff(source, window=None, bands=None)

Load a GeoTIFF file and return data with metadata.

Parameters:

Name Type Description Default
source Union[str, DatasetReader]

Path to GeoTIFF file or open rasterio DatasetReader.

required
window Optional[Window]

Optional rasterio Window for reading a subset.

None
bands Optional[List[int]]

List of band indices to read (1-indexed). If None, read all bands.

None

Returns:

Type Description
Tuple[ndarray, Dict]

Tuple of (image array in CHW format, metadata dict).

Example

processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base") data, metadata = processor.load_geotiff("input.tif") print(data.shape) # (C, H, W) print(metadata['crs']) # CRS info

Source code in geoai/auto.py
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
def load_geotiff(
    self,
    source: Union[str, "rasterio.DatasetReader"],
    window: Optional[Window] = None,
    bands: Optional[List[int]] = None,
) -> Tuple[np.ndarray, Dict]:
    """Load a GeoTIFF file and return data with metadata.

    Args:
        source: Path to GeoTIFF file or open rasterio DatasetReader.
        window: Optional rasterio Window for reading a subset.
        bands: List of band indices to read (1-indexed). If None, read all bands.

    Returns:
        Tuple of (image array in CHW format, metadata dict).

    Example:
        >>> processor = AutoGeoImageProcessor.from_pretrained("facebook/sam-vit-base")
        >>> data, metadata = processor.load_geotiff("input.tif")
        >>> print(data.shape)  # (C, H, W)
        >>> print(metadata['crs'])  # CRS info
    """
    should_close = False
    if isinstance(source, str):
        src = rasterio.open(source)
        should_close = True
    else:
        src = source

    try:
        # Read specified bands or all bands
        if bands:
            data = src.read(bands, window=window)
        else:
            data = src.read(window=window)

        # Get profile and update for window
        profile = src.profile.copy()
        if window:
            profile.update(
                {
                    "height": window.height,
                    "width": window.width,
                    "transform": src.window_transform(window),
                }
            )

        metadata = {
            "profile": profile,
            "crs": src.crs,
            "transform": profile["transform"],
            "bounds": (
                src.bounds
                if not window
                else rasterio.windows.bounds(window, src.transform)
            ),
            "width": profile["width"],
            "height": profile["height"],
            "count": data.shape[0],
        }

    finally:
        if should_close:
            src.close()

    return data, metadata

load_image(source, window=None, bands=None)

Load an image from various sources.

Parameters:

Name Type Description Default
source Union[str, ndarray, Image]

Path to image file, numpy array, or PIL Image.

required
window Optional[Window]

Optional rasterio Window (only for GeoTIFF).

None
bands Optional[List[int]]

List of band indices (only for GeoTIFF, 1-indexed).

None

Returns:

Type Description
Tuple[ndarray, Optional[Dict]]

Tuple of (image array in CHW format, metadata dict or None).

Source code in geoai/auto.py
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
def load_image(
    self,
    source: Union[str, np.ndarray, Image.Image],
    window: Optional[Window] = None,
    bands: Optional[List[int]] = None,
) -> Tuple[np.ndarray, Optional[Dict]]:
    """Load an image from various sources.

    Args:
        source: Path to image file, numpy array, or PIL Image.
        window: Optional rasterio Window (only for GeoTIFF).
        bands: List of band indices (only for GeoTIFF, 1-indexed).

    Returns:
        Tuple of (image array in CHW format, metadata dict or None).
    """
    if isinstance(source, str):
        # Check if GeoTIFF
        try:
            with rasterio.open(source) as src:
                if src.crs is not None or source.lower().endswith(
                    (".tif", ".tiff")
                ):
                    return self.load_geotiff(source, window, bands)
        except (rasterio.RasterioIOError, rasterio.errors.RasterioIOError):
            # If opening as GeoTIFF fails, fall back to loading as a regular image.
            pass

        # Load as regular image
        image = Image.open(source).convert("RGB")
        data = np.array(image).transpose(2, 0, 1)  # HWC -> CHW
        return data, None

    elif isinstance(source, np.ndarray):
        # Ensure CHW format
        if source.ndim == 2:
            source = source[np.newaxis, :, :]
        elif source.ndim == 3 and source.shape[2] in [1, 3, 4]:
            source = source.transpose(2, 0, 1)
        return source, None

    elif isinstance(source, Image.Image):
        data = np.array(source.convert("RGB")).transpose(2, 0, 1)
        return data, None

    else:
        raise TypeError(f"Unsupported source type: {type(source)}")

prepare_for_model(data, normalize=True, to_rgb=True, percentile_clip=True, return_tensors='pt')

Prepare image data for model input.

Parameters:

Name Type Description Default
data ndarray

Image array in CHW format.

required
normalize bool

Whether to normalize pixel values.

True
to_rgb bool

Whether to convert to 3-channel RGB.

True
percentile_clip bool

Whether to use percentile clipping for normalization.

True
return_tensors str

Return format ('pt' for PyTorch, 'np' for numpy).

'pt'

Returns:

Type Description
Dict[str, Any]

Dictionary with processed inputs ready for model.

Source code in geoai/auto.py
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
def prepare_for_model(
    self,
    data: np.ndarray,
    normalize: bool = True,
    to_rgb: bool = True,
    percentile_clip: bool = True,
    return_tensors: str = "pt",
) -> Dict[str, Any]:
    """Prepare image data for model input.

    Args:
        data: Image array in CHW format.
        normalize: Whether to normalize pixel values.
        to_rgb: Whether to convert to 3-channel RGB.
        percentile_clip: Whether to use percentile clipping for normalization.
        return_tensors: Return format ('pt' for PyTorch, 'np' for numpy).

    Returns:
        Dictionary with processed inputs ready for model.
    """
    # Convert to HWC format
    if data.ndim == 3:
        img = data.transpose(1, 2, 0)  # CHW -> HWC
    else:
        img = data

    # Handle different band counts
    if img.ndim == 2:
        img = np.stack([img] * 3, axis=-1)
    elif img.shape[-1] == 1:
        img = np.repeat(img, 3, axis=-1)
    elif img.shape[-1] > 3:
        img = img[..., :3]

    # Normalize
    if normalize:
        if percentile_clip:
            for i in range(img.shape[-1]):
                band = img[..., i]
                p2, p98 = np.percentile(band, [2, 98])
                if p98 > p2:
                    img[..., i] = np.clip((band - p2) / (p98 - p2), 0, 1)
                else:
                    img[..., i] = 0
            img = (img * 255).astype(np.uint8)
        elif img.dtype != np.uint8:
            img = ((img - img.min()) / (img.max() - img.min()) * 255).astype(
                np.uint8
            )

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

    # Process with transformers processor
    inputs = self.processor(images=pil_image, return_tensors=return_tensors)

    return inputs

save_geotiff(data, output_path, metadata, dtype=None, compress='lzw', nodata=None)

Save array as GeoTIFF with geospatial metadata.

Parameters:

Name Type Description Default
data ndarray

Array to save (2D or 3D in CHW format).

required
output_path str

Output file path.

required
metadata Dict

Metadata dictionary from load_geotiff.

required
dtype Optional[str]

Output data type. If None, infer from data.

None
compress str

Compression method.

'lzw'
nodata Optional[float]

NoData value.

None

Returns:

Type Description
str

Path to saved file.

Source code in geoai/auto.py
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
def save_geotiff(
    self,
    data: np.ndarray,
    output_path: str,
    metadata: Dict,
    dtype: Optional[str] = None,
    compress: str = "lzw",
    nodata: Optional[float] = None,
) -> str:
    """Save array as GeoTIFF with geospatial metadata.

    Args:
        data: Array to save (2D or 3D in CHW format).
        output_path: Output file path.
        metadata: Metadata dictionary from load_geotiff.
        dtype: Output data type. If None, infer from data.
        compress: Compression method.
        nodata: NoData value.

    Returns:
        Path to saved file.
    """
    profile = metadata["profile"].copy()

    if dtype is None:
        dtype = str(data.dtype)

    # Handle 2D vs 3D arrays
    if data.ndim == 2:
        count = 1
        height, width = data.shape
    else:
        count = data.shape[0]
        height, width = data.shape[1], data.shape[2]

    profile.update(
        {
            "dtype": dtype,
            "count": count,
            "height": height,
            "width": width,
            "compress": compress,
        }
    )

    if nodata is not None:
        profile["nodata"] = nodata

    os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)

    with rasterio.open(output_path, "w", **profile) as dst:
        if data.ndim == 2:
            dst.write(data, 1)
        else:
            dst.write(data)

    return output_path

AutoGeoModel

Auto model for geospatial inference with GeoTIFF support.

This class wraps Hugging Face transformers' AutoModel classes and adds geospatial capabilities for processing GeoTIFF images and saving results as georeferenced outputs (GeoTIFF or vector data).

Use from_pretrained to instantiate this class, following the transformers pattern.

Attributes:

Name Type Description
model

The underlying transformers model instance.

processor

AutoGeoImageProcessor for preprocessing.

device str

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

task str

The task type.

tile_size int

Size of tiles for processing large images.

overlap int

Overlap between tiles.

Example

model = AutoGeoModel.from_pretrained( ... "facebook/sam-vit-base", ... task="mask-generation" ... ) result = model.predict("input.tif", output_path="output.tif")

Source code in geoai/auto.py
 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
 736
 737
 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
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
class AutoGeoModel:
    """
    Auto model for geospatial inference with GeoTIFF support.

    This class wraps Hugging Face transformers' AutoModel classes and adds
    geospatial capabilities for processing GeoTIFF images and saving results
    as georeferenced outputs (GeoTIFF or vector data).

    Use `from_pretrained` to instantiate this class, following the transformers pattern.

    Attributes:
        model: The underlying transformers model instance.
        processor: AutoGeoImageProcessor for preprocessing.
        device (str): The device being used ('cuda' or 'cpu').
        task (str): The task type.
        tile_size (int): Size of tiles for processing large images.
        overlap (int): Overlap between tiles.

    Example:
        >>> model = AutoGeoModel.from_pretrained(
        ...     "facebook/sam-vit-base",
        ...     task="mask-generation"
        ... )
        >>> result = model.predict("input.tif", output_path="output.tif")
    """

    TASK_MODEL_MAPPING = {
        "segmentation": AutoModelForSemanticSegmentation,
        "semantic-segmentation": AutoModelForSemanticSegmentation,
        "image-segmentation": AutoModelForImageSegmentation,
        "universal-segmentation": AutoModelForUniversalSegmentation,
        "depth-estimation": AutoModelForDepthEstimation,
        "mask-generation": AutoModelForMaskGeneration,
        "object-detection": AutoModelForObjectDetection,
        "zero-shot-object-detection": AutoModelForZeroShotObjectDetection,
        "classification": AutoModelForImageClassification,
        "image-classification": AutoModelForImageClassification,
    }

    def __init__(
        self,
        model: torch.nn.Module,
        processor: Optional["AutoGeoImageProcessor"] = None,
        model_name: Optional[str] = None,
        task: Optional[str] = None,
        device: Optional[str] = None,
        tile_size: int = 1024,
        overlap: int = 128,
    ) -> None:
        """Initialize AutoGeoModel with an existing model.

        Note: Use `from_pretrained` class method to load from Hugging Face Hub.

        Args:
            model: A transformers model instance.
            processor: An AutoGeoImageProcessor instance (optional).
            model_name: Name or path of the model (for reference).
            task: Task type for the model.
            device: Device to use ('cuda', 'cpu'). If None, auto-detect.
            tile_size: Size of tiles for processing large images.
            overlap: Overlap between tiles.
        """
        self.model = model
        self.processor = processor
        self.model_name = model_name
        self.task = task
        self.tile_size = tile_size
        self.overlap = overlap

        if device is None:
            self.device = get_device()
        else:
            self.device = device

        # Ensure model is on the correct device and in eval mode
        self.model = self.model.to(self.device)
        self.model.eval()

    @classmethod
    def from_pretrained(
        cls,
        pretrained_model_name_or_path: str,
        task: Optional[str] = None,
        device: Optional[str] = None,
        tile_size: int = 1024,
        overlap: int = 128,
        **kwargs: Any,
    ) -> "AutoGeoModel":
        """Load an AutoGeoModel from a pretrained model.

        This method wraps transformers' AutoModel.from_pretrained and adds
        geospatial capabilities for processing GeoTIFF files.

        Args:
            pretrained_model_name_or_path: Hugging Face model name or local path.
                Can be a model ID from huggingface.co or a local directory path.
            task: Task type for automatic model class selection. Options:
                - 'segmentation' or 'semantic-segmentation': Semantic segmentation
                - 'image-segmentation': General image segmentation
                - 'universal-segmentation': Universal segmentation (Mask2Former, etc.)
                - 'depth-estimation': Depth estimation
                - 'mask-generation': Mask generation (SAM, etc.)
                - 'object-detection': Object detection
                - 'zero-shot-object-detection': Zero-shot object detection
                - 'classification' or 'image-classification': Image classification
                If None, will try to infer from model config.
            device: Device to use ('cuda', 'cpu'). If None, auto-detect.
            tile_size: Size of tiles for processing large images.
            overlap: Overlap between tiles to avoid edge artifacts.
            **kwargs: Additional arguments passed to the model's from_pretrained.
                Common options include:
                - trust_remote_code (bool): Whether to trust remote code.
                - revision (str): Specific model version to use.
                - torch_dtype: Data type for model weights.

        Returns:
            AutoGeoModel instance with geospatial support.

        Example:
            >>> model = AutoGeoModel.from_pretrained("facebook/sam-vit-base", task="mask-generation")
            >>> model = AutoGeoModel.from_pretrained(
            ...     "nvidia/segformer-b0-finetuned-ade-512-512",
            ...     task="semantic-segmentation",
            ...     device="cuda"
            ... )
        """
        # Determine device
        if device is None:
            device = get_device()

        # Load model using appropriate auto class
        model = cls._load_model_from_pretrained(
            pretrained_model_name_or_path, task, **kwargs
        )

        # Load processor - use full processor for models that need text inputs
        needs_full_processor = task in (
            "zero-shot-object-detection",
            "object-detection",
        )
        try:
            processor = AutoGeoImageProcessor.from_pretrained(
                pretrained_model_name_or_path,
                device=device,
                use_full_processor=needs_full_processor,
            )
        except Exception:
            processor = None

        instance = cls(
            model=model,
            processor=processor,
            model_name=pretrained_model_name_or_path,
            task=task,
            device=device,
            tile_size=tile_size,
            overlap=overlap,
        )

        print(f"Model loaded on {device}")
        return instance

    @classmethod
    def _load_model_from_pretrained(
        cls,
        model_name_or_path: str,
        task: Optional[str] = None,
        **kwargs: Any,
    ) -> torch.nn.Module:
        """Load the appropriate model based on task using from_pretrained."""
        if task and task in cls.TASK_MODEL_MAPPING:
            model_class = cls.TASK_MODEL_MAPPING[task]
            return model_class.from_pretrained(model_name_or_path, **kwargs)

        # Try to infer from config
        try:
            config = AutoConfig.from_pretrained(model_name_or_path)
            architectures = getattr(config, "architectures", [])

            if any("Segmentation" in arch for arch in architectures):
                return AutoModelForSemanticSegmentation.from_pretrained(
                    model_name_or_path, **kwargs
                )
            elif any("Detection" in arch for arch in architectures):
                return AutoModelForObjectDetection.from_pretrained(
                    model_name_or_path, **kwargs
                )
            elif any("Classification" in arch for arch in architectures):
                return AutoModelForImageClassification.from_pretrained(
                    model_name_or_path, **kwargs
                )
            else:
                return AutoModel.from_pretrained(model_name_or_path, **kwargs)
        except Exception:
            return AutoModel.from_pretrained(model_name_or_path, **kwargs)

    def predict(
        self,
        source: Union[str, np.ndarray, Image.Image],
        output_path: Optional[str] = None,
        output_vector_path: Optional[str] = None,
        window: Optional[Window] = None,
        bands: Optional[List[int]] = None,
        threshold: float = 0.5,
        text: Optional[str] = None,
        labels: Optional[List[str]] = None,
        box_threshold: float = 0.3,
        text_threshold: float = 0.25,
        min_object_area: int = 100,
        simplify_tolerance: float = 1.0,
        batch_size: int = 1,
        return_probabilities: bool = False,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Run inference on a GeoTIFF or image.

        Args:
            source: Input image (path, array, or PIL Image). Can also be a URL.
            output_path: Path to save output GeoTIFF.
            output_vector_path: Path to save output vector file (GeoJSON, GPKG, etc.).
            window: Optional rasterio Window for processing a subset.
            bands: List of band indices to use (1-indexed).
            threshold: Threshold for binary masks (segmentation tasks).
            text: Text prompt for zero-shot detection models (e.g., "a cat. a dog.").
                For Grounding DINO, labels should be lowercase and end with a dot.
            labels: List of labels to detect (alternative to text).
                Will be converted to text prompt format automatically.
            box_threshold: Confidence threshold for bounding boxes (detection tasks).
            text_threshold: Text similarity threshold for zero-shot detection.
            min_object_area: Minimum object area in pixels for vectorization.
            simplify_tolerance: Tolerance for polygon simplification.
            batch_size: Batch size for processing tiles.
            return_probabilities: Whether to return probability maps.
            **kwargs: Additional arguments for specific tasks.

        Returns:
            Dictionary with results including mask/detections, metadata, and optional vector data.

        Example:
            >>> # Zero-shot object detection
            >>> model = AutoGeoModel.from_pretrained(
            ...     "IDEA-Research/grounding-dino-base",
            ...     task="zero-shot-object-detection"
            ... )
            >>> result = model.predict(
            ...     "image.jpg",
            ...     text="a building. a car. a tree.",
            ...     box_threshold=0.3
            ... )
            >>> print(result["boxes"], result["labels"])
        """
        # Convert labels list to text format if provided
        if labels is not None and text is None:
            text = " ".join(f"{label.lower().strip()}." for label in labels)

        # Handle zero-shot object detection separately
        if self.task in ("zero-shot-object-detection", "object-detection"):
            return self._predict_detection(
                source,
                text=text,
                box_threshold=box_threshold,
                text_threshold=text_threshold,
                output_vector_path=output_vector_path,
                **kwargs,
            )

        # Load image (handles URLs, local files, arrays, PIL Images)
        pil_image = None
        if isinstance(source, str):
            # Check if URL
            if source.startswith(("http://", "https://")):
                pil_image = Image.open(requests.get(source, stream=True).raw)
                metadata = None
                data = np.array(pil_image.convert("RGB")).transpose(2, 0, 1)
            else:
                # Local file - try to load with geospatial info
                if self.processor is not None:
                    data, metadata = self.processor.load_image(source, window, bands)
                else:
                    try:
                        with rasterio.open(source) as src:
                            data = src.read(bands) if bands else src.read()
                            profile = src.profile.copy()
                            metadata = {
                                "profile": profile,
                                "crs": src.crs,
                                "transform": src.transform,
                                "bounds": src.bounds,
                                "width": src.width,
                                "height": src.height,
                            }
                    except Exception:
                        # Fall back to PIL for regular images
                        pil_image = Image.open(source).convert("RGB")
                        data = np.array(pil_image).transpose(2, 0, 1)
                        metadata = None
        elif isinstance(source, Image.Image):
            pil_image = source
            data = np.array(source.convert("RGB")).transpose(2, 0, 1)
            metadata = None
        else:
            data = np.array(source)
            if data.ndim == 3 and data.shape[2] in [1, 3, 4]:
                data = data.transpose(2, 0, 1)
            metadata = None

        # Check if we need tiled processing (not for classification tasks)
        if data.ndim == 3:
            _, height, width = data.shape
        elif data.ndim == 2:
            height, width = data.shape
            _ = 1
        else:
            raise ValueError(f"Unexpected data shape: {data.shape}")

        # Classification tasks should not use tiled processing
        use_tiled = (
            height > self.tile_size or width > self.tile_size
        ) and self.task not in ("classification", "image-classification")

        if use_tiled:
            result = self._predict_tiled(
                source,
                data,
                metadata,
                threshold=threshold,
                batch_size=batch_size,
                return_probabilities=return_probabilities,
                **kwargs,
            )
        else:
            result = self._predict_single(
                data,
                metadata,
                threshold=threshold,
                return_probabilities=return_probabilities,
                **kwargs,
            )

        # Save GeoTIFF output
        if output_path and metadata:
            self.save_geotiff(
                result.get("mask", result.get("output")),
                output_path,
                metadata,
                nodata=0,
            )
            result["output_path"] = output_path

        # Save vector output
        if output_vector_path and metadata and "mask" in result:
            gdf = self.mask_to_vector(
                result["mask"],
                metadata,
                threshold=threshold,
                min_object_area=min_object_area,
                simplify_tolerance=simplify_tolerance,
            )
            if gdf is not None and len(gdf) > 0:
                gdf.to_file(output_vector_path)
                result["vector_path"] = output_vector_path
                result["geodataframe"] = gdf

        return result

    def _predict_single(
        self,
        data: np.ndarray,
        metadata: Optional[Dict],
        threshold: float = 0.5,
        return_probabilities: bool = False,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Run inference on a single image."""
        # Prepare input
        if self.processor is not None:
            inputs = self.processor.prepare_for_model(data)
        else:
            # Fallback preparation
            img = data.transpose(1, 2, 0) if data.ndim == 3 else data
            if img.ndim == 2:
                img = np.stack([img] * 3, axis=-1)
            elif img.shape[-1] > 3:
                img = img[..., :3]

            if img.dtype != np.uint8:
                img = ((img - img.min()) / (img.max() - img.min()) * 255).astype(
                    np.uint8
                )

            pil_image = Image.fromarray(img)
            inputs = {
                "pixel_values": torch.from_numpy(
                    np.array(pil_image).transpose(2, 0, 1) / 255.0
                )
                .float()
                .unsqueeze(0)
            }

        # Move to device
        inputs = {
            k: v.to(self.device) if isinstance(v, torch.Tensor) else v
            for k, v in inputs.items()
        }

        # Run inference
        with torch.no_grad():
            outputs = self.model(**inputs)

        # Process outputs based on model type
        result = self._process_outputs(
            outputs, data.shape, threshold, return_probabilities
        )
        result["metadata"] = metadata

        return result

    def _predict_tiled(
        self,
        source: Union[str, np.ndarray],
        data: np.ndarray,
        metadata: Optional[Dict],
        threshold: float = 0.5,
        batch_size: int = 1,
        return_probabilities: bool = False,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Run tiled inference for large images."""
        if data.ndim == 3:
            _, height, width = data.shape
        else:
            height, width = data.shape

        effective_tile_size = self.tile_size - 2 * self.overlap

        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

        # Initialize output arrays
        mask_output = np.zeros((height, width), dtype=np.float32)
        count_output = np.zeros((height, width), dtype=np.float32)

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

        with tqdm(total=total_tiles, desc="Processing tiles") as pbar:
            for y in range(n_tiles_y):
                for x in range(n_tiles_x):
                    # Calculate tile coordinates
                    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)

                    # Extract tile
                    if data.ndim == 3:
                        tile = data[:, y_start:y_end, x_start:x_end]
                    else:
                        tile = data[y_start:y_end, x_start:x_end]

                    try:
                        # Run inference on tile
                        tile_result = self._predict_single(
                            tile, None, threshold, return_probabilities
                        )

                        tile_mask = tile_result.get("mask", tile_result.get("output"))
                        if tile_mask is not None:
                            # Handle different dimensions
                            if tile_mask.ndim > 2:
                                tile_mask = tile_mask.squeeze()
                            if tile_mask.ndim > 2:
                                tile_mask = tile_mask[0]

                            # Resize if necessary
                            tile_h, tile_w = y_end - y_start, x_end - x_start
                            if tile_mask.shape != (tile_h, tile_w):
                                tile_mask = cv2.resize(
                                    tile_mask.astype(np.float32),
                                    (tile_w, tile_h),
                                    interpolation=cv2.INTER_LINEAR,
                                )

                            # Add to output with blending
                            mask_output[y_start:y_end, x_start:x_end] += tile_mask
                            count_output[y_start:y_end, x_start:x_end] += 1

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

                    pbar.update(1)

        # Average overlapping regions
        count_output = np.maximum(count_output, 1)
        mask_output = mask_output / count_output

        result = {
            "mask": (mask_output > threshold).astype(np.uint8),
            "probabilities": mask_output if return_probabilities else None,
            "metadata": metadata,
        }

        return result

    def _predict_detection(
        self,
        source: Union[str, np.ndarray, Image.Image],
        text: Optional[str] = None,
        box_threshold: float = 0.3,
        text_threshold: float = 0.25,
        output_vector_path: Optional[str] = None,
        **kwargs: Any,
    ) -> Dict[str, Any]:
        """Run object detection inference.

        Args:
            source: Input image (path, URL, array, or PIL Image).
            text: Text prompt for zero-shot detection (e.g., "a cat. a dog.").
            box_threshold: Confidence threshold for bounding boxes.
            text_threshold: Text similarity threshold for zero-shot detection.
            output_vector_path: Path to save detection results as vector file.
            **kwargs: Additional arguments.

        Returns:
            Dictionary with boxes, scores, labels, and optional GeoDataFrame.
        """
        # Load image
        if isinstance(source, str):
            if source.startswith(("http://", "https://")):
                pil_image = Image.open(requests.get(source, stream=True).raw)
            else:
                try:
                    # Try loading with rasterio for GeoTIFF
                    with rasterio.open(source) as src:
                        data = src.read()
                        if data.shape[0] > 3:
                            data = data[:3]
                        elif data.shape[0] == 1:
                            data = np.repeat(data, 3, axis=0)
                        # Normalize to uint8
                        if data.dtype != np.uint8:
                            for i in range(data.shape[0]):
                                band = data[i].astype(np.float32)
                                p2, p98 = np.percentile(band, [2, 98])
                                if p98 > p2:
                                    data[i] = np.clip(
                                        (band - p2) / (p98 - p2) * 255, 0, 255
                                    )
                                else:
                                    data[i] = 0
                            data = data.astype(np.uint8)
                        pil_image = Image.fromarray(data.transpose(1, 2, 0))
                except Exception:
                    pil_image = Image.open(source)
        elif isinstance(source, np.ndarray):
            if source.ndim == 3 and source.shape[0] in [1, 3, 4]:
                source = source.transpose(1, 2, 0)
            if source.dtype != np.uint8:
                source = (
                    (source - source.min()) / (source.max() - source.min()) * 255
                ).astype(np.uint8)
            pil_image = Image.fromarray(source)
        else:
            pil_image = source

        pil_image = pil_image.convert("RGB")
        image_size = pil_image.size[::-1]  # (height, width)

        # Get the underlying processor
        processor = self.processor.processor if self.processor else None
        if processor is None:
            # Load processor directly if not available
            processor = AutoProcessor.from_pretrained(self.model_name)

        # Prepare inputs based on task type
        if self.task == "zero-shot-object-detection":
            if text is None:
                raise ValueError(
                    "Text prompt is required for zero-shot object detection. "
                    "Provide text='a cat. a dog.' or labels=['cat', 'dog']"
                )
            # Use the processor to prepare inputs with text
            inputs = processor(images=pil_image, text=text, return_tensors="pt")
        else:
            # Standard object detection
            inputs = processor(images=pil_image, return_tensors="pt")

        # Move to device - use .to() method for BatchFeature objects
        inputs = inputs.to(self.device)

        # Run inference
        with torch.no_grad():
            outputs = self.model(**inputs)

        # Post-process results
        result = self._process_detection_outputs(
            outputs,
            inputs,
            text,
            image_size,
            box_threshold,
            text_threshold,
            processor,
        )

        # Convert to GeoDataFrame if requested
        if output_vector_path and result.get("boxes") is not None:
            gdf = self._detections_to_geodataframe(result, pil_image.size)
            if gdf is not None and len(gdf) > 0:
                gdf.to_file(output_vector_path)
                result["vector_path"] = output_vector_path
                result["geodataframe"] = gdf

        return result

    def _process_detection_outputs(
        self,
        outputs: Any,
        inputs: Dict,
        text: Optional[str],
        image_size: Tuple[int, int],
        box_threshold: float,
        text_threshold: float,
        processor: Any = None,
    ) -> Dict[str, Any]:
        """Process detection model outputs."""
        result = {}

        if processor is None:
            processor = self.processor.processor if self.processor else None

        if self.task == "zero-shot-object-detection":
            # Use processor's post-processing for grounded detection
            try:
                results = processor.post_process_grounded_object_detection(
                    outputs,
                    inputs["input_ids"],
                    threshold=box_threshold,  # box confidence threshold
                    text_threshold=text_threshold,
                    target_sizes=[image_size],
                )
                if results and len(results) > 0:
                    r = results[0]
                    result["boxes"] = r["boxes"].cpu().numpy()
                    result["scores"] = r["scores"].cpu().numpy()
                    # Handle different output formats for labels
                    if "labels" in r:
                        result["labels"] = r["labels"]
                    elif "text_labels" in r:
                        result["labels"] = r["text_labels"]
                    else:
                        # Extract labels from logits if not provided
                        result["labels"] = [
                            f"object_{i}" for i in range(len(r["boxes"]))
                        ]
            except Exception as e:
                # Fallback for models without grounded post-processing
                print(f"Warning: Using fallback detection processing: {e}")
                if hasattr(outputs, "pred_boxes"):
                    boxes = outputs.pred_boxes[0].cpu().numpy()
                    logits = outputs.logits[0].cpu()
                    scores = logits.sigmoid().max(dim=-1).values.numpy()
                    mask = scores > box_threshold
                    result["boxes"] = boxes[mask]
                    result["scores"] = scores[mask]
                    result["labels"] = [
                        f"object_{i}" for i in range(len(result["boxes"]))
                    ]
        else:
            # Standard object detection post-processing
            if hasattr(outputs, "pred_boxes") and processor is not None:
                target_sizes = torch.tensor([image_size], device=self.device)
                results = processor.post_process_object_detection(
                    outputs, threshold=box_threshold, target_sizes=target_sizes
                )
                if results and len(results) > 0:
                    r = results[0]
                    result["boxes"] = r["boxes"].cpu().numpy()
                    result["scores"] = r["scores"].cpu().numpy()
                    result["labels"] = r["labels"].cpu().numpy()

        return result

    def _detections_to_geodataframe(
        self,
        detections: Dict[str, Any],
        image_size: Tuple[int, int],
    ) -> Optional[gpd.GeoDataFrame]:
        """Convert detection results to a GeoDataFrame.

        Note: Without geospatial metadata, coordinates are in pixel space.
        """
        boxes = detections.get("boxes")
        if boxes is None or len(boxes) == 0:
            return None

        scores = detections.get("scores", [None] * len(boxes))
        labels = detections.get("labels", [None] * len(boxes))

        geometries = []
        for bbox in boxes:
            # Convert [x1, y1, x2, y2] to polygon
            x1, y1, x2, y2 = bbox
            geometries.append(box(x1, y1, x2, y2))

        gdf = gpd.GeoDataFrame(
            {
                "geometry": geometries,
                "score": scores,
                "label": labels,
            }
        )

        return gdf

    def _process_outputs(
        self,
        outputs: Any,
        input_shape: Tuple,
        threshold: float = 0.5,
        return_probabilities: bool = False,
    ) -> Dict[str, Any]:
        """Process model outputs to extract masks or predictions."""
        result = {}

        # Handle different output types
        if hasattr(outputs, "logits"):
            logits = outputs.logits
            if logits.dim() == 4:  # Segmentation output
                # Upsample if needed
                if logits.shape[2:] != input_shape[1:]:
                    logits = torch.nn.functional.interpolate(
                        logits,
                        size=(input_shape[1], input_shape[2]),
                        mode="bilinear",
                        align_corners=False,
                    )

                probs = torch.softmax(logits, dim=1)
                mask = probs.argmax(dim=1).squeeze().cpu().numpy()
                result["mask"] = mask.astype(np.uint8)

                if return_probabilities:
                    result["probabilities"] = probs.squeeze().cpu().numpy()

            elif logits.dim() == 2:  # Classification output
                probs = torch.softmax(logits, dim=-1)
                pred_class = probs.argmax(dim=-1).item()
                result["class"] = pred_class
                result["probabilities"] = probs.squeeze().cpu().numpy()

        elif hasattr(outputs, "pred_masks"):
            masks = outputs.pred_masks.squeeze().cpu().numpy()
            if masks.ndim == 3:
                mask = masks.max(axis=0)
            else:
                mask = masks
            result["mask"] = (mask > threshold).astype(np.uint8)

            if return_probabilities:
                result["probabilities"] = mask

        elif hasattr(outputs, "predicted_depth"):
            depth = outputs.predicted_depth.squeeze().cpu().numpy()
            result["output"] = depth
            result["depth"] = depth

        elif hasattr(outputs, "masks"):
            # SAM-like output
            masks = outputs.masks
            if isinstance(masks, torch.Tensor):
                masks = masks.cpu().numpy()
            if masks.ndim == 4:
                masks = masks.squeeze(0)
            if masks.ndim == 3:
                mask = masks.max(axis=0)
            else:
                mask = masks
            result["mask"] = (mask > threshold).astype(np.uint8)
            result["all_masks"] = masks

        else:
            # Generic output handling
            if hasattr(outputs, "last_hidden_state"):
                result["features"] = outputs.last_hidden_state.cpu().numpy()
            else:
                result["output"] = outputs

        return result

    def mask_to_vector(
        self,
        mask: np.ndarray,
        metadata: Dict,
        threshold: float = 0.5,
        min_object_area: int = 100,
        max_object_area: Optional[int] = None,
        simplify_tolerance: float = 1.0,
    ) -> Optional[gpd.GeoDataFrame]:
        """Convert a raster mask to vector polygons.

        Args:
            mask: Binary or probability mask array.
            metadata: Geospatial metadata dictionary.
            threshold: Threshold for binarizing probability masks.
            min_object_area: Minimum area in pixels for valid objects.
            max_object_area: Maximum area in pixels (optional).
            simplify_tolerance: Tolerance for polygon simplification.

        Returns:
            GeoDataFrame with polygon geometries, or None if no valid polygons.
        """
        if metadata is None or metadata.get("crs") is None:
            print("Warning: No CRS information available for vectorization")
            return None

        # Ensure binary mask
        if mask.dtype == np.float32 or mask.dtype == np.float64:
            mask = (mask > threshold).astype(np.uint8)
        else:
            mask = (mask > 0).astype(np.uint8)

        # Get transform
        transform = metadata.get("transform")
        crs = metadata.get("crs")

        if transform is None:
            print("Warning: No transform available for vectorization")
            return None

        # Extract shapes using rasterio
        polygons = []
        values = []

        try:
            for geom, value in shapes(mask, transform=transform):
                if value > 0:  # Only keep non-background
                    poly = shape(geom)

                    # Filter by area
                    pixel_area = poly.area / (transform.a * abs(transform.e))
                    if pixel_area < min_object_area:
                        continue
                    if max_object_area and pixel_area > max_object_area:
                        continue

                    # Simplify
                    if simplify_tolerance > 0:
                        poly = poly.simplify(
                            simplify_tolerance * abs(transform.a),
                            preserve_topology=True,
                        )

                    if poly.is_valid and not poly.is_empty:
                        polygons.append(poly)
                        values.append(value)

        except Exception as e:
            print(f"Error during vectorization: {e}")
            return None

        if not polygons:
            return None

        # Create GeoDataFrame
        gdf = gpd.GeoDataFrame(
            {"geometry": polygons, "class": values},
            crs=crs,
        )

        return gdf

    def save_geotiff(
        self,
        data: np.ndarray,
        output_path: str,
        metadata: Dict,
        dtype: Optional[str] = None,
        compress: str = "lzw",
        nodata: Optional[float] = None,
    ) -> str:
        """Save array as GeoTIFF with geospatial metadata.

        Args:
            data: Array to save (2D or 3D in CHW format).
            output_path: Output file path.
            metadata: Metadata dictionary from load_geotiff.
            dtype: Output data type. If None, infer from data.
            compress: Compression method.
            nodata: NoData value.

        Returns:
            Path to saved file.
        """
        profile = metadata["profile"].copy()

        if dtype is None:
            dtype = str(data.dtype)

        # Handle 2D vs 3D arrays
        if data.ndim == 2:
            count = 1
            height, width = data.shape
        else:
            count = data.shape[0]
            height, width = data.shape[1], data.shape[2]

        profile.update(
            {
                "dtype": dtype,
                "count": count,
                "height": height,
                "width": width,
                "compress": compress,
            }
        )

        if nodata is not None:
            profile["nodata"] = nodata

        os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)

        with rasterio.open(output_path, "w", **profile) as dst:
            if data.ndim == 2:
                dst.write(data, 1)
            else:
                dst.write(data)

        return output_path

    def save_vector(
        self,
        gdf: gpd.GeoDataFrame,
        output_path: str,
        driver: Optional[str] = None,
    ) -> str:
        """Save GeoDataFrame to file.

        Args:
            gdf: GeoDataFrame to save.
            output_path: Output file path.
            driver: File driver (auto-detected from extension if None).

        Returns:
            Path to saved file.
        """
        os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)

        if driver is None:
            ext = os.path.splitext(output_path)[1].lower()
            driver_map = {
                ".geojson": "GeoJSON",
                ".json": "GeoJSON",
                ".gpkg": "GPKG",
                ".shp": "ESRI Shapefile",
                ".parquet": "Parquet",
                ".fgb": "FlatGeobuf",
            }
            driver = driver_map.get(ext, "GeoJSON")

        gdf.to_file(output_path, driver=driver)
        return output_path

__init__(model, processor=None, model_name=None, task=None, device=None, tile_size=1024, overlap=128)

Initialize AutoGeoModel with an existing model.

Note: Use from_pretrained class method to load from Hugging Face Hub.

Parameters:

Name Type Description Default
model Module

A transformers model instance.

required
processor Optional[AutoGeoImageProcessor]

An AutoGeoImageProcessor instance (optional).

None
model_name Optional[str]

Name or path of the model (for reference).

None
task Optional[str]

Task type for the model.

None
device Optional[str]

Device to use ('cuda', 'cpu'). If None, auto-detect.

None
tile_size int

Size of tiles for processing large images.

1024
overlap int

Overlap between tiles.

128
Source code in geoai/auto.py
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
def __init__(
    self,
    model: torch.nn.Module,
    processor: Optional["AutoGeoImageProcessor"] = None,
    model_name: Optional[str] = None,
    task: Optional[str] = None,
    device: Optional[str] = None,
    tile_size: int = 1024,
    overlap: int = 128,
) -> None:
    """Initialize AutoGeoModel with an existing model.

    Note: Use `from_pretrained` class method to load from Hugging Face Hub.

    Args:
        model: A transformers model instance.
        processor: An AutoGeoImageProcessor instance (optional).
        model_name: Name or path of the model (for reference).
        task: Task type for the model.
        device: Device to use ('cuda', 'cpu'). If None, auto-detect.
        tile_size: Size of tiles for processing large images.
        overlap: Overlap between tiles.
    """
    self.model = model
    self.processor = processor
    self.model_name = model_name
    self.task = task
    self.tile_size = tile_size
    self.overlap = overlap

    if device is None:
        self.device = get_device()
    else:
        self.device = device

    # Ensure model is on the correct device and in eval mode
    self.model = self.model.to(self.device)
    self.model.eval()

from_pretrained(pretrained_model_name_or_path, task=None, device=None, tile_size=1024, overlap=128, **kwargs) classmethod

Load an AutoGeoModel from a pretrained model.

This method wraps transformers' AutoModel.from_pretrained and adds geospatial capabilities for processing GeoTIFF files.

Parameters:

Name Type Description Default
pretrained_model_name_or_path str

Hugging Face model name or local path. Can be a model ID from huggingface.co or a local directory path.

required
task Optional[str]

Task type for automatic model class selection. Options: - 'segmentation' or 'semantic-segmentation': Semantic segmentation - 'image-segmentation': General image segmentation - 'universal-segmentation': Universal segmentation (Mask2Former, etc.) - 'depth-estimation': Depth estimation - 'mask-generation': Mask generation (SAM, etc.) - 'object-detection': Object detection - 'zero-shot-object-detection': Zero-shot object detection - 'classification' or 'image-classification': Image classification If None, will try to infer from model config.

None
device Optional[str]

Device to use ('cuda', 'cpu'). If None, auto-detect.

None
tile_size int

Size of tiles for processing large images.

1024
overlap int

Overlap between tiles to avoid edge artifacts.

128
**kwargs Any

Additional arguments passed to the model's from_pretrained. Common options include: - trust_remote_code (bool): Whether to trust remote code. - revision (str): Specific model version to use. - torch_dtype: Data type for model weights.

{}

Returns:

Type Description
AutoGeoModel

AutoGeoModel instance with geospatial support.

Example

model = AutoGeoModel.from_pretrained("facebook/sam-vit-base", task="mask-generation") model = AutoGeoModel.from_pretrained( ... "nvidia/segformer-b0-finetuned-ade-512-512", ... task="semantic-segmentation", ... device="cuda" ... )

Source code in geoai/auto.py
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
@classmethod
def from_pretrained(
    cls,
    pretrained_model_name_or_path: str,
    task: Optional[str] = None,
    device: Optional[str] = None,
    tile_size: int = 1024,
    overlap: int = 128,
    **kwargs: Any,
) -> "AutoGeoModel":
    """Load an AutoGeoModel from a pretrained model.

    This method wraps transformers' AutoModel.from_pretrained and adds
    geospatial capabilities for processing GeoTIFF files.

    Args:
        pretrained_model_name_or_path: Hugging Face model name or local path.
            Can be a model ID from huggingface.co or a local directory path.
        task: Task type for automatic model class selection. Options:
            - 'segmentation' or 'semantic-segmentation': Semantic segmentation
            - 'image-segmentation': General image segmentation
            - 'universal-segmentation': Universal segmentation (Mask2Former, etc.)
            - 'depth-estimation': Depth estimation
            - 'mask-generation': Mask generation (SAM, etc.)
            - 'object-detection': Object detection
            - 'zero-shot-object-detection': Zero-shot object detection
            - 'classification' or 'image-classification': Image classification
            If None, will try to infer from model config.
        device: Device to use ('cuda', 'cpu'). If None, auto-detect.
        tile_size: Size of tiles for processing large images.
        overlap: Overlap between tiles to avoid edge artifacts.
        **kwargs: Additional arguments passed to the model's from_pretrained.
            Common options include:
            - trust_remote_code (bool): Whether to trust remote code.
            - revision (str): Specific model version to use.
            - torch_dtype: Data type for model weights.

    Returns:
        AutoGeoModel instance with geospatial support.

    Example:
        >>> model = AutoGeoModel.from_pretrained("facebook/sam-vit-base", task="mask-generation")
        >>> model = AutoGeoModel.from_pretrained(
        ...     "nvidia/segformer-b0-finetuned-ade-512-512",
        ...     task="semantic-segmentation",
        ...     device="cuda"
        ... )
    """
    # Determine device
    if device is None:
        device = get_device()

    # Load model using appropriate auto class
    model = cls._load_model_from_pretrained(
        pretrained_model_name_or_path, task, **kwargs
    )

    # Load processor - use full processor for models that need text inputs
    needs_full_processor = task in (
        "zero-shot-object-detection",
        "object-detection",
    )
    try:
        processor = AutoGeoImageProcessor.from_pretrained(
            pretrained_model_name_or_path,
            device=device,
            use_full_processor=needs_full_processor,
        )
    except Exception:
        processor = None

    instance = cls(
        model=model,
        processor=processor,
        model_name=pretrained_model_name_or_path,
        task=task,
        device=device,
        tile_size=tile_size,
        overlap=overlap,
    )

    print(f"Model loaded on {device}")
    return instance

mask_to_vector(mask, metadata, threshold=0.5, min_object_area=100, max_object_area=None, simplify_tolerance=1.0)

Convert a raster mask to vector polygons.

Parameters:

Name Type Description Default
mask ndarray

Binary or probability mask array.

required
metadata Dict

Geospatial metadata dictionary.

required
threshold float

Threshold for binarizing probability masks.

0.5
min_object_area int

Minimum area in pixels for valid objects.

100
max_object_area Optional[int]

Maximum area in pixels (optional).

None
simplify_tolerance float

Tolerance for polygon simplification.

1.0

Returns:

Type Description
Optional[GeoDataFrame]

GeoDataFrame with polygon geometries, or None if no valid polygons.

Source code in geoai/auto.py
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
def mask_to_vector(
    self,
    mask: np.ndarray,
    metadata: Dict,
    threshold: float = 0.5,
    min_object_area: int = 100,
    max_object_area: Optional[int] = None,
    simplify_tolerance: float = 1.0,
) -> Optional[gpd.GeoDataFrame]:
    """Convert a raster mask to vector polygons.

    Args:
        mask: Binary or probability mask array.
        metadata: Geospatial metadata dictionary.
        threshold: Threshold for binarizing probability masks.
        min_object_area: Minimum area in pixels for valid objects.
        max_object_area: Maximum area in pixels (optional).
        simplify_tolerance: Tolerance for polygon simplification.

    Returns:
        GeoDataFrame with polygon geometries, or None if no valid polygons.
    """
    if metadata is None or metadata.get("crs") is None:
        print("Warning: No CRS information available for vectorization")
        return None

    # Ensure binary mask
    if mask.dtype == np.float32 or mask.dtype == np.float64:
        mask = (mask > threshold).astype(np.uint8)
    else:
        mask = (mask > 0).astype(np.uint8)

    # Get transform
    transform = metadata.get("transform")
    crs = metadata.get("crs")

    if transform is None:
        print("Warning: No transform available for vectorization")
        return None

    # Extract shapes using rasterio
    polygons = []
    values = []

    try:
        for geom, value in shapes(mask, transform=transform):
            if value > 0:  # Only keep non-background
                poly = shape(geom)

                # Filter by area
                pixel_area = poly.area / (transform.a * abs(transform.e))
                if pixel_area < min_object_area:
                    continue
                if max_object_area and pixel_area > max_object_area:
                    continue

                # Simplify
                if simplify_tolerance > 0:
                    poly = poly.simplify(
                        simplify_tolerance * abs(transform.a),
                        preserve_topology=True,
                    )

                if poly.is_valid and not poly.is_empty:
                    polygons.append(poly)
                    values.append(value)

    except Exception as e:
        print(f"Error during vectorization: {e}")
        return None

    if not polygons:
        return None

    # Create GeoDataFrame
    gdf = gpd.GeoDataFrame(
        {"geometry": polygons, "class": values},
        crs=crs,
    )

    return gdf

predict(source, output_path=None, output_vector_path=None, window=None, bands=None, threshold=0.5, text=None, labels=None, box_threshold=0.3, text_threshold=0.25, min_object_area=100, simplify_tolerance=1.0, batch_size=1, return_probabilities=False, **kwargs)

Run inference on a GeoTIFF or image.

Parameters:

Name Type Description Default
source Union[str, ndarray, Image]

Input image (path, array, or PIL Image). Can also be a URL.

required
output_path Optional[str]

Path to save output GeoTIFF.

None
output_vector_path Optional[str]

Path to save output vector file (GeoJSON, GPKG, etc.).

None
window Optional[Window]

Optional rasterio Window for processing a subset.

None
bands Optional[List[int]]

List of band indices to use (1-indexed).

None
threshold float

Threshold for binary masks (segmentation tasks).

0.5
text Optional[str]

Text prompt for zero-shot detection models (e.g., "a cat. a dog."). For Grounding DINO, labels should be lowercase and end with a dot.

None
labels Optional[List[str]]

List of labels to detect (alternative to text). Will be converted to text prompt format automatically.

None
box_threshold float

Confidence threshold for bounding boxes (detection tasks).

0.3
text_threshold float

Text similarity threshold for zero-shot detection.

0.25
min_object_area int

Minimum object area in pixels for vectorization.

100
simplify_tolerance float

Tolerance for polygon simplification.

1.0
batch_size int

Batch size for processing tiles.

1
return_probabilities bool

Whether to return probability maps.

False
**kwargs Any

Additional arguments for specific tasks.

{}

Returns:

Type Description
Dict[str, Any]

Dictionary with results including mask/detections, metadata, and optional vector data.

Example

Zero-shot object detection

model = AutoGeoModel.from_pretrained( ... "IDEA-Research/grounding-dino-base", ... task="zero-shot-object-detection" ... ) result = model.predict( ... "image.jpg", ... text="a building. a car. a tree.", ... box_threshold=0.3 ... ) print(result["boxes"], result["labels"])

Source code in geoai/auto.py
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
736
737
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
def predict(
    self,
    source: Union[str, np.ndarray, Image.Image],
    output_path: Optional[str] = None,
    output_vector_path: Optional[str] = None,
    window: Optional[Window] = None,
    bands: Optional[List[int]] = None,
    threshold: float = 0.5,
    text: Optional[str] = None,
    labels: Optional[List[str]] = None,
    box_threshold: float = 0.3,
    text_threshold: float = 0.25,
    min_object_area: int = 100,
    simplify_tolerance: float = 1.0,
    batch_size: int = 1,
    return_probabilities: bool = False,
    **kwargs: Any,
) -> Dict[str, Any]:
    """Run inference on a GeoTIFF or image.

    Args:
        source: Input image (path, array, or PIL Image). Can also be a URL.
        output_path: Path to save output GeoTIFF.
        output_vector_path: Path to save output vector file (GeoJSON, GPKG, etc.).
        window: Optional rasterio Window for processing a subset.
        bands: List of band indices to use (1-indexed).
        threshold: Threshold for binary masks (segmentation tasks).
        text: Text prompt for zero-shot detection models (e.g., "a cat. a dog.").
            For Grounding DINO, labels should be lowercase and end with a dot.
        labels: List of labels to detect (alternative to text).
            Will be converted to text prompt format automatically.
        box_threshold: Confidence threshold for bounding boxes (detection tasks).
        text_threshold: Text similarity threshold for zero-shot detection.
        min_object_area: Minimum object area in pixels for vectorization.
        simplify_tolerance: Tolerance for polygon simplification.
        batch_size: Batch size for processing tiles.
        return_probabilities: Whether to return probability maps.
        **kwargs: Additional arguments for specific tasks.

    Returns:
        Dictionary with results including mask/detections, metadata, and optional vector data.

    Example:
        >>> # Zero-shot object detection
        >>> model = AutoGeoModel.from_pretrained(
        ...     "IDEA-Research/grounding-dino-base",
        ...     task="zero-shot-object-detection"
        ... )
        >>> result = model.predict(
        ...     "image.jpg",
        ...     text="a building. a car. a tree.",
        ...     box_threshold=0.3
        ... )
        >>> print(result["boxes"], result["labels"])
    """
    # Convert labels list to text format if provided
    if labels is not None and text is None:
        text = " ".join(f"{label.lower().strip()}." for label in labels)

    # Handle zero-shot object detection separately
    if self.task in ("zero-shot-object-detection", "object-detection"):
        return self._predict_detection(
            source,
            text=text,
            box_threshold=box_threshold,
            text_threshold=text_threshold,
            output_vector_path=output_vector_path,
            **kwargs,
        )

    # Load image (handles URLs, local files, arrays, PIL Images)
    pil_image = None
    if isinstance(source, str):
        # Check if URL
        if source.startswith(("http://", "https://")):
            pil_image = Image.open(requests.get(source, stream=True).raw)
            metadata = None
            data = np.array(pil_image.convert("RGB")).transpose(2, 0, 1)
        else:
            # Local file - try to load with geospatial info
            if self.processor is not None:
                data, metadata = self.processor.load_image(source, window, bands)
            else:
                try:
                    with rasterio.open(source) as src:
                        data = src.read(bands) if bands else src.read()
                        profile = src.profile.copy()
                        metadata = {
                            "profile": profile,
                            "crs": src.crs,
                            "transform": src.transform,
                            "bounds": src.bounds,
                            "width": src.width,
                            "height": src.height,
                        }
                except Exception:
                    # Fall back to PIL for regular images
                    pil_image = Image.open(source).convert("RGB")
                    data = np.array(pil_image).transpose(2, 0, 1)
                    metadata = None
    elif isinstance(source, Image.Image):
        pil_image = source
        data = np.array(source.convert("RGB")).transpose(2, 0, 1)
        metadata = None
    else:
        data = np.array(source)
        if data.ndim == 3 and data.shape[2] in [1, 3, 4]:
            data = data.transpose(2, 0, 1)
        metadata = None

    # Check if we need tiled processing (not for classification tasks)
    if data.ndim == 3:
        _, height, width = data.shape
    elif data.ndim == 2:
        height, width = data.shape
        _ = 1
    else:
        raise ValueError(f"Unexpected data shape: {data.shape}")

    # Classification tasks should not use tiled processing
    use_tiled = (
        height > self.tile_size or width > self.tile_size
    ) and self.task not in ("classification", "image-classification")

    if use_tiled:
        result = self._predict_tiled(
            source,
            data,
            metadata,
            threshold=threshold,
            batch_size=batch_size,
            return_probabilities=return_probabilities,
            **kwargs,
        )
    else:
        result = self._predict_single(
            data,
            metadata,
            threshold=threshold,
            return_probabilities=return_probabilities,
            **kwargs,
        )

    # Save GeoTIFF output
    if output_path and metadata:
        self.save_geotiff(
            result.get("mask", result.get("output")),
            output_path,
            metadata,
            nodata=0,
        )
        result["output_path"] = output_path

    # Save vector output
    if output_vector_path and metadata and "mask" in result:
        gdf = self.mask_to_vector(
            result["mask"],
            metadata,
            threshold=threshold,
            min_object_area=min_object_area,
            simplify_tolerance=simplify_tolerance,
        )
        if gdf is not None and len(gdf) > 0:
            gdf.to_file(output_vector_path)
            result["vector_path"] = output_vector_path
            result["geodataframe"] = gdf

    return result

save_geotiff(data, output_path, metadata, dtype=None, compress='lzw', nodata=None)

Save array as GeoTIFF with geospatial metadata.

Parameters:

Name Type Description Default
data ndarray

Array to save (2D or 3D in CHW format).

required
output_path str

Output file path.

required
metadata Dict

Metadata dictionary from load_geotiff.

required
dtype Optional[str]

Output data type. If None, infer from data.

None
compress str

Compression method.

'lzw'
nodata Optional[float]

NoData value.

None

Returns:

Type Description
str

Path to saved file.

Source code in geoai/auto.py
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
def save_geotiff(
    self,
    data: np.ndarray,
    output_path: str,
    metadata: Dict,
    dtype: Optional[str] = None,
    compress: str = "lzw",
    nodata: Optional[float] = None,
) -> str:
    """Save array as GeoTIFF with geospatial metadata.

    Args:
        data: Array to save (2D or 3D in CHW format).
        output_path: Output file path.
        metadata: Metadata dictionary from load_geotiff.
        dtype: Output data type. If None, infer from data.
        compress: Compression method.
        nodata: NoData value.

    Returns:
        Path to saved file.
    """
    profile = metadata["profile"].copy()

    if dtype is None:
        dtype = str(data.dtype)

    # Handle 2D vs 3D arrays
    if data.ndim == 2:
        count = 1
        height, width = data.shape
    else:
        count = data.shape[0]
        height, width = data.shape[1], data.shape[2]

    profile.update(
        {
            "dtype": dtype,
            "count": count,
            "height": height,
            "width": width,
            "compress": compress,
        }
    )

    if nodata is not None:
        profile["nodata"] = nodata

    os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)

    with rasterio.open(output_path, "w", **profile) as dst:
        if data.ndim == 2:
            dst.write(data, 1)
        else:
            dst.write(data)

    return output_path

save_vector(gdf, output_path, driver=None)

Save GeoDataFrame to file.

Parameters:

Name Type Description Default
gdf GeoDataFrame

GeoDataFrame to save.

required
output_path str

Output file path.

required
driver Optional[str]

File driver (auto-detected from extension if None).

None

Returns:

Type Description
str

Path to saved file.

Source code in geoai/auto.py
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
def save_vector(
    self,
    gdf: gpd.GeoDataFrame,
    output_path: str,
    driver: Optional[str] = None,
) -> str:
    """Save GeoDataFrame to file.

    Args:
        gdf: GeoDataFrame to save.
        output_path: Output file path.
        driver: File driver (auto-detected from extension if None).

    Returns:
        Path to saved file.
    """
    os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)

    if driver is None:
        ext = os.path.splitext(output_path)[1].lower()
        driver_map = {
            ".geojson": "GeoJSON",
            ".json": "GeoJSON",
            ".gpkg": "GPKG",
            ".shp": "ESRI Shapefile",
            ".parquet": "Parquet",
            ".fgb": "FlatGeobuf",
        }
        driver = driver_map.get(ext, "GeoJSON")

    gdf.to_file(output_path, driver=driver)
    return output_path

depth_estimation(input_path, output_path, model_name='depth-anything/Depth-Anything-V2-Small-hf', tile_size=1024, overlap=128, device=None, **kwargs)

Perform depth estimation on a GeoTIFF image.

Parameters:

Name Type Description Default
input_path str

Path to input GeoTIFF.

required
output_path str

Path to save output depth GeoTIFF.

required
model_name str

Hugging Face model name.

'depth-anything/Depth-Anything-V2-Small-hf'
tile_size int

Size of tiles for processing large images.

1024
overlap int

Overlap between tiles.

128
device Optional[str]

Device to use ('cuda', 'cpu').

None
**kwargs Any

Additional arguments for prediction.

{}

Returns:

Type Description
Dict[str, Any]

Dictionary with results.

Example

result = depth_estimation( ... "input.tif", ... "depth_output.tif", ... model_name="depth-anything/Depth-Anything-V2-Small-hf" ... )

Source code in geoai/auto.py
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
def depth_estimation(
    input_path: str,
    output_path: str,
    model_name: str = "depth-anything/Depth-Anything-V2-Small-hf",
    tile_size: int = 1024,
    overlap: int = 128,
    device: Optional[str] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """
    Perform depth estimation on a GeoTIFF image.

    Args:
        input_path: Path to input GeoTIFF.
        output_path: Path to save output depth GeoTIFF.
        model_name: Hugging Face model name.
        tile_size: Size of tiles for processing large images.
        overlap: Overlap between tiles.
        device: Device to use ('cuda', 'cpu').
        **kwargs: Additional arguments for prediction.

    Returns:
        Dictionary with results.

    Example:
        >>> result = depth_estimation(
        ...     "input.tif",
        ...     "depth_output.tif",
        ...     model_name="depth-anything/Depth-Anything-V2-Small-hf"
        ... )
    """
    model = AutoGeoModel.from_pretrained(
        model_name,
        task="depth-estimation",
        device=device,
        tile_size=tile_size,
        overlap=overlap,
    )

    return model.predict(input_path, output_path=output_path, **kwargs)

get_hf_model_config(model_id)

Get the model configuration for a Hugging Face model.

Parameters:

Name Type Description Default
model_id str

The Hugging Face model ID (e.g., "facebook/sam-vit-base").

required

Returns:

Type Description
Dict[str, Any]

Dictionary representation of the model config.

Example

config = get_hf_model_config("nvidia/segformer-b0-finetuned-ade-512-512") print(config.get("model_type"))

Source code in geoai/auto.py
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
def get_hf_model_config(model_id: str) -> Dict[str, Any]:
    """Get the model configuration for a Hugging Face model.

    Args:
        model_id: The Hugging Face model ID (e.g., "facebook/sam-vit-base").

    Returns:
        Dictionary representation of the model config.

    Example:
        >>> config = get_hf_model_config("nvidia/segformer-b0-finetuned-ade-512-512")
        >>> print(config.get("model_type"))
    """
    cfg = AutoConfig.from_pretrained(model_id)
    return cfg.to_dict()

get_hf_tasks()

Get all supported Hugging Face tasks for this module.

Returns:

Type Description
List[str]

List of supported task names.

Source code in geoai/auto.py
1612
1613
1614
1615
1616
1617
1618
1619
1620
def get_hf_tasks() -> List[str]:
    """Get all supported Hugging Face tasks for this module.

    Returns:
        List of supported task names.
    """
    from transformers.pipelines import SUPPORTED_TASKS

    return sorted(list(SUPPORTED_TASKS.keys()))

image_classification(input_path, model_name='google/vit-base-patch16-224', device=None, **kwargs)

Perform image classification on a GeoTIFF image.

Parameters:

Name Type Description Default
input_path str

Path to input GeoTIFF.

required
model_name str

Hugging Face model name.

'google/vit-base-patch16-224'
device Optional[str]

Device to use ('cuda', 'cpu').

None
**kwargs Any

Additional arguments for prediction.

{}

Returns:

Type Description
Dict[str, Any]

Dictionary with classification results.

Example

result = image_classification( ... "input.tif", ... model_name="google/vit-base-patch16-224" ... ) print(result['class'], result['probabilities'])

Source code in geoai/auto.py
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
def image_classification(
    input_path: str,
    model_name: str = "google/vit-base-patch16-224",
    device: Optional[str] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """
    Perform image classification on a GeoTIFF image.

    Args:
        input_path: Path to input GeoTIFF.
        model_name: Hugging Face model name.
        device: Device to use ('cuda', 'cpu').
        **kwargs: Additional arguments for prediction.

    Returns:
        Dictionary with classification results.

    Example:
        >>> result = image_classification(
        ...     "input.tif",
        ...     model_name="google/vit-base-patch16-224"
        ... )
        >>> print(result['class'], result['probabilities'])
    """
    model = AutoGeoModel.from_pretrained(
        model_name,
        task="image-classification",
        device=device,
    )

    return model.predict(input_path, **kwargs)

object_detection(input_path, text=None, labels=None, model_name='IDEA-Research/grounding-dino-base', output_vector_path=None, box_threshold=0.3, text_threshold=0.25, device=None, **kwargs)

Perform object detection on an image using Grounding DINO or similar models.

Parameters:

Name Type Description Default
input_path str

Path to input image or URL.

required
text Optional[str]

Text prompt for detection (e.g., "a building. a car."). Labels should be lowercase and end with a dot.

None
labels Optional[List[str]]

List of labels to detect (alternative to text). Will be converted to text format automatically.

None
model_name str

Hugging Face model name.

'IDEA-Research/grounding-dino-base'
output_vector_path Optional[str]

Optional path to save detection boxes as vector file.

None
box_threshold float

Confidence threshold for bounding boxes.

0.3
text_threshold float

Text similarity threshold for zero-shot detection.

0.25
device Optional[str]

Device to use ('cuda', 'cpu').

None
**kwargs Any

Additional arguments for prediction.

{}

Returns:

Type Description
Dict[str, Any]

Dictionary with detection results (boxes, scores, labels).

Example

result = object_detection( ... "image.jpg", ... labels=["car", "building", "tree"], ... box_threshold=0.3 ... ) print(result["boxes"], result["labels"])

Source code in geoai/auto.py
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
def object_detection(
    input_path: str,
    text: Optional[str] = None,
    labels: Optional[List[str]] = None,
    model_name: str = "IDEA-Research/grounding-dino-base",
    output_vector_path: Optional[str] = None,
    box_threshold: float = 0.3,
    text_threshold: float = 0.25,
    device: Optional[str] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """
    Perform object detection on an image using Grounding DINO or similar models.

    Args:
        input_path: Path to input image or URL.
        text: Text prompt for detection (e.g., "a building. a car.").
            Labels should be lowercase and end with a dot.
        labels: List of labels to detect (alternative to text).
            Will be converted to text format automatically.
        model_name: Hugging Face model name.
        output_vector_path: Optional path to save detection boxes as vector file.
        box_threshold: Confidence threshold for bounding boxes.
        text_threshold: Text similarity threshold for zero-shot detection.
        device: Device to use ('cuda', 'cpu').
        **kwargs: Additional arguments for prediction.

    Returns:
        Dictionary with detection results (boxes, scores, labels).

    Example:
        >>> result = object_detection(
        ...     "image.jpg",
        ...     labels=["car", "building", "tree"],
        ...     box_threshold=0.3
        ... )
        >>> print(result["boxes"], result["labels"])
    """
    # Determine task type based on model
    task = "zero-shot-object-detection"
    if "grounding-dino" not in model_name.lower() and "owl" not in model_name.lower():
        task = "object-detection"

    model = AutoGeoModel.from_pretrained(
        model_name,
        task=task,
        device=device,
    )

    return model.predict(
        input_path,
        text=text,
        labels=labels,
        box_threshold=box_threshold,
        text_threshold=text_threshold,
        output_vector_path=output_vector_path,
        **kwargs,
    )

semantic_segmentation(input_path, output_path, model_name='nvidia/segformer-b0-finetuned-ade-512-512', output_vector_path=None, threshold=0.5, tile_size=1024, overlap=128, min_object_area=100, simplify_tolerance=1.0, device=None, **kwargs)

Perform semantic segmentation on a GeoTIFF image.

Parameters:

Name Type Description Default
input_path str

Path to input GeoTIFF.

required
output_path str

Path to save output segmentation GeoTIFF.

required
model_name str

Hugging Face model name.

'nvidia/segformer-b0-finetuned-ade-512-512'
output_vector_path Optional[str]

Optional path to save vectorized output.

None
threshold float

Threshold for binary masks.

0.5
tile_size int

Size of tiles for processing large images.

1024
overlap int

Overlap between tiles.

128
min_object_area int

Minimum object area for vectorization.

100
simplify_tolerance float

Tolerance for polygon simplification.

1.0
device Optional[str]

Device to use ('cuda', 'cpu').

None
**kwargs Any

Additional arguments for prediction.

{}

Returns:

Type Description
Dict[str, Any]

Dictionary with results.

Example

result = semantic_segmentation( ... "input.tif", ... "output.tif", ... model_name="nvidia/segformer-b0-finetuned-ade-512-512", ... output_vector_path="output.geojson" ... )

Source code in geoai/auto.py
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
def semantic_segmentation(
    input_path: str,
    output_path: str,
    model_name: str = "nvidia/segformer-b0-finetuned-ade-512-512",
    output_vector_path: Optional[str] = None,
    threshold: float = 0.5,
    tile_size: int = 1024,
    overlap: int = 128,
    min_object_area: int = 100,
    simplify_tolerance: float = 1.0,
    device: Optional[str] = None,
    **kwargs: Any,
) -> Dict[str, Any]:
    """
    Perform semantic segmentation on a GeoTIFF image.

    Args:
        input_path: Path to input GeoTIFF.
        output_path: Path to save output segmentation GeoTIFF.
        model_name: Hugging Face model name.
        output_vector_path: Optional path to save vectorized output.
        threshold: Threshold for binary masks.
        tile_size: Size of tiles for processing large images.
        overlap: Overlap between tiles.
        min_object_area: Minimum object area for vectorization.
        simplify_tolerance: Tolerance for polygon simplification.
        device: Device to use ('cuda', 'cpu').
        **kwargs: Additional arguments for prediction.

    Returns:
        Dictionary with results.

    Example:
        >>> result = semantic_segmentation(
        ...     "input.tif",
        ...     "output.tif",
        ...     model_name="nvidia/segformer-b0-finetuned-ade-512-512",
        ...     output_vector_path="output.geojson"
        ... )
    """
    model = AutoGeoModel.from_pretrained(
        model_name,
        task="semantic-segmentation",
        device=device,
        tile_size=tile_size,
        overlap=overlap,
    )

    return model.predict(
        input_path,
        output_path=output_path,
        output_vector_path=output_vector_path,
        threshold=threshold,
        min_object_area=min_object_area,
        simplify_tolerance=simplify_tolerance,
        **kwargs,
    )

show_depth(source, depth, figsize=(14, 6), title=None, cmap='plasma', show_original=True, show_colorbar=True, axis_off=True, **kwargs)

Display depth estimation results.

Parameters:

Name Type Description Default
source Union[str, ndarray, Image]

Image source (path to file, numpy array, or PIL Image).

required
depth ndarray

Depth map array.

required
figsize Tuple[int, int]

Figure size as (width, height).

(14, 6)
title Optional[str]

Optional title for the plot.

None
cmap str

Colormap for the depth map.

'plasma'
show_original bool

Whether to show original image side-by-side.

True
show_colorbar bool

Whether to show a colorbar.

True
axis_off bool

Whether to hide axes.

True
**kwargs Any

Additional arguments passed to plt.imshow().

{}

Returns:

Type Description
Figure

Matplotlib figure object.

Example

result = geoai.auto.depth_estimation("aerial.tif", output_path="depth.tif") fig = show_depth("aerial.tif", result["depth"])

Source code in geoai/auto.py
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
def show_depth(
    source: Union[str, np.ndarray, Image.Image],
    depth: np.ndarray,
    figsize: Tuple[int, int] = (14, 6),
    title: Optional[str] = None,
    cmap: str = "plasma",
    show_original: bool = True,
    show_colorbar: bool = True,
    axis_off: bool = True,
    **kwargs: Any,
) -> "plt.Figure":
    """Display depth estimation results.

    Args:
        source: Image source (path to file, numpy array, or PIL Image).
        depth: Depth map array.
        figsize: Figure size as (width, height).
        title: Optional title for the plot.
        cmap: Colormap for the depth map.
        show_original: Whether to show original image side-by-side.
        show_colorbar: Whether to show a colorbar.
        axis_off: Whether to hide axes.
        **kwargs: Additional arguments passed to plt.imshow().

    Returns:
        Matplotlib figure object.

    Example:
        >>> result = geoai.auto.depth_estimation("aerial.tif", output_path="depth.tif")
        >>> fig = show_depth("aerial.tif", result["depth"])
    """
    import matplotlib.pyplot as plt

    img, _ = _load_image_for_display(source)

    # Resize depth if necessary
    if depth.shape[:2] != img.shape[:2]:
        depth = cv2.resize(
            depth.astype(np.float32),
            (img.shape[1], img.shape[0]),
            interpolation=cv2.INTER_LINEAR,
        )

    if show_original:
        fig, axes = plt.subplots(1, 2, figsize=figsize)

        axes[0].imshow(img, **kwargs)
        axes[0].set_title("Original Image")
        if axis_off:
            axes[0].axis("off")

        im = axes[1].imshow(depth, cmap=cmap)
        axes[1].set_title(title or "Depth Estimation")
        if axis_off:
            axes[1].axis("off")
        if show_colorbar:
            plt.colorbar(im, ax=axes[1], label="Relative Depth")
    else:
        fig, ax = plt.subplots(figsize=figsize)
        im = ax.imshow(depth, cmap=cmap)
        if title:
            ax.set_title(title)
        if axis_off:
            ax.axis("off")
        if show_colorbar:
            plt.colorbar(im, ax=ax, label="Relative Depth")

    plt.tight_layout()
    return fig

show_detections(source, detections, figsize=(12, 10), title=None, box_color='red', text_color='white', linewidth=2, fontsize=10, show_scores=True, axis_off=True, **kwargs)

Display an image with detection bounding boxes.

Parameters:

Name Type Description Default
source Union[str, ndarray, Image]

Image source (path to file, numpy array, or PIL Image).

required
detections Dict[str, Any]

Detection results dictionary with 'boxes', 'scores', 'labels'.

required
figsize Tuple[int, int]

Figure size as (width, height).

(12, 10)
title Optional[str]

Optional title for the plot.

None
box_color str

Color for bounding boxes (can be single color or list).

'red'
text_color str

Color for label text.

'white'
linewidth int

Width of bounding box lines.

2
fontsize int

Font size for labels.

10
show_scores bool

Whether to show confidence scores.

True
axis_off bool

Whether to hide axes.

True
**kwargs Any

Additional arguments passed to plt.imshow().

{}

Returns:

Type Description
Figure

Matplotlib figure object.

Example

result = geoai.auto.object_detection("aerial.tif", labels=["building", "tree"]) fig = show_detections("aerial.tif", result)

Source code in geoai/auto.py
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
def show_detections(
    source: Union[str, np.ndarray, Image.Image],
    detections: Dict[str, Any],
    figsize: Tuple[int, int] = (12, 10),
    title: Optional[str] = None,
    box_color: str = "red",
    text_color: str = "white",
    linewidth: int = 2,
    fontsize: int = 10,
    show_scores: bool = True,
    axis_off: bool = True,
    **kwargs: Any,
) -> "plt.Figure":
    """Display an image with detection bounding boxes.

    Args:
        source: Image source (path to file, numpy array, or PIL Image).
        detections: Detection results dictionary with 'boxes', 'scores', 'labels'.
        figsize: Figure size as (width, height).
        title: Optional title for the plot.
        box_color: Color for bounding boxes (can be single color or list).
        text_color: Color for label text.
        linewidth: Width of bounding box lines.
        fontsize: Font size for labels.
        show_scores: Whether to show confidence scores.
        axis_off: Whether to hide axes.
        **kwargs: Additional arguments passed to plt.imshow().

    Returns:
        Matplotlib figure object.

    Example:
        >>> result = geoai.auto.object_detection("aerial.tif", labels=["building", "tree"])
        >>> fig = show_detections("aerial.tif", result)
    """
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches

    img, _ = _load_image_for_display(source)

    fig, ax = plt.subplots(figsize=figsize)
    ax.imshow(img, **kwargs)

    boxes = detections.get("boxes", [])
    scores = detections.get("scores", [None] * len(boxes))
    labels = detections.get("labels", [None] * len(boxes))

    # Handle color list
    if isinstance(box_color, str):
        colors = [box_color] * len(boxes)
    else:
        colors = box_color

    for i, (bbox, score, label) in enumerate(zip(boxes, scores, labels)):
        x1, y1, x2, y2 = bbox
        width = x2 - x1
        height = y2 - y1

        color = colors[i % len(colors)]

        rect = patches.Rectangle(
            (x1, y1),
            width,
            height,
            linewidth=linewidth,
            edgecolor=color,
            facecolor="none",
        )
        ax.add_patch(rect)

        # Add label
        if label is not None:
            text = str(label)
            if show_scores and score is not None:
                text = f"{label}: {score:.2f}"
            ax.text(
                x1,
                y1 - 5,
                text,
                color=text_color,
                fontsize=fontsize,
                bbox=dict(boxstyle="round,pad=0.3", facecolor=color, alpha=0.7),
            )

    if title:
        ax.set_title(title)
    if axis_off:
        ax.axis("off")

    plt.tight_layout()
    return fig

show_image(source, figsize=(10, 10), title=None, axis_off=True, **kwargs)

Display an image (GeoTIFF or regular image).

Parameters:

Name Type Description Default
source Union[str, ndarray, Image]

Image source (path to file, numpy array, or PIL Image).

required
figsize Tuple[int, int]

Figure size as (width, height).

(10, 10)
title Optional[str]

Optional title for the plot.

None
axis_off bool

Whether to hide axes.

True
**kwargs Any

Additional arguments passed to plt.imshow().

{}

Returns:

Type Description
Figure

Matplotlib figure object.

Example

fig = show_image("aerial.tif", title="Aerial Image")

Source code in geoai/auto.py
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
def show_image(
    source: Union[str, np.ndarray, Image.Image],
    figsize: Tuple[int, int] = (10, 10),
    title: Optional[str] = None,
    axis_off: bool = True,
    **kwargs: Any,
) -> "plt.Figure":
    """Display an image (GeoTIFF or regular image).

    Args:
        source: Image source (path to file, numpy array, or PIL Image).
        figsize: Figure size as (width, height).
        title: Optional title for the plot.
        axis_off: Whether to hide axes.
        **kwargs: Additional arguments passed to plt.imshow().

    Returns:
        Matplotlib figure object.

    Example:
        >>> fig = show_image("aerial.tif", title="Aerial Image")
    """
    import matplotlib.pyplot as plt

    img, _ = _load_image_for_display(source)

    fig, ax = plt.subplots(figsize=figsize)
    ax.imshow(img, **kwargs)

    if title:
        ax.set_title(title)
    if axis_off:
        ax.axis("off")

    plt.tight_layout()
    return fig

show_segmentation(source, mask, figsize=(14, 6), title=None, alpha=0.5, cmap='tab20', show_original=True, axis_off=True, **kwargs)

Display segmentation results overlaid on the original image.

Parameters:

Name Type Description Default
source Union[str, ndarray, Image]

Image source (path to file, numpy array, or PIL Image).

required
mask ndarray

Segmentation mask array.

required
figsize Tuple[int, int]

Figure size as (width, height).

(14, 6)
title Optional[str]

Optional title for the plot.

None
alpha float

Transparency of the mask overlay.

0.5
cmap str

Colormap for the segmentation mask.

'tab20'
show_original bool

Whether to show original image side-by-side.

True
axis_off bool

Whether to hide axes.

True
**kwargs Any

Additional arguments passed to plt.imshow().

{}

Returns:

Type Description
Figure

Matplotlib figure object.

Example

result = geoai.auto.semantic_segmentation("aerial.tif", output_path="seg.tif") fig = show_segmentation("aerial.tif", result["mask"])

Source code in geoai/auto.py
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
def show_segmentation(
    source: Union[str, np.ndarray, Image.Image],
    mask: np.ndarray,
    figsize: Tuple[int, int] = (14, 6),
    title: Optional[str] = None,
    alpha: float = 0.5,
    cmap: str = "tab20",
    show_original: bool = True,
    axis_off: bool = True,
    **kwargs: Any,
) -> "plt.Figure":
    """Display segmentation results overlaid on the original image.

    Args:
        source: Image source (path to file, numpy array, or PIL Image).
        mask: Segmentation mask array.
        figsize: Figure size as (width, height).
        title: Optional title for the plot.
        alpha: Transparency of the mask overlay.
        cmap: Colormap for the segmentation mask.
        show_original: Whether to show original image side-by-side.
        axis_off: Whether to hide axes.
        **kwargs: Additional arguments passed to plt.imshow().

    Returns:
        Matplotlib figure object.

    Example:
        >>> result = geoai.auto.semantic_segmentation("aerial.tif", output_path="seg.tif")
        >>> fig = show_segmentation("aerial.tif", result["mask"])
    """
    import matplotlib.pyplot as plt

    img, _ = _load_image_for_display(source)

    # Resize mask if necessary
    if mask.shape[:2] != img.shape[:2]:
        mask = cv2.resize(
            mask.astype(np.float32),
            (img.shape[1], img.shape[0]),
            interpolation=cv2.INTER_NEAREST,
        ).astype(mask.dtype)

    if show_original:
        fig, axes = plt.subplots(1, 2, figsize=figsize)

        axes[0].imshow(img, **kwargs)
        axes[0].set_title("Original Image")
        if axis_off:
            axes[0].axis("off")

        axes[1].imshow(img, **kwargs)
        axes[1].imshow(mask, alpha=alpha, cmap=cmap)
        axes[1].set_title(title or "Segmentation Overlay")
        if axis_off:
            axes[1].axis("off")
    else:
        fig, ax = plt.subplots(figsize=figsize)
        ax.imshow(img, **kwargs)
        ax.imshow(mask, alpha=alpha, cmap=cmap)
        if title:
            ax.set_title(title)
        if axis_off:
            ax.axis("off")

    plt.tight_layout()
    return fig