geoai module¶
Main module.
AgricultureFieldDelineator
¶
Bases: ObjectDetector
Agricultural field boundary delineation using a pre-trained Mask R-CNN model.
This class extends the ObjectDetector class to specifically handle Sentinel-2 imagery with 12 spectral bands for agricultural field boundary detection.
Attributes:
| Name | Type | Description |
|---|---|---|
band_selection |
List of band indices to use for prediction (default: RGB) |
|
sentinel_band_stats |
Per-band statistics for Sentinel-2 data |
|
use_ndvi |
Whether to calculate and include NDVI as an additional channel |
Source code in geoai/extract.py
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 | |
__init__(model_path='field_boundary_detector.pth', repo_id=None, model=None, device=None, band_selection=None, use_ndvi=False)
¶
Initialize the field boundary delineator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the .pth model file. |
'field_boundary_detector.pth'
|
repo_id
|
Optional[str]
|
Repo ID for loading models from the Hub. |
None
|
model
|
Optional[Any]
|
Custom model to use for inference. |
None
|
device
|
Optional[str]
|
Device to use for inference ('cuda:0', 'cpu', etc.). |
None
|
band_selection
|
Optional[List[int]]
|
List of Sentinel-2 band indices to use (None = adapt based on model) |
None
|
use_ndvi
|
bool
|
Whether to calculate and include NDVI as an additional channel |
False
|
Source code in geoai/extract.py
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 | |
initialize_sentinel2_model(model=None)
¶
Initialize a Mask R-CNN model with a modified first layer to accept Sentinel-2 data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Optional[Any]
|
Pre-initialized model (optional) |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Modified model with appropriate input channels |
Source code in geoai/extract.py
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 | |
preprocess_sentinel_bands(image_data, band_selection=None, use_ndvi=None)
¶
Preprocess Sentinel-2 band data for model input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_data
|
ndarray
|
Raw Sentinel-2 image data as numpy array [bands, height, width] |
required |
band_selection
|
Optional[List[int]]
|
List of band indices to use (overrides instance default if provided) |
None
|
use_ndvi
|
Optional[bool]
|
Whether to include NDVI (overrides instance default if provided) |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Processed tensor ready for model input |
Source code in geoai/extract.py
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 | |
process_sentinel_raster(raster_path, output_path=None, batch_size=4, band_selection=None, use_ndvi=None, filter_edges=True, edge_buffer=20, **kwargs)
¶
Process a Sentinel-2 raster to extract field boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to Sentinel-2 raster file |
required |
output_path
|
Optional[str]
|
Path to output GeoJSON or Parquet file (optional) |
None
|
batch_size
|
int
|
Batch size for processing |
4
|
band_selection
|
Optional[List[int]]
|
List of bands to use (None = use instance default) |
None
|
use_ndvi
|
Optional[bool]
|
Whether to include NDVI (None = use instance default) |
None
|
filter_edges
|
bool
|
Whether to filter out objects at the edges of the image |
True
|
edge_buffer
|
int
|
Size of edge buffer in pixels to filter out objects |
20
|
**kwargs
|
Any
|
Additional parameters for processing |
{}
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with field boundaries |
Source code in geoai/extract.py
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 | |
update_band_stats(raster_path, band_selection=None, sample_size=1000)
¶
Update band statistics from the input Sentinel-2 raster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the Sentinel-2 raster file |
required |
band_selection
|
Optional[List[int]]
|
Specific bands to update (None = update all available) |
None
|
sample_size
|
int
|
Number of random pixels to sample for statistics calculation |
1000
|
Returns:
| Type | Description |
|---|---|
Dict[str, List[float]]
|
Updated band statistics dictionary |
Source code in geoai/extract.py
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 | |
BoundingBox
dataclass
¶
Represents a bounding box with coordinates.
Source code in geoai/segment.py
35 36 37 38 39 40 41 42 43 44 45 46 | |
BuildingFootprintExtractor
¶
Bases: ObjectDetector
Building footprint extraction using a pre-trained Mask R-CNN model.
This class extends the
ObjectDetector class with additional methods for building footprint extraction."
Source code in geoai/extract.py
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 | |
__init__(model_path='building_footprints_usa.pth', repo_id=None, model=None, device=None)
¶
Initialize the object extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the .pth model file. |
'building_footprints_usa.pth'
|
repo_id
|
Optional[str]
|
Repo ID for loading models from the Hub. |
None
|
model
|
Optional[Any]
|
Custom model to use for inference. |
None
|
device
|
Optional[str]
|
Device to use for inference ('cuda:0', 'cpu', etc.). |
None
|
Source code in geoai/extract.py
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 | |
regularize_buildings(gdf, min_area=10, angle_threshold=15, orthogonality_threshold=0.3, rectangularity_threshold=0.7)
¶
Regularize building footprints to enforce right angles and rectangular shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
GeoDataFrame with building footprints |
required |
min_area
|
int
|
Minimum area in square units to keep a building |
10
|
angle_threshold
|
int
|
Maximum deviation from 90 degrees to consider an angle as orthogonal (degrees) |
15
|
orthogonality_threshold
|
float
|
Percentage of angles that must be orthogonal for a building to be regularized |
0.3
|
rectangularity_threshold
|
float
|
Minimum area ratio to building's oriented bounding box for rectangular simplification |
0.7
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with regularized building footprints |
Source code in geoai/extract.py
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 | |
CLIPSegmentation
¶
A class for segmenting high-resolution satellite imagery using text prompts with CLIP-based models.
This segmenter utilizes the CLIP-Seg model to perform semantic segmentation based on text prompts. It can process large GeoTIFF files by tiling them and handles proper georeferencing in the output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Name of the CLIP-Seg model to use. Defaults to "CIDAS/clipseg-rd64-refined". |
'CIDAS/clipseg-rd64-refined'
|
device
|
str
|
Device to run the model on ('cuda', 'mps', 'cpu').
If None, auto-selects the best available device
(CUDA > MPS > CPU) via |
None
|
tile_size
|
int
|
Size of tiles to process the image in chunks. Defaults to 352. |
512
|
overlap
|
int
|
Overlap between tiles to avoid edge artifacts. Defaults to 16. |
32
|
Attributes:
| Name | Type | Description |
|---|---|---|
processor |
CLIPSegProcessor
|
The processor for the CLIP-Seg model. |
model |
CLIPSegForImageSegmentation
|
The CLIP-Seg model for segmentation. |
device |
str
|
The device being used ('cuda', 'mps', or 'cpu'). |
tile_size |
int
|
Size of tiles for processing. |
overlap |
int
|
Overlap between tiles. |
Source code in geoai/segment.py
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 | |
__init__(model_name='CIDAS/clipseg-rd64-refined', device=None, tile_size=512, overlap=32)
¶
Initialize the ImageSegmenter with the specified model and settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
|
str
|
Name of the CLIP-Seg model to use. Defaults to "CIDAS/clipseg-rd64-refined". |
'CIDAS/clipseg-rd64-refined'
|
device
|
str
|
Device to run the model on ('cuda', 'mps', 'cpu').
If None, auto-selects the best available device
(CUDA > MPS > CPU) via |
None
|
tile_size
|
int
|
Size of tiles to process the image in chunks. Defaults to 512. |
512
|
overlap
|
int
|
Overlap between tiles to avoid edge artifacts. Defaults to 32. |
32
|
Source code in geoai/segment.py
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 | |
segment_image(input_path, output_path, text_prompt, threshold=0.5, smoothing_sigma=1.0)
¶
Segment a GeoTIFF image using the provided text prompt.
The function processes the image in tiles and saves the result as a GeoTIFF with two bands: - Band 1: Binary segmentation mask (0 or 1) - Band 2: Probability scores (0.0 to 1.0)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Path to the input GeoTIFF file. |
required |
output_path
|
str
|
Path where the output GeoTIFF will be saved. |
required |
text_prompt
|
str
|
Text description of what to segment (e.g., "water", "buildings"). |
required |
threshold
|
float
|
Threshold for binary segmentation (0.0 to 1.0). Defaults to 0.5. |
0.5
|
smoothing_sigma
|
float
|
Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the saved output file. |
Source code in geoai/segment.py
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 | |
segment_image_batch(input_paths, output_dir, text_prompt, threshold=0.5, smoothing_sigma=1.0, suffix='_segmented')
¶
Segment multiple GeoTIFF images using the provided text prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_paths
|
list
|
List of paths to input GeoTIFF files. |
required |
output_dir
|
str
|
Directory where output GeoTIFFs will be saved. |
required |
text_prompt
|
str
|
Text description of what to segment. |
required |
threshold
|
float
|
Threshold for binary segmentation. Defaults to 0.5. |
0.5
|
smoothing_sigma
|
float
|
Sigma value for Gaussian smoothing to reduce blockiness. Defaults to 1.0. |
1.0
|
suffix
|
str
|
Suffix to add to output filenames. Defaults to "_segmented". |
'_segmented'
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
List[str]
|
Paths to all saved output files. |
Source code in geoai/segment.py
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 | |
CarDetector
¶
Bases: ObjectDetector
Car detection using a pre-trained Mask R-CNN model.
This class extends the ObjectDetector class with additional methods for car detection.
Source code in geoai/extract.py
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 | |
__init__(model_path='car_detection_usa.pth', repo_id=None, model=None, device=None)
¶
Initialize the object extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the .pth model file. |
'car_detection_usa.pth'
|
repo_id
|
Optional[str]
|
Repo ID for loading models from the Hub. |
None
|
model
|
Optional[Any]
|
Custom model to use for inference. |
None
|
device
|
Optional[str]
|
Device to use for inference ('cuda:0', 'cpu', etc.). |
None
|
Source code in geoai/extract.py
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 | |
CustomDataset
¶
Bases: NonGeoDataset
A TorchGeo dataset for object extraction with overlapping tiles support.
This dataset class creates overlapping image tiles for object detection, ensuring complete coverage of the input raster including right and bottom edges. It inherits from NonGeoDataset to avoid spatial indexing issues.
Attributes:
| Name | Type | Description |
|---|---|---|
raster_path |
Path to the input raster file. |
|
chip_size |
Size of image chips to extract (height, width). |
|
overlap |
Amount of overlap between adjacent tiles (0.0-1.0). |
|
transforms |
Transforms to apply to the image. |
|
verbose |
Whether to print detailed processing information. |
|
stride_x |
Horizontal stride between tiles based on overlap. |
|
stride_y |
Vertical stride between tiles based on overlap. |
|
row_starts |
Starting Y positions for each row of tiles. |
|
col_starts |
Starting X positions for each column of tiles. |
|
crs |
Coordinate reference system of the raster. |
|
transform |
Affine transform of the raster. |
|
height |
Height of the raster in pixels. |
|
width |
Width of the raster in pixels. |
|
count |
Number of bands in the raster. |
|
bounds |
Geographic bounds of the raster (west, south, east, north). |
|
roi |
Shapely box representing the region of interest. |
|
rows |
Number of rows of tiles. |
|
cols |
Number of columns of tiles. |
|
raster_stats |
Statistics of the raster. |
Source code in geoai/extract.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
__getitem__(idx)
¶
Get an image chip from the dataset by index.
Retrieves an image tile with the specified overlap pattern, ensuring proper coverage of the entire raster including edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
Index of the chip to retrieve. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict[str, Any]
|
Dictionary containing: - image: Image tensor. - bbox: Geographic bounding box for the window. - coords: Pixel coordinates as tensor [i, j]. - window_size: Window size as tensor [width, height]. |
Source code in geoai/extract.py
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 | |
__init__(raster_path, chip_size=(512, 512), overlap=0.5, transforms=None, band_indexes=None, verbose=False)
¶
Initialize the dataset with overlapping tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the input raster file. |
required |
chip_size
|
Tuple[int, int]
|
Size of image chips to extract (height, width). Default is (512, 512). |
(512, 512)
|
overlap
|
float
|
Amount of overlap between adjacent tiles (0.0-1.0). Default is 0.5 (50%). |
0.5
|
transforms
|
Optional[Any]
|
Transforms to apply to the image. Default is None. |
None
|
band_indexes
|
Optional[List[int]]
|
List of band indexes to use. Default is None (use all bands). |
None
|
verbose
|
bool
|
Whether to print detailed processing information. Default is False. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If overlap is too high resulting in non-positive stride. |
Source code in geoai/extract.py
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 | |
__len__()
¶
Return the number of samples in the dataset.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total number of tiles in the dataset. |
Source code in geoai/extract.py
269 270 271 272 273 274 275 276 | |
DetectionResult
dataclass
¶
Represents a detection result with score, label, bounding box, and optional mask.
Source code in geoai/segment.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | |
FocalLoss
¶
Bases: Module
Focal Loss for addressing class imbalance in segmentation.
Reference: Lin, T. Y., Goyal, P., Girshick, R., He, K., & Dollár, P. (2017). Focal loss for dense object detection. ICCV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
Weighting factor in range (0,1) to balance positive/negative examples |
1.0
|
|
gamma
|
Exponent of the modulating factor (1 - p_t)^gamma |
2.0
|
|
ignore_index
|
Specifies a target value that is ignored |
-100
|
|
reduction
|
Specifies the reduction to apply to the output |
'mean'
|
|
weight
|
Manual rescaling weight given to each class |
None
|
Source code in geoai/landcover_train.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
forward(inputs, targets)
¶
Forward pass of focal loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Predictions (N, C, H, W) where C = number of classes |
required | |
targets
|
Ground truth (N, H, W) with class indices |
required |
Returns:
| Type | Description |
|---|---|
|
Loss value |
Source code in geoai/landcover_train.py
53 54 55 56 57 58 59 60 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 | |
GroundedSAM
¶
A class for segmenting remote sensing imagery using text prompts with Grounding DINO + SAM.
This class combines Grounding DINO for object detection and Segment Anything Model (SAM) for precise segmentation based on text prompts. It can process large GeoTIFF files by tiling them and handles proper georeferencing in the outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
detector_id
|
str
|
Hugging Face model ID for Grounding DINO. Defaults to "IDEA-Research/grounding-dino-tiny". |
'IDEA-Research/grounding-dino-tiny'
|
segmenter_id
|
str
|
Hugging Face model ID for SAM. Defaults to "facebook/sam-vit-base". |
'facebook/sam-vit-base'
|
device
|
str
|
Device to run the models on ('cuda', 'cpu'). If None, will use CUDA if available. |
None
|
tile_size
|
int
|
Size of tiles to process the image in chunks. Defaults to 1024. |
1024
|
overlap
|
int
|
Overlap between tiles to avoid edge artifacts. Defaults to 128. |
128
|
threshold
|
float
|
Detection threshold for Grounding DINO. Defaults to 0.3. |
0.3
|
Attributes:
| Name | Type | Description |
|---|---|---|
detector_id |
str
|
The Grounding DINO model ID. |
segmenter_id |
str
|
The SAM model ID. |
device |
str
|
The device being used ('cuda' or 'cpu'). |
tile_size |
int
|
Size of tiles for processing. |
overlap |
int
|
Overlap between tiles. |
threshold |
float
|
Detection threshold. |
object_detector |
float
|
The Grounding DINO pipeline. |
segmentator |
float
|
The SAM model. |
processor |
float
|
The SAM processor. |
Source code in geoai/segment.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
__init__(detector_id='IDEA-Research/grounding-dino-tiny', segmenter_id='facebook/sam-vit-base', device=None, tile_size=1024, overlap=128, threshold=0.3)
¶
Initialize the GroundedSAM with the specified models and settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
detector_id
|
str
|
Hugging Face model ID for Grounding DINO. |
'IDEA-Research/grounding-dino-tiny'
|
segmenter_id
|
str
|
Hugging Face model ID for SAM. |
'facebook/sam-vit-base'
|
device
|
str
|
Device to run the models on ('cuda', 'cpu'). |
None
|
tile_size
|
int
|
Size of tiles to process the image in chunks. |
1024
|
overlap
|
int
|
Overlap between tiles to avoid edge artifacts. |
128
|
threshold
|
float
|
Detection threshold for Grounding DINO. |
0.3
|
Source code in geoai/segment.py
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 | |
segment_image(input_path, output_path, text_prompts, polygon_refinement=False, export_boxes=False, export_polygons=True, smoothing_sigma=1.0, nms_threshold=0.5, min_polygon_area=50, simplify_tolerance=2.0)
¶
Segment a GeoTIFF image using text prompts with improved instance segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Path to the input GeoTIFF file. |
required |
output_path
|
str
|
Path where the output GeoTIFF will be saved. |
required |
text_prompts
|
Union[str, List[str]]
|
Text prompt(s) describing what to segment. |
required |
polygon_refinement
|
bool
|
Whether to refine masks using polygon fitting. |
False
|
export_boxes
|
bool
|
Whether to export bounding boxes as a separate vector file. |
False
|
export_polygons
|
bool
|
Whether to export segmentation polygons as vector file. |
True
|
smoothing_sigma
|
float
|
Sigma value for Gaussian smoothing to reduce blockiness. |
1.0
|
nms_threshold
|
float
|
Non-maximum suppression threshold for removing overlapping detections. |
0.5
|
min_polygon_area
|
int
|
Minimum area in pixels for valid polygons. |
50
|
simplify_tolerance
|
float
|
Tolerance for polygon simplification. |
2.0
|
Returns:
| Name | Type | Description |
|---|---|---|
Dict |
str
|
Dictionary containing paths to output files. |
Source code in geoai/segment.py
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | |
LandcoverCrossEntropyLoss
¶
Bases: Module
Enhanced CrossEntropyLoss with optional ignore_index and class weights.
This extends the standard CrossEntropyLoss with more flexible ignore_index handling, specifically designed for landcover classification tasks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight
|
Optional[Tensor]
|
Manual rescaling weight given to each class |
None
|
ignore_index
|
Union[int, bool]
|
Specifies a target value that is ignored. - False: No values ignored (standard behavior) - int: Specific class index to ignore (e.g., 0 for background) |
False
|
reduction
|
str
|
Specifies the reduction to apply ('mean', 'sum', 'none') |
'mean'
|
Source code in geoai/landcover_train.py
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 | |
forward(input, target)
¶
Compute cross entropy loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input
|
Tensor
|
Predictions (N, C, H, W) where C = number of classes |
required |
target
|
Tensor
|
Ground truth (N, H, W) with class indices |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Loss value |
Source code in geoai/landcover_train.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | |
LeafMap
¶
Bases: Map
A subclass of leafmap.Map for GeoAI applications.
Source code in geoai/geoai.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
__init__(*args, **kwargs)
¶
Initialize the Map class.
Source code in geoai/geoai.py
59 60 61 | |
add_dinov3_gui(raster, processor, features, **kwargs)
¶
Add a DINOv3 GUI to the map.
Source code in geoai/geoai.py
63 64 65 66 67 68 69 70 71 | |
Map
¶
Bases: Map
A subclass of maplibregl.Map for GeoAI applications.
Source code in geoai/geoai.py
74 75 76 77 78 79 | |
__init__(*args, **kwargs)
¶
Initialize the Map class.
Source code in geoai/geoai.py
77 78 79 | |
ObjectDetector
¶
Object extraction using Mask R-CNN with TorchGeo.
Source code in geoai/extract.py
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 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 1415 1416 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 1474 1475 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 1516 1517 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 1550 1551 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 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 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 1750 1751 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 1843 1844 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 1912 1913 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 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 | |
__init__(model_path=None, repo_id=None, model=None, num_classes=2, device=None)
¶
Initialize the object extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
Optional[str]
|
Path to the .pth model file. |
None
|
repo_id
|
Optional[str]
|
Hugging Face repository ID for model download. |
None
|
model
|
Optional[Any]
|
Pre-initialized model object (optional). |
None
|
num_classes
|
int
|
Number of classes for detection (default: 2). |
2
|
device
|
Optional[str]
|
Device to use for inference ('cuda:0', 'cpu', etc.). |
None
|
Source code in geoai/extract.py
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 | |
download_model_from_hf(model_path=None, repo_id=None)
¶
Download the object detection model from Hugging Face.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
Optional[str]
|
Path to the model file. |
None
|
repo_id
|
Optional[str]
|
Hugging Face repository ID. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the downloaded model file |
Source code in geoai/extract.py
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 | |
filter_edge_objects(gdf, raster_path, edge_buffer=10)
¶
Filter out object detections that fall in padding/edge areas of the image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
GeoDataFrame with object detections |
required |
raster_path
|
str
|
Path to the original raster file |
required |
edge_buffer
|
int
|
Buffer in pixels to consider as edge region |
10
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with filtered objects |
Source code in geoai/extract.py
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 | |
filter_overlapping_polygons(gdf, **kwargs)
¶
Filter overlapping polygons using non-maximum suppression.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
GeoDataFrame with polygons |
required |
**kwargs
|
Any
|
Optional parameters: nms_iou_threshold: IoU threshold for filtering |
{}
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
Filtered GeoDataFrame |
Source code in geoai/extract.py
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 | |
generate_masks(raster_path, output_path=None, confidence_threshold=None, mask_threshold=None, min_object_area=10, max_object_area=float('inf'), overlap=0.25, batch_size=4, band_indexes=None, verbose=False, **kwargs)
¶
Save masks with confidence values as a multi-band GeoTIFF.
Objects with area smaller than min_object_area or larger than max_object_area will be filtered out.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to input raster |
required |
output_path
|
Optional[str]
|
Path for output GeoTIFF |
None
|
confidence_threshold
|
Optional[float]
|
Minimum confidence score (0.0-1.0) |
None
|
mask_threshold
|
Optional[float]
|
Threshold for mask binarization (0.0-1.0) |
None
|
min_object_area
|
int
|
Minimum area (in pixels) for an object to be included |
10
|
max_object_area
|
float
|
Maximum area (in pixels) for an object to be included |
float('inf')
|
overlap
|
float
|
Overlap between tiles (0.0-1.0) |
0.25
|
batch_size
|
int
|
Batch size for processing |
4
|
band_indexes
|
Optional[List[int]]
|
List of band indexes to use (default: all bands) |
None
|
verbose
|
bool
|
Whether to print detailed processing information |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the saved GeoTIFF |
Source code in geoai/extract.py
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 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 | |
initialize_model(model, num_classes=2)
¶
Initialize a deep learning model for object detection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
A pre-initialized model object. |
required |
num_classes
|
int
|
Number of classes for detection. |
2
|
Returns:
| Type | Description |
|---|---|
Any
|
torch.nn.Module: A deep learning model for object detection. |
Source code in geoai/extract.py
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 | |
load_weights(model_path)
¶
Load weights from file with error handling for different formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to model weights |
required |
Source code in geoai/extract.py
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 | |
mask_to_polygons(mask, **kwargs)
¶
Convert binary mask to polygon contours using OpenCV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
ndarray
|
Binary mask as numpy array |
required |
**kwargs
|
Any
|
Optional parameters: simplify_tolerance: Tolerance for polygon simplification mask_threshold: Threshold for mask binarization min_object_area: Minimum area in pixels to keep an object max_object_area: Maximum area in pixels to keep an object |
{}
|
Returns:
| Type | Description |
|---|---|
List[Polygon]
|
List of polygons as lists of (x, y) coordinates |
Source code in geoai/extract.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 | |
masks_to_vector(mask_path, output_path=None, simplify_tolerance=None, mask_threshold=None, min_object_area=None, max_object_area=None, nms_iou_threshold=None, regularize=True, angle_threshold=15, rectangularity_threshold=0.7)
¶
Convert an object mask GeoTIFF to vector polygons and save as GeoJSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_path
|
str
|
Path to the object masks GeoTIFF |
required |
output_path
|
Optional[str]
|
Path to save the output GeoJSON or Parquet file (default: mask_path with .geojson extension) |
None
|
simplify_tolerance
|
Optional[float]
|
Tolerance for polygon simplification (default: self.simplify_tolerance) |
None
|
mask_threshold
|
Optional[float]
|
Threshold for mask binarization (default: self.mask_threshold) |
None
|
min_object_area
|
Optional[int]
|
Minimum area in pixels to keep an object (default: self.min_object_area) |
None
|
max_object_area
|
Optional[int]
|
Minimum area in pixels to keep an object (default: self.max_object_area) |
None
|
nms_iou_threshold
|
Optional[float]
|
IoU threshold for non-maximum suppression (default: self.nms_iou_threshold) |
None
|
regularize
|
bool
|
Whether to regularize objects to right angles (default: True) |
True
|
angle_threshold
|
int
|
Maximum deviation from 90 degrees for regularization (default: 15) |
15
|
rectangularity_threshold
|
float
|
Threshold for rectangle simplification (default: 0.7) |
0.7
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with objects |
Source code in geoai/extract.py
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 | |
process_raster(raster_path, output_path=None, batch_size=4, filter_edges=True, edge_buffer=20, band_indexes=None, **kwargs)
¶
Process a raster file to extract objects with customizable parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to input raster file |
required |
output_path
|
Optional[str]
|
Path to output GeoJSON or Parquet file (optional) |
None
|
batch_size
|
int
|
Batch size for processing |
4
|
filter_edges
|
bool
|
Whether to filter out objects at the edges of the image |
True
|
edge_buffer
|
int
|
Size of edge buffer in pixels to filter out objects (if filter_edges=True) |
20
|
band_indexes
|
Optional[List[int]]
|
List of band indexes to use (if None, use all bands) |
None
|
**kwargs
|
Any
|
Additional parameters: confidence_threshold: Minimum confidence score to keep a detection (0.0-1.0) overlap: Overlap between adjacent tiles (0.0-1.0) chip_size: Size of image chips for processing (height, width) nms_iou_threshold: IoU threshold for non-maximum suppression (0.0-1.0) mask_threshold: Threshold for mask binarization (0.0-1.0) min_object_area: Minimum area in pixels to keep an object simplify_tolerance: Tolerance for polygon simplification |
{}
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with objects |
Source code in geoai/extract.py
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 | |
regularize_objects(gdf, min_area=10, angle_threshold=15, orthogonality_threshold=0.3, rectangularity_threshold=0.7)
¶
Regularize objects to enforce right angles and rectangular shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdf
|
GeoDataFrame
|
GeoDataFrame with objects |
required |
min_area
|
int
|
Minimum area in square units to keep an object |
10
|
angle_threshold
|
int
|
Maximum deviation from 90 degrees to consider an angle as orthogonal (degrees) |
15
|
orthogonality_threshold
|
float
|
Percentage of angles that must be orthogonal for an object to be regularized |
0.3
|
rectangularity_threshold
|
float
|
Minimum area ratio to Object's oriented bounding box for rectangular simplification |
0.7
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with regularized objects |
Source code in geoai/extract.py
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 1415 1416 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 1474 1475 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 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 | |
save_masks_as_geotiff(raster_path, output_path=None, batch_size=4, verbose=False, **kwargs)
¶
Process a raster file to extract object masks and save as GeoTIFF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to input raster file |
required |
output_path
|
Optional[str]
|
Path to output GeoTIFF file (optional, default: input_masks.tif) |
None
|
batch_size
|
int
|
Batch size for processing |
4
|
verbose
|
bool
|
Whether to print detailed processing information |
False
|
**kwargs
|
Any
|
Additional parameters: confidence_threshold: Minimum confidence score to keep a detection (0.0-1.0) chip_size: Size of image chips for processing (height, width) mask_threshold: Threshold for mask binarization (0.0-1.0) |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the saved GeoTIFF file |
Source code in geoai/extract.py
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 | |
vectorize_masks(masks_path, output_path=None, confidence_threshold=0.5, min_object_area=100, max_object_area=None, n_workers=None, **kwargs)
¶
Convert masks with confidence to vector polygons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
masks_path
|
str
|
Path to masks GeoTIFF with confidence band. |
required |
output_path
|
Optional[str]
|
Path for output GeoJSON. |
None
|
confidence_threshold
|
float
|
Minimum confidence score (0.0-1.0). Default: 0.5 |
0.5
|
min_object_area
|
int
|
Minimum area in pixels to keep an object. Default: 100 |
100
|
max_object_area
|
Optional[int]
|
Maximum area in pixels to keep an object. Default: None |
None
|
n_workers
|
Optional[int]
|
int, default=None The number of worker threads to use. "None" means single-threaded processing. "-1" means using all available CPU processors. Positive integer means using that specific number of threads. |
None
|
**kwargs
|
Any
|
Additional parameters |
{}
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
GeoDataFrame with car detections and confidence values |
Source code in geoai/extract.py
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 | |
visualize_results(raster_path, gdf=None, output_path=None, figsize=(12, 12))
¶
Visualize object detection results with proper coordinate transformation.
This function displays objects on top of the raster image, ensuring proper alignment between the GeoDataFrame polygons and the image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to input raster |
required |
gdf
|
Optional[GeoDataFrame]
|
GeoDataFrame with object polygons (optional) |
None
|
output_path
|
Optional[str]
|
Path to save visualization (optional) |
None
|
figsize
|
Tuple[int, int]
|
Figure size (width, height) in inches |
(12, 12)
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if visualization was successful |
Source code in geoai/extract.py
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 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 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 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 1750 1751 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 1843 1844 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 1912 1913 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 | |
ParkingSplotDetector
¶
Bases: ObjectDetector
Car detection using a pre-trained Mask R-CNN model.
This class extends the ObjectDetector class with additional methods for car detection.
Source code in geoai/extract.py
2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 | |
__init__(model_path='parking_spot_detection.pth', repo_id=None, model=None, num_classes=3, device=None)
¶
Initialize the object extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the .pth model file. |
'parking_spot_detection.pth'
|
repo_id
|
Optional[str]
|
Repo ID for loading models from the Hub. |
None
|
model
|
Optional[Any]
|
Custom model to use for inference. |
None
|
num_classes
|
int
|
Number of classes for the model. Default: 3 |
3
|
device
|
Optional[str]
|
Device to use for inference ('cuda:0', 'cpu', etc.). |
None
|
Source code in geoai/extract.py
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 | |
ShipDetector
¶
Bases: ObjectDetector
Ship detection using a pre-trained Mask R-CNN model.
This class extends the
ObjectDetector class with additional methods for ship detection."
Source code in geoai/extract.py
2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 | |
__init__(model_path='ship_detection.pth', repo_id=None, model=None, device=None)
¶
Initialize the object extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the .pth model file. |
'ship_detection.pth'
|
repo_id
|
Optional[str]
|
Repo ID for loading models from the Hub. |
None
|
model
|
Optional[Any]
|
Custom model to use for inference. |
None
|
device
|
Optional[str]
|
Device to use for inference ('cuda:0', 'cpu', etc.). |
None
|
Source code in geoai/extract.py
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 | |
SolarPanelDetector
¶
Bases: ObjectDetector
Solar panel detection using a pre-trained Mask R-CNN model.
This class extends the
ObjectDetector class with additional methods for solar panel detection."
Source code in geoai/extract.py
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 | |
__init__(model_path='solar_panel_detection.pth', repo_id=None, model=None, device=None)
¶
Initialize the object extractor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the .pth model file. |
'solar_panel_detection.pth'
|
repo_id
|
Optional[str]
|
Repo ID for loading models from the Hub. |
None
|
model
|
Optional[Any]
|
Custom model to use for inference. |
None
|
device
|
Optional[str]
|
Device to use for inference ('cuda:0', 'cpu', etc.). |
None
|
Source code in geoai/extract.py
2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 | |
adaptive_regularization(building_polygons, simplify_tolerance=0.5, area_threshold=0.9, preserve_shape=True)
¶
Adaptively regularizes building footprints based on their characteristics.
This approach determines the best regularization method for each building.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
building_polygons
|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons |
required |
simplify_tolerance
|
float
|
Distance tolerance for simplification |
0.5
|
area_threshold
|
float
|
Minimum acceptable area ratio |
0.9
|
preserve_shape
|
bool
|
Whether to preserve overall shape for complex buildings |
True
|
Returns:
| Type | Description |
|---|---|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons with regularized building footprints |
Source code in geoai/utils/geometry.py
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 | |
add_geometric_properties(data, properties=None, area_unit='m2', length_unit='m')
¶
Calculates geometric properties and adds them to the GeoDataFrame.
This function calculates various geometric properties of features in a GeoDataFrame and adds them as new columns without modifying existing attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
GeoDataFrame
|
GeoDataFrame containing vector features. |
required |
properties
|
Optional[List[str]]
|
List of geometric properties to calculate. Options include: 'area', 'length', 'perimeter', 'centroid_x', 'centroid_y', 'bounds', 'convex_hull_area', 'orientation', 'complexity', 'area_bbox', 'area_convex', 'area_filled', 'major_length', 'minor_length', 'eccentricity', 'diameter_area', 'extent', 'solidity', 'elongation'. Defaults to ['area', 'length'] if None. |
None
|
area_unit
|
str
|
String specifying the unit for area calculation ('m2', 'km2', 'ha'). Defaults to 'm2'. |
'm2'
|
length_unit
|
str
|
String specifying the unit for length calculation ('m', 'km'). Defaults to 'm'. |
'm'
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
geopandas.GeoDataFrame: A copy of the input GeoDataFrame with added |
GeoDataFrame
|
geometric property columns. |
Source code in geoai/utils/vector.py
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 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 | |
analyze_vector_attributes(vector_path, attribute_name)
¶
Analyze a specific attribute in a vector dataset and create a histogram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
attribute_name
|
str
|
Name of the attribute to analyze |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing analysis results for the attribute |
Source code in geoai/utils/vector.py
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 | |
batch_vector_to_raster(vector_path, output_dir, attribute_field=None, reference_rasters=None, bounds_list=None, output_filename_pattern='{vector_name}_{index}', pixel_size=1.0, all_touched=False, fill_value=0, dtype=np.uint8, nodata=None)
¶
Batch convert vector data to multiple rasters based on different extents or reference rasters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str or GeoDataFrame
|
Path to the input vector file or a GeoDataFrame. |
required |
output_dir
|
str
|
Directory to save output raster files. |
required |
attribute_field
|
str
|
Field name in the vector data to use for pixel values. |
None
|
reference_rasters
|
list
|
List of paths to reference rasters for dimensions, transform and CRS. |
None
|
bounds_list
|
list
|
List of bounds tuples (left, bottom, right, top) to use if reference_rasters not provided. |
None
|
output_filename_pattern
|
str
|
Pattern for output filenames. Can include {vector_name} and {index} placeholders. |
'{vector_name}_{index}'
|
pixel_size
|
float or tuple
|
Pixel size to use if reference_rasters not provided. |
1.0
|
all_touched
|
bool
|
If True, all pixels touched by geometries will be burned in. |
False
|
fill_value
|
int
|
Value to fill the raster with before burning in features. |
0
|
dtype
|
dtype
|
Data type of the output raster. |
uint8
|
nodata
|
int
|
No data value for the output raster. |
None
|
Returns:
| Type | Description |
|---|---|
List[str]
|
List[str]: List of paths to the created raster files. |
Source code in geoai/utils/raster.py
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 | |
bbox_to_xy(src_fp, coords, coord_crs='epsg:4326', **kwargs)
¶
Converts a list of coordinates to pixel coordinates, i.e., (col, row) coordinates. Note that map bbox coords is [minx, miny, maxx, maxy] from bottomleft to topright While rasterio bbox coords is [minx, max, maxx, min] from topleft to bottomright
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
coords
|
list
|
A list of coordinates in the format of [[minx, miny, maxx, maxy], [minx, miny, maxx, maxy], ...] |
required |
coord_crs
|
str
|
The coordinate CRS of the input coordinates. Defaults to "epsg:4326". |
'epsg:4326'
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
List[float]
|
A list of pixel coordinates in the format of [[minx, maxy, maxx, miny], ...] from top left to bottom right. |
Source code in geoai/utils/conversion.py
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 | |
boxes_to_vector(coords, src_crs, dst_crs='EPSG:4326', output=None, **kwargs)
¶
Convert a list of bounding box coordinates to vector data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
list
|
A list of bounding box coordinates in the format [[left, top, right, bottom], [left, top, right, bottom], ...]. |
required |
src_crs
|
int or str
|
The EPSG code or proj4 string representing the source coordinate reference system (CRS) of the input coordinates. |
required |
dst_crs
|
int or str
|
The EPSG code or proj4 string representing the destination CRS to reproject the data (default is "EPSG:4326"). |
'EPSG:4326'
|
output
|
str or None
|
The full file path (including the directory and filename without the extension) where the vector data should be saved. If None (default), the function returns the GeoDataFrame without saving it to a file. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to geopandas.GeoDataFrame.to_file() when saving the vector data. |
{}
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
geopandas.GeoDataFrame or None: The GeoDataFrame with the converted vector data if output is None, otherwise None if the data is saved to a file. |
Source code in geoai/utils/vector.py
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 | |
calc_stats(dataset, divide_by=1.0)
¶
Calculate the statistics (mean and std) for the entire dataset.
This function is adapted from the plot_batch() function in the torchgeo library at https://torchgeo.readthedocs.io/en/stable/tutorials/earth_surface_water.html. Credit to the torchgeo developers for the original implementation.
Warning: This is an approximation. The correct value should take into account the mean for the whole dataset for computing individual stds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
RasterDataset
|
The dataset to calculate statistics for. |
required |
divide_by
|
float
|
The value to divide the image data by. Defaults to 1.0. |
1.0
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Tuple[np.ndarray, np.ndarray]: The mean and standard deviation for each band. |
Source code in geoai/utils/raster.py
52 53 54 55 56 57 58 59 60 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 | |
clip_raster_by_bbox(input_raster, output_raster, bbox, bands=None, bbox_type='geo', bbox_crs=None)
¶
Clip a raster dataset using a bounding box and optionally select specific bands.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_raster
|
str
|
Path to the input raster file. |
required |
output_raster
|
str
|
Path where the clipped raster will be saved. |
required |
bbox
|
tuple
|
Bounding box coordinates either as: - Geographic coordinates (minx, miny, maxx, maxy) if bbox_type="geo" - Pixel indices (min_row, min_col, max_row, max_col) if bbox_type="pixel" |
required |
bands
|
list
|
List of band indices to keep (1-based indexing). If None, all bands will be kept. |
None
|
bbox_type
|
str
|
Type of bounding box coordinates. Either "geo" for geographic coordinates or "pixel" for row/column indices. Default is "geo". |
'geo'
|
bbox_crs
|
str or dict
|
CRS of the bbox if different from the raster CRS. Can be provided as EPSG code (e.g., "EPSG:4326") or as a proj4 string. Only applies when bbox_type="geo". If None, assumes bbox is in the same CRS as the raster. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the clipped output raster. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If required dependencies are not installed. |
ValueError
|
If the bbox is invalid, bands are out of range, or bbox_type is invalid. |
RuntimeError
|
If the clipping operation fails. |
Examples:
Clip using geographic coordinates in the same CRS as the raster
1 2 | |
Clip using WGS84 coordinates when the raster is in a different CRS
1 2 3 | |
Clip using row/column indices
1 2 3 | |
Clip with band selection
1 2 3 | |
Source code in geoai/utils/raster.py
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 | |
compute_class_weights(labels_dir, num_classes, ignore_index=-100, custom_multipliers=None, max_weight=50.0, use_inverse_frequency=True)
¶
Compute class weights for imbalanced datasets with optional custom multipliers and maximum weight cap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels_dir
|
str
|
Directory containing label files |
required |
num_classes
|
int
|
Number of classes |
required |
ignore_index
|
Union[int, bool]
|
Class index to ignore when computing weights. - If int: specific class to ignore (pixels will be excluded from weight calc) - If False: no class ignored (all classes contribute to weights) |
-100
|
custom_multipliers
|
Optional[Dict[int, float]]
|
Custom multipliers for specific classes after inverse frequency calculation. Format: {class_id: multiplier} Example: {1: 0.5, 7: 2.0} - reduce class 1 weight by half, double class 7 weight |
None
|
max_weight
|
float
|
Maximum allowed weight value to prevent extreme values (default: 50.0) |
50.0
|
use_inverse_frequency
|
bool
|
Whether to compute inverse frequency weights. - True (default): Compute inverse frequency weights, then apply custom multipliers - False: Use uniform weights (1.0) for all classes, then apply custom multipliers |
True
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Tensor of class weights (num_classes,) with custom adjustments and maximum weight cap applied |
Source code in geoai/landcover_train.py
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | |
coords_to_xy(src_fp, coords, coord_crs='epsg:4326', return_out_of_bounds=False, **kwargs)
¶
Converts a list or array of coordinates to pixel coordinates, i.e., (col, row) coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
coords
|
ndarray
|
A 2D or 3D array of coordinates. Can be of shape [[x1, y1], [x2, y2], ...] or [[[x1, y1]], [[x2, y2]], ...]. |
required |
coord_crs
|
str
|
The coordinate CRS of the input coordinates. Defaults to "epsg:4326". |
'epsg:4326'
|
return_out_of_bounds
|
bool
|
Whether to return out-of-bounds coordinates. Defaults to False. |
False
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rasterio.transform.rowcol. |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2D or 3D array of pixel coordinates in the same format as the input. |
Source code in geoai/utils/conversion.py
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 | |
create_vector_data(m=None, properties=None, time_format='%Y%m%dT%H%M%S', column_widths=(9, 3), map_height='600px', out_dir=None, filename_prefix='', file_ext='geojson', add_mapillary=False, style='photo', radius=5e-05, width=300, height=420, frame_border=0, **kwargs)
¶
Generates a widget-based interface for creating and managing vector data on a map.
This function creates an interactive widget interface that allows users to draw features (points, lines, polygons) on a map, assign properties to these features, and export them as GeoJSON files. The interface includes a map, a sidebar for property management, and buttons for saving, exporting, and resetting the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m
|
Map
|
An existing Map object. If not provided, a default map with basemaps and drawing controls will be created. Defaults to None. |
None
|
properties
|
Dict[str, List[Any]]
|
A dictionary where keys are property names and values are lists of possible values for each property. These properties can be assigned to the drawn features. Defaults to None. |
None
|
time_format
|
str
|
The format string for the timestamp used in the exported filename. Defaults to "%Y%m%dT%H%M%S". |
'%Y%m%dT%H%M%S'
|
column_widths
|
Optional[List[int]]
|
A list of two integers specifying the relative widths of the map and sidebar columns. Defaults to (9, 3). |
(9, 3)
|
map_height
|
str
|
The height of the map widget. Defaults to "600px". |
'600px'
|
out_dir
|
str
|
The directory where the exported GeoJSON files will be saved. If not provided, the current working directory is used. Defaults to None. |
None
|
filename_prefix
|
str
|
A prefix to be added to the exported filename. Defaults to "". |
''
|
file_ext
|
str
|
The file extension for the exported file. Defaults to "geojson". |
'geojson'
|
add_mapillary
|
bool
|
Whether to add a Mapillary image widget that displays the nearest image to the clicked point on the map. Defaults to False. |
False
|
style
|
str
|
The style of the Mapillary image widget. Can be "classic", "photo", or "split". Defaults to "photo". |
'photo'
|
radius
|
float
|
The radius (in degrees) used to search for the nearest Mapillary image. Defaults to 0.00005 degrees. |
5e-05
|
width
|
int
|
The width of the Mapillary image widget. Defaults to 300. |
300
|
height
|
int
|
The height of the Mapillary image widget. Defaults to 420. |
420
|
frame_border
|
int
|
The width of the frame border for the Mapillary image widget. Defaults to 0. |
0
|
**kwargs
|
Any
|
Additional keyword arguments that may be passed to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
widgets.VBox: A vertical box widget containing the map, sidebar, and control buttons. |
Example
properties = { ... "Type": ["Residential", "Commercial", "Industrial"], ... "Area": [100, 200, 300], ... } widget = create_vector_data(properties=properties) display(widget) # Display the widget in a Jupyter notebook
Source code in geoai/geoai.py
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 | |
dict_to_image(data_dict, output=None, **kwargs)
¶
Convert a dictionary containing spatial data to a rasterio dataset or save it to a file. The dictionary should contain the following keys: "crs", "bounds", and "image". It can be generated from a TorchGeo dataset sampler.
This function transforms a dictionary with CRS, bounding box, and image data into a rasterio DatasetReader using leafmap's array_to_image utility after first converting to a rioxarray DataArray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dict
|
Dict[str, Any]
|
A dictionary containing: - 'crs': A pyproj CRS object - 'bounds': A BoundingBox object with minx, maxx, miny, maxy attributes and optionally mint, maxt for temporal bounds - 'image': A tensor or array-like object with image data |
required |
output
|
Optional[str]
|
Optional path to save the image to a file. If not provided, the image will be returned as a rasterio DatasetReader object. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to leafmap.array_to_image. Common options include: - colormap: str, name of the colormap (e.g., 'viridis', 'terrain') - vmin: float, minimum value for colormap scaling - vmax: float, maximum value for colormap scaling |
{}
|
Returns:
| Type | Description |
|---|---|
Union[str, Any]
|
A rasterio DatasetReader object that can be used for visualization or |
Union[str, Any]
|
further processing. |
Examples:
1 2 3 4 5 6 | |
Source code in geoai/utils/conversion.py
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 | |
dict_to_rioxarray(data_dict)
¶
Convert a dictionary to a xarray DataArray. The dictionary should contain the following keys: "crs", "bounds", and "image". It can be generated from a TorchGeo dataset sampler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_dict
|
Dict
|
The dictionary containing the data. |
required |
Returns:
| Type | Description |
|---|---|
DataArray
|
xr.DataArray: The xarray DataArray. |
Source code in geoai/utils/conversion.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
download_file(url, output_path=None, overwrite=False, unzip=True)
¶
Download a file from a given URL with a progress bar. Optionally unzip the file if it's a ZIP archive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
The URL of the file to download. |
required |
output_path
|
str
|
The path where the downloaded file will be saved. If not provided, the filename from the URL will be used. |
None
|
overwrite
|
bool
|
Whether to overwrite the file if it already exists. |
False
|
unzip
|
bool
|
Whether to unzip the file if it is a ZIP archive. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The path to the downloaded file or the extracted directory. |
Source code in geoai/utils/download.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
download_model_from_hf(model_path, repo_id=None)
¶
Download the object detection model from Hugging Face.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
|
str
|
Path to the model file. |
required |
repo_id
|
Optional[str]
|
Hugging Face repository ID. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Path to the downloaded model file |
Source code in geoai/utils/download.py
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 | |
edit_vector_data(m=None, filename=None, properties=None, time_format='%Y%m%dT%H%M%S', column_widths=(9, 3), map_height='600px', out_dir=None, filename_prefix='', file_ext='geojson', add_mapillary=False, style='photo', radius=5e-05, width=300, height=420, frame_border=0, controls=None, position='top-right', fit_bounds_options=None, **kwargs)
¶
Generates a widget-based interface for creating and managing vector data on a map.
This function creates an interactive widget interface that allows users to draw features (points, lines, polygons) on a map, assign properties to these features, and export them as GeoJSON files. The interface includes a map, a sidebar for property management, and buttons for saving, exporting, and resetting the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
m
|
Map
|
An existing Map object. If not provided, a default map with basemaps and drawing controls will be created. Defaults to None. |
None
|
filename
|
str or GeoDataFrame
|
The path to a GeoJSON file or a GeoDataFrame containing the vector data to be edited. Defaults to None. |
None
|
properties
|
Dict[str, List[Any]]
|
A dictionary where keys are property names and values are lists of possible values for each property. These properties can be assigned to the drawn features. Defaults to None. |
None
|
time_format
|
str
|
The format string for the timestamp used in the exported filename. Defaults to "%Y%m%dT%H%M%S". |
'%Y%m%dT%H%M%S'
|
column_widths
|
Optional[List[int]]
|
A list of two integers specifying the relative widths of the map and sidebar columns. Defaults to (9, 3). |
(9, 3)
|
map_height
|
str
|
The height of the map widget. Defaults to "600px". |
'600px'
|
out_dir
|
str
|
The directory where the exported GeoJSON files will be saved. If not provided, the current working directory is used. Defaults to None. |
None
|
filename_prefix
|
str
|
A prefix to be added to the exported filename. Defaults to "". |
''
|
file_ext
|
str
|
The file extension for the exported file. Defaults to "geojson". |
'geojson'
|
add_mapillary
|
bool
|
Whether to add a Mapillary image widget that displays the nearest image to the clicked point on the map. Defaults to False. |
False
|
style
|
str
|
The style of the Mapillary image widget. Can be "classic", "photo", or "split". Defaults to "photo". |
'photo'
|
radius
|
float
|
The radius (in degrees) used to search for the nearest Mapillary image. Defaults to 0.00005 degrees. |
5e-05
|
width
|
int
|
The width of the Mapillary image widget. Defaults to 300. |
300
|
height
|
int
|
The height of the Mapillary image widget. Defaults to 420. |
420
|
frame_border
|
int
|
The width of the frame border for the Mapillary image widget. Defaults to 0. |
0
|
controls
|
Optional[List[str]]
|
The drawing controls to be added to the map. Defaults to ["point", "polygon", "line_string", "trash"]. |
None
|
position
|
str
|
The position of the drawing controls on the map. Defaults to "top-right". |
'top-right'
|
**kwargs
|
Any
|
Additional keyword arguments that may be passed to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
widgets.VBox: A vertical box widget containing the map, sidebar, and control buttons. |
Source code in geoai/geoai.py
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 | |
empty_cache()
¶
Empty the cache of the current device.
Source code in geoai/utils/device.py
85 86 87 88 89 90 91 92 | |
evaluate_sparse_iou(model, images_dir, labels_dir, num_classes, num_channels=3, batch_size=8, background_class=0, ignore_index=False, device=None, verbose=True)
¶
Evaluate a trained model using sparse labels IoU.
This function is designed for incomplete/sparse ground truth where background (0) means "unlabeled" rather than "definitely not this class". Predictions in background areas are NOT penalized as false positives.
Use this for post-training evaluation when your training masks are incomplete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Trained segmentation model |
required |
images_dir
|
str
|
Directory containing validation images |
required |
labels_dir
|
str
|
Directory containing validation labels |
required |
num_classes
|
int
|
Number of classes |
required |
num_channels
|
int
|
Number of input channels (default: 3) |
3
|
batch_size
|
int
|
Batch size for evaluation (default: 8) |
8
|
background_class
|
int
|
Class ID for background/unlabeled pixels (default: 0) |
0
|
ignore_index
|
Union[int, bool]
|
Class to ignore during evaluation. - If int: specific class index to ignore - If False: no class ignored (default) |
False
|
device
|
Optional[device]
|
Torch device (auto-detected if None) |
None
|
verbose
|
bool
|
Print detailed results (default: True) |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing: |
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Dict[str, Any]
|
|
Example
model = torch.load("best_model.pth") results = evaluate_sparse_iou( ... model=model, ... images_dir="tiles/images", ... labels_dir="tiles/labels", ... num_classes=18, ... background_class=0, ... ) print(f"Sparse IoU: {results['mean_sparse_iou']:.4f}")
Source code in geoai/landcover_train.py
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 1474 1475 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 1516 1517 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 1550 1551 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 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 | |
export_landcover_tiles(in_raster, out_folder, in_class_data=None, tile_size=256, stride=128, class_value_field='class', buffer_radius=0, max_tiles=None, quiet=False, all_touched=True, create_overview=False, skip_empty_tiles=False, min_feature_ratio=False, metadata_format='PASCAL_VOC')
¶
Export GeoTIFF tiles optimized for landcover classification training.
This function extends the base export_geotiff_tiles with enhanced filtering capabilities specifically designed for discrete landcover classification. It can filter out tiles dominated by background pixels to improve training data quality and reduce dataset size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
in_raster
|
str
|
Path to input raster (image to tile) |
required |
out_folder
|
str
|
Output directory for tiles |
required |
in_class_data
|
Optional[Union[str, GeoDataFrame]]
|
Path to vector mask or GeoDataFrame (optional for image-only export) |
None
|
tile_size
|
int
|
Size of output tiles in pixels (default: 256) |
256
|
stride
|
int
|
Stride for sliding window (default: 128) |
128
|
class_value_field
|
str
|
Field name containing class values (default: "class") |
'class'
|
buffer_radius
|
float
|
Buffer radius around features in pixels (default: 0) |
0
|
max_tiles
|
Optional[int]
|
Maximum number of tiles to export (default: None) |
None
|
quiet
|
bool
|
Suppress progress output (default: False) |
False
|
all_touched
|
bool
|
Include pixels touched by geometry (default: True) |
True
|
create_overview
|
bool
|
Create overview image showing tile locations (default: False) |
False
|
skip_empty_tiles
|
bool
|
Skip tiles with no features (default: False) |
False
|
min_feature_ratio
|
Union[bool, float]
|
Minimum ratio of non-background pixels required to keep tile - False: Disable ratio filtering (default) - 0.0-1.0: Minimum ratio threshold (e.g., 0.1 = 10% features required) |
False
|
metadata_format
|
str
|
Annotation format ("PASCAL_VOC" or "YOLO") |
'PASCAL_VOC'
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing: - tiles_exported: Number of tiles successfully exported - tiles_skipped_empty: Number of completely empty tiles skipped - tiles_skipped_ratio: Number of tiles filtered by min_feature_ratio - output_dirs: Dictionary with paths to images and labels directories |
Examples:
Original behavior (no filtering)¶
export_landcover_tiles( "input.tif", "output", "mask.shp", skip_empty_tiles=True )
Light filtering (keep tiles with ≥5% features)¶
export_landcover_tiles( "input.tif", "output", "mask.shp", skip_empty_tiles=True, min_feature_ratio=0.05 )
Moderate filtering (keep tiles with ≥15% features)¶
export_landcover_tiles( "input.tif", "output", "mask.shp", skip_empty_tiles=True, min_feature_ratio=0.15 )
Note
This function is designed for discrete landcover classification where class 0 typically represents background/no data. The min_feature_ratio parameter counts non-zero pixels as "features".
Source code in geoai/landcover_utils.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
export_tiles_to_geojson(tile_coordinates, src, output_path, tile_size=None, stride=None)
¶
Export tile rectangles directly to GeoJSON without creating an overview image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile_coordinates
|
list
|
A list of dictionaries containing tile information. |
required |
src
|
DatasetReader
|
The source raster dataset. |
required |
output_path
|
str
|
The path where the GeoJSON will be saved. |
required |
tile_size
|
int
|
The size of each tile in pixels. Only needed if not in tile_coordinates. |
None
|
stride
|
int
|
The stride between tiles in pixels. Used to calculate overlaps between tiles. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the saved GeoJSON file. |
Source code in geoai/utils/vector.py
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 | |
geojson_to_coords(geojson, src_crs='epsg:4326', dst_crs='epsg:4326')
¶
Converts a geojson file or a dictionary of feature collection to a list of centroid coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geojson
|
str | dict
|
The geojson file path or a dictionary of feature collection. |
required |
src_crs
|
str
|
The source CRS. Defaults to "epsg:4326". |
'epsg:4326'
|
dst_crs
|
str
|
The destination CRS. Defaults to "epsg:4326". |
'epsg:4326'
|
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
A list of centroid coordinates in the format of [[x1, y1], [x2, y2], ...] |
Source code in geoai/utils/vector.py
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 | |
geojson_to_xy(src_fp, geojson, coord_crs='epsg:4326', **kwargs)
¶
Converts a geojson file or a dictionary of feature collection to a list of pixel coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
geojson
|
str
|
The geojson file path or a dictionary of feature collection. |
required |
coord_crs
|
str
|
The coordinate CRS of the input coordinates. Defaults to "epsg:4326". |
'epsg:4326'
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rasterio.transform.rowcol. |
{}
|
Returns:
| Type | Description |
|---|---|
List[List[float]]
|
A list of pixel coordinates in the format of [[x1, y1], [x2, y2], ...] |
Source code in geoai/utils/vector.py
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 | |
get_device()
¶
Returns the best available device for deep learning in the order: CUDA (NVIDIA GPU) > MPS (Apple Silicon GPU) > CPU
Source code in geoai/utils/device.py
70 71 72 73 74 75 76 77 78 79 80 81 82 | |
get_landcover_loss_function(loss_name='crossentropy', num_classes=2, ignore_index=-100, class_weights=None, use_class_weights=False, focal_alpha=1.0, focal_gamma=2.0, device=None)
¶
Get loss function configured for landcover classification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss_name
|
str
|
Name of loss function ("crossentropy", "focal", "dice", "combo") |
'crossentropy'
|
num_classes
|
int
|
Number of classes |
2
|
ignore_index
|
Union[int, bool]
|
Class index to ignore, or False to not ignore any class. - If int: pixels with this label value will be ignored during training - If False: no pixels will be ignored (all pixels contribute to loss) |
-100
|
class_weights
|
Optional[Tensor]
|
Manual class weights tensor |
None
|
use_class_weights
|
bool
|
Whether to use class weights |
False
|
focal_alpha
|
float
|
Alpha parameter for focal loss |
1.0
|
focal_gamma
|
float
|
Gamma parameter for focal loss |
2.0
|
device
|
Optional[device]
|
Device to place loss function on |
None
|
Returns:
| Type | Description |
|---|---|
Module
|
Configured loss function |
Source code in geoai/landcover_train.py
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 | |
get_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. |
required |
Returns:
| Type | Description |
|---|---|
PretrainedConfig
|
transformers.configuration_utils.PretrainedConfig: The model configuration. |
Source code in geoai/hf.py
22 23 24 25 26 27 28 29 30 31 32 33 34 | |
get_model_input_channels(model_id)
¶
Check the number of input channels supported by a Hugging Face model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
The Hugging Face model ID. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of input channels the model accepts. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If unable to determine the number of input channels. |
Source code in geoai/hf.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
get_raster_info(raster_path)
¶
Display basic information about a raster dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict[str, Any]
|
Dictionary containing the basic information about the raster |
Source code in geoai/utils/raster.py
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 | |
get_raster_info_gdal(raster_path)
¶
Get basic information about a raster dataset using GDAL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing the basic information about the raster, or None if the file cannot be opened |
Source code in geoai/utils/raster.py
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 | |
get_raster_resolution(image_path)
¶
Get pixel resolution from the raster using rasterio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
|
str
|
The path to the raster image. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[float, float]
|
A tuple of (x resolution, y resolution). |
Source code in geoai/utils/raster.py
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 | |
get_raster_stats(raster_path, divide_by=1.0)
¶
Calculate statistics for each band in a raster dataset.
This function computes min, max, mean, and standard deviation values for each band in the provided raster, returning results in a dictionary with lists for each statistic type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
divide_by
|
float
|
Value to divide pixel values by. Defaults to 1.0, which keeps the original pixel |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict[str, Any]
|
Dictionary containing lists of statistics with keys: - 'min': List of minimum values for each band - 'max': List of maximum values for each band - 'mean': List of mean values for each band - 'std': List of standard deviation values for each band |
Source code in geoai/utils/raster.py
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 | |
get_vector_info(vector_path)
¶
Display basic information about a vector dataset using GeoPandas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing the basic information about the vector dataset |
Source code in geoai/utils/vector.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
get_vector_info_ogr(vector_path)
¶
Get basic information about a vector dataset using OGR.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing the basic information about the vector dataset, or None if the file cannot be opened |
Source code in geoai/utils/vector.py
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 | |
hybrid_regularization(building_polygons)
¶
A comprehensive hybrid approach to building footprint regularization.
Applies different strategies based on building characteristics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
building_polygons
|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons containing building footprints |
required |
Returns:
| Type | Description |
|---|---|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons with regularized building footprints |
Source code in geoai/utils/geometry.py
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 | |
image_segmentation(tif_path, output_path, labels_to_extract=None, dtype='uint8', model_name=None, segmenter_args=None, **kwargs)
¶
Segments an image with a Hugging Face segmentation model and saves the results as a single georeferenced image where each class has a unique integer value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tif_path
|
str
|
Path to the input georeferenced TIF file. |
required |
output_path
|
str
|
Path where the output georeferenced segmentation will be saved. |
required |
labels_to_extract
|
list
|
List of labels to extract. If None, extracts all labels. |
None
|
dtype
|
str
|
Data type to use for the output mask. Defaults to "uint8". |
'uint8'
|
model_name
|
str
|
Name of the Hugging Face model to use for segmentation, such as "facebook/mask2former-swin-large-cityscapes-semantic". Defaults to None. See https://huggingface.co/models?pipeline_tag=image-segmentation&sort=trending for options. |
None
|
segmenter_args
|
dict
|
Additional arguments to pass to the segmenter. Defaults to None. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the segmentation pipeline |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
str
|
(Path to saved image, dictionary mapping label names to their assigned values, dictionary mapping label names to confidence scores) |
Source code in geoai/hf.py
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 | |
install_package(package)
¶
Install a Python package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
package
|
str | list
|
The package name or a GitHub URL or a list of package names or GitHub URLs. |
required |
Source code in geoai/utils/device.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
landcover_iou(pred, target, num_classes, ignore_index=False, smooth=1e-06, mode='mean', boundary_weight_map=None, background_class=None)
¶
Calculate IoU for landcover classification with multiple weighting options.
Supports four IoU calculation modes: 1. "mean": Simple mean IoU across all classes 2. "perclass_frequency": Weight by per-class pixel frequency 3. "boundary_weighted": Weight by distance to class boundaries 4. "sparse_labels": For incomplete ground truth - only penalize FP where GT is positive (does NOT penalize predictions in unlabeled/background areas)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pred
|
Tensor
|
Predicted classes (N, H, W) or logits (N, C, H, W) |
required |
target
|
Tensor
|
Ground truth (N, H, W) |
required |
num_classes
|
int
|
Number of classes |
required |
ignore_index
|
Union[int, bool]
|
Class index to ignore (default: None) |
False
|
smooth
|
float
|
Smoothing factor to avoid division by zero |
1e-06
|
mode
|
str
|
IoU calculation mode ("mean", "perclass_frequency", "boundary_weighted", "sparse_labels") |
'mean'
|
boundary_weight_map
|
Optional[Tensor]
|
Optional boundary weights (N, H, W) |
None
|
background_class
|
Optional[int]
|
Background/unlabeled class for sparse_labels mode (default: 0) |
None
|
Returns:
| Type | Description |
|---|---|
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "mean": float (mean IoU) |
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "perclass_frequency": tuple (weighted IoU, per-class IoUs, class counts) |
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "boundary_weighted": float (boundary-weighted IoU) |
Union[float, Tuple[float, List[float], List[int]]]
|
If mode == "sparse_labels": tuple (sparse IoU, per-class IoUs, per-class recall, per-class precision) |
Source code in geoai/landcover_train.py
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 | |
mask_generation(input_path, output_mask_path, output_csv_path, model='facebook/sam-vit-base', confidence_threshold=0.5, points_per_side=32, crop_size=None, batch_size=1, band_indices=None, min_object_size=0, generator_kwargs=None, **kwargs)
¶
Process a GeoTIFF using SAM mask generation and save results as a GeoTIFF and CSV.
The function reads a GeoTIFF image, applies the SAM mask generator from the Hugging Face transformers pipeline, rasterizes the resulting masks to create a labeled mask GeoTIFF, and saves mask scores and geometries to a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Path to the input GeoTIFF image. |
required |
output_mask_path
|
str
|
Path where the output mask GeoTIFF will be saved. |
required |
output_csv_path
|
str
|
Path where the mask scores CSV will be saved. |
required |
model
|
str
|
HuggingFace model checkpoint for the SAM model. |
'facebook/sam-vit-base'
|
confidence_threshold
|
float
|
Minimum confidence score for masks to be included. |
0.5
|
points_per_side
|
int
|
Number of points to sample along each side of the image. |
32
|
crop_size
|
Optional[int]
|
Size of image crops for processing. If None, process the full image. |
None
|
band_indices
|
Optional[List[int]]
|
List of band indices to use. If None, use all bands. |
None
|
batch_size
|
int
|
Batch size for inference. |
1
|
min_object_size
|
int
|
Minimum size in pixels for objects to be included. Smaller masks will be filtered out. |
0
|
generator_kwargs
|
Optional[Dict]
|
Additional keyword arguments to pass to the mask generator. |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[str, str]
|
Tuple containing the paths to the saved mask GeoTIFF and CSV file. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input file cannot be opened or processed. |
RuntimeError
|
If mask generation fails. |
Source code in geoai/hf.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
masks_to_vector(mask_path, output_path=None, simplify_tolerance=1.0, mask_threshold=0.5, min_object_area=100, max_object_area=None, nms_iou_threshold=0.5)
¶
Convert a building mask GeoTIFF to vector polygons and save as a vector dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask_path
|
str
|
Path to the building masks GeoTIFF |
required |
output_path
|
Optional[str]
|
Path to save the output GeoJSON (default: mask_path with .geojson extension) |
None
|
simplify_tolerance
|
float
|
Tolerance for polygon simplification (default: self.simplify_tolerance) |
1.0
|
mask_threshold
|
float
|
Threshold for mask binarization (default: self.mask_threshold) |
0.5
|
min_object_area
|
int
|
Minimum area in pixels to keep a building (default: self.min_object_area) |
100
|
max_object_area
|
Optional[int]
|
Maximum area in pixels to keep a building (default: self.max_object_area) |
None
|
nms_iou_threshold
|
float
|
IoU threshold for non-maximum suppression (default: self.nms_iou_threshold) |
0.5
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
GeoDataFrame with building footprints |
Source code in geoai/utils/raster.py
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 | |
mosaic_geotiffs(input_dir, output_file, mask_file=None)
¶
Create a mosaic from all GeoTIFF files as a Cloud Optimized GeoTIFF (COG).
This function identifies all GeoTIFF files in the specified directory, creates a seamless mosaic with proper handling of nodata values, and saves as a Cloud Optimized GeoTIFF format. If a mask file is provided, the output will be clipped to the extent of the mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
str
|
Path to the directory containing GeoTIFF files. |
required |
output_file
|
str
|
Path to the output Cloud Optimized GeoTIFF file. |
required |
mask_file
|
str
|
Path to a mask file to clip the output. If provided, the output will be clipped to the extent of this mask. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
None
|
True if the mosaic was created successfully, False otherwise. |
Examples:
1 2 3 4 | |
Source code in geoai/utils/raster.py
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 1474 1475 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 1516 1517 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 1550 1551 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 | |
normalize_radiometric(subject_image, reference_image, output_path=None, method='lirrn', p_n=500, num_quantisation_classes=3, num_sampling_rounds=3, subsample_ratio=0.1, random_state=None)
¶
Normalize subject image radiometry to match a reference image.
Adjusts brightness and contrast of the subject image so that its pixel value distribution matches the reference image. This is essential for multi-temporal analysis where images are acquired under different atmospheric conditions, sensor calibrations, or illumination angles.
Currently supports the LIRRN (Location-Independent Relative Radiometric Normalization) method, which uses multi-Otsu thresholding and linear regression to identify pseudo-invariant features and transform pixel values band-by-band.
Reference: doi:10.3390/s24072272
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject_image
|
Union[str, ndarray]
|
Path to the subject GeoTIFF or numpy array with shape (H, W, B). The image to be normalized. |
required |
reference_image
|
Union[str, ndarray]
|
Path to the reference GeoTIFF or numpy array with shape (H, W, B). The target radiometry to match. |
required |
output_path
|
Optional[str]
|
Path to save the normalized image as GeoTIFF. Only applicable when subject_image is a file path (so spatial metadata is available). If None, the array is returned without saving. Default: None. |
None
|
method
|
str
|
Normalization method. Currently only |
'lirrn'
|
p_n
|
int
|
Number of pseudo-invariant feature samples per quantization level. Higher values increase accuracy but slow computation. Default: 500. |
500
|
num_quantisation_classes
|
int
|
Number of brightness strata for stratified sampling. Default: 3. |
3
|
num_sampling_rounds
|
int
|
Number of iterative refinement rounds for sample selection. Default: 3. |
3
|
subsample_ratio
|
float
|
Fraction of candidates retained for regression. Default: 0.1. |
0.1
|
random_state
|
Optional[Union[int, Generator]]
|
Seed or numpy Generator for reproducible results. Default: None (non-deterministic). |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, Dict[str, ndarray]]
|
Tuple of (normalized_image, metrics) where:
- normalized_image: numpy array (H, W, B) float64.
- metrics: dict with keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If method is not |
ValueError
|
If p_n < 1 or num_sampling_rounds < 1. |
ValueError
|
If subject and reference have different band counts. |
ValueError
|
If input arrays are not 3-dimensional. |
ValueError
|
If output_path is set but subject_image is an array. |
FileNotFoundError
|
If file paths do not point to existing files. |
Examples:
Normalize a satellite image using file paths:
1 2 3 4 5 6 7 | |
Normalize using numpy arrays:
1 2 3 4 5 6 | |
Note
The subject and reference images must have the same number of bands but may have different spatial dimensions (height and width).
Source code in geoai/landcover_utils.py
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 | |
orthogonalize(input_path, output_path=None, epsilon=0.2, min_area=10, min_segments=4, area_tolerance=0.7, detect_triangles=True)
¶
Orthogonalizes object masks in a GeoTIFF file.
This function reads a GeoTIFF containing object masks (binary or labeled regions), converts the raster masks to vector polygons, applies orthogonalization to each polygon, and optionally writes the result to a GeoJSON file. The source code is adapted from the Solar Panel Detection algorithm by Esri. See https://www.arcgis.com/home/item.html?id=c2508d72f2614104bfcfd5ccf1429284. Credits to Esri for the original code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
str
|
Path to the input GeoTIFF file. |
required |
output_path
|
str
|
Path to save the output GeoJSON file. If None, no file is saved. |
None
|
epsilon
|
float
|
Simplification tolerance for the Douglas-Peucker algorithm. Higher values result in more simplification. Default is 0.2. |
0.2
|
min_area
|
float
|
Minimum area of polygons to process (smaller ones are kept as-is). |
10
|
min_segments
|
int
|
Minimum number of segments to keep after simplification. Default is 4 (for rectangular shapes). |
4
|
area_tolerance
|
float
|
Allowed ratio of area change. Values less than 1.0 restrict area change. Default is 0.7 (allows reduction to 70% of original area). |
0.7
|
detect_triangles
|
bool
|
If True, performs additional check to avoid creating triangular shapes. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
A GeoDataFrame containing the orthogonalized features. |
Source code in geoai/utils/geometry.py
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 1415 1416 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 1474 1475 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 1516 1517 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 1550 1551 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 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 | |
print_raster_info(raster_path, show_preview=True, figsize=(10, 8))
¶
Print formatted information about a raster dataset and optionally show a preview.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the raster file |
required |
show_preview
|
bool
|
Whether to display a visual preview of the raster. Defaults to True. |
True
|
figsize
|
tuple
|
Figure size as (width, height). Defaults to (10, 8). |
(10, 8)
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing raster information if successful, None otherwise |
Source code in geoai/utils/raster.py
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 | |
print_vector_info(vector_path, show_preview=True, figsize=(10, 8))
¶
Print formatted information about a vector dataset and optionally show a preview.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
show_preview
|
bool
|
Whether to display a visual preview of the vector data. Defaults to True. |
True
|
figsize
|
tuple
|
Figure size as (width, height). Defaults to (10, 8). |
(10, 8)
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Optional[Dict[str, Any]]
|
Dictionary containing vector information if successful, None otherwise |
Source code in geoai/utils/vector.py
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 | |
raster_to_vector(raster_path, output_path=None, threshold=0, min_area=10, simplify_tolerance=None, class_values=None, attribute_name='class', unique_attribute_value=False, output_format='geojson', plot_result=False)
¶
Convert a raster label mask to vector polygons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raster_path
|
str
|
Path to the input raster file (e.g., GeoTIFF). |
required |
output_path
|
str
|
Path to save the output vector file. If None, returns GeoDataFrame without saving. |
None
|
threshold
|
int / float
|
Pixel values greater than this threshold will be vectorized. |
0
|
min_area
|
float
|
Minimum polygon area in square map units to keep. |
10
|
simplify_tolerance
|
float
|
Tolerance for geometry simplification. None for no simplification. |
None
|
class_values
|
list
|
Specific pixel values to vectorize. If None, all values > threshold are vectorized. |
None
|
attribute_name
|
str
|
Name of the attribute field for the class values. |
'class'
|
unique_attribute_value
|
bool
|
Whether to generate unique values for each shape within a class. |
False
|
output_format
|
str
|
Format for output file - 'geojson', 'shapefile', 'gpkg'. Auto-detected from the file extension of output_path when possible. |
'geojson'
|
plot_result
|
bool
|
Whether to plot the resulting polygons overlaid on the raster. |
False
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
geopandas.GeoDataFrame: A GeoDataFrame containing the vectorized polygons. |
Source code in geoai/utils/raster.py
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 | |
raster_to_vector_batch(input_dir, output_dir, pattern='*.tif', threshold=0, min_area=10, simplify_tolerance=None, class_values=None, attribute_name='class', output_format='geojson', merge_output=False, merge_filename='merged_vectors')
¶
Batch convert multiple raster files to vector polygons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
str
|
Directory containing input raster files. |
required |
output_dir
|
str
|
Directory to save output vector files. |
required |
pattern
|
str
|
Pattern to match raster files (e.g., '*.tif'). |
'*.tif'
|
threshold
|
int / float
|
Pixel values greater than this threshold will be vectorized. |
0
|
min_area
|
float
|
Minimum polygon area in square map units to keep. |
10
|
simplify_tolerance
|
float
|
Tolerance for geometry simplification. None for no simplification. |
None
|
class_values
|
list
|
Specific pixel values to vectorize. If None, all values > threshold are vectorized. |
None
|
attribute_name
|
str
|
Name of the attribute field for the class values. |
'class'
|
output_format
|
str
|
Format for output files - 'geojson', 'shapefile', 'gpkg'. |
'geojson'
|
merge_output
|
bool
|
Whether to merge all output vectors into a single file. |
False
|
merge_filename
|
str
|
Filename for the merged output (without extension). |
'merged_vectors'
|
Returns:
| Type | Description |
|---|---|
Optional[GeoDataFrame]
|
geopandas.GeoDataFrame or None: If merge_output is True, returns the merged GeoDataFrame. |
Source code in geoai/utils/raster.py
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 | |
read_raster(source, band=None, masked=True, **kwargs)
¶
Reads raster data from various formats using rioxarray.
This function reads raster data from local files or URLs into a rioxarray data structure with preserved geospatial metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
String path to the raster file or URL. |
required |
band
|
Optional[Union[int, List[int]]]
|
Integer or list of integers specifying which band(s) to read. Defaults to None (all bands). |
None
|
masked
|
bool
|
Boolean indicating whether to mask nodata values. Defaults to True. |
True
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rioxarray.open_rasterio. |
{}
|
Returns:
| Type | Description |
|---|---|
DataArray
|
xarray.DataArray: A DataArray containing the raster data with geospatial metadata preserved. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file format is not supported or source cannot be accessed. |
Examples:
Read a local GeoTIFF
1 2 3 4 5 6 7 | |
Source code in geoai/utils/raster.py
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 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 | |
read_vector(source, layer=None, **kwargs)
¶
Reads vector data from various formats including GeoParquet.
This function dynamically determines the file type based on extension and reads it into a GeoDataFrame. It supports both local files and HTTP/HTTPS URLs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
String path to the vector file or URL. |
required |
layer
|
Optional[str]
|
String or integer specifying which layer to read from multi-layer files (only applicable for formats like GPKG, GeoJSON, etc.). Defaults to None. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the underlying reader. |
{}
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
geopandas.GeoDataFrame: A GeoDataFrame containing the vector data. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the file format is not supported or source cannot be accessed. |
Examples:
Read a local shapefile
1 2 3 4 5 6 7 | |
Source code in geoai/utils/raster.py
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 | |
region_groups(image, connectivity=1, min_size=10, max_size=None, threshold=None, properties=None, intensity_image=None, out_csv=None, out_vector=None, out_image=None, **kwargs)
¶
Segment regions in an image and filter them based on size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Union[str, DataArray, ndarray]
|
Input image, can be a file path, xarray DataArray, or numpy array. |
required |
connectivity
|
int
|
Connectivity for labeling. Defaults to 1 for 4-connectivity. Use 2 for 8-connectivity. |
1
|
min_size
|
int
|
Minimum size of regions to keep. Defaults to 10. |
10
|
max_size
|
Optional[int]
|
Maximum size of regions to keep. Defaults to None. |
None
|
threshold
|
Optional[int]
|
Threshold for filling holes. Defaults to None, which is equal to min_size. |
None
|
properties
|
Optional[List[str]]
|
List of properties to measure. See https://scikit-image.org/docs/stable/api/skimage.measure.html#skimage.measure.regionprops Defaults to None. |
None
|
intensity_image
|
Optional[Union[str, DataArray, ndarray]]
|
Intensity image to measure properties. Defaults to None. |
None
|
out_csv
|
Optional[str]
|
Path to save the properties as a CSV file. Defaults to None. |
None
|
out_vector
|
Optional[str]
|
Path to save the vector file. Defaults to None. |
None
|
out_image
|
Optional[str]
|
Path to save the output image. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
Union[Tuple[ndarray, DataFrame], Tuple[DataArray, DataFrame]]
|
Union[Tuple[np.ndarray, pd.DataFrame], Tuple[xr.DataArray, pd.DataFrame]]: Labeled image and properties DataFrame. |
Source code in geoai/utils/geometry.py
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | |
regularization(building_polygons, angle_tolerance=10, simplify_tolerance=0.5, orthogonalize=True, preserve_topology=True)
¶
Regularizes building footprint polygons with multiple techniques beyond minimum rotated rectangles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
building_polygons
|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons containing building footprints |
required |
angle_tolerance
|
float
|
Degrees within which angles will be regularized to 90/180 degrees |
10
|
simplify_tolerance
|
float
|
Distance tolerance for Douglas-Peucker simplification |
0.5
|
orthogonalize
|
bool
|
Whether to enforce orthogonal angles in the final polygons |
True
|
preserve_topology
|
bool
|
Whether to preserve topology during simplification |
True
|
Returns:
| Type | Description |
|---|---|
Union[GeoDataFrame, List[Polygon]]
|
GeoDataFrame or list of shapely Polygons with regularized building footprints |
Source code in geoai/utils/geometry.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 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 | |
regularize(data, parallel_threshold=1.0, target_crs=None, simplify=True, simplify_tolerance=0.5, allow_45_degree=True, diagonal_threshold_reduction=15, allow_circles=True, circle_threshold=0.9, num_cores=1, include_metadata=False, output_path=None, **kwargs)
¶
Regularizes polygon geometries in a GeoDataFrame by aligning edges.
Aligns edges to be parallel or perpendicular (optionally also 45 degrees) to their main direction. Handles reprojection, initial simplification, regularization, geometry cleanup, and parallel processing.
This function is a wrapper around the regularize_geodataframe function
from the buildingregulariser package. Credits to the original author
Nick Wright. Check out the repo at https://github.com/DPIRD-DMA/Building-Regulariser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[GeoDataFrame, str]
|
Input GeoDataFrame with polygon or multipolygon geometries, or a file path to the GeoDataFrame. |
required |
parallel_threshold
|
float
|
Distance threshold for merging nearly parallel adjacent edges during regularization. Defaults to 1.0. |
1.0
|
target_crs
|
Optional[Union[str, CRS]]
|
Target Coordinate Reference System for processing. If None, uses the input GeoDataFrame's CRS. Processing is more reliable in a projected CRS. Defaults to None. |
None
|
simplify
|
bool
|
If True, applies initial simplification to the geometry before regularization. Defaults to True. |
True
|
simplify_tolerance
|
float
|
Tolerance for the initial simplification step (if |
0.5
|
allow_45_degree
|
bool
|
If True, allows edges to be oriented at 45-degree angles relative to the main direction during regularization. Defaults to True. |
True
|
diagonal_threshold_reduction
|
float
|
Reduction factor in degrees to reduce the likelihood of diagonal edges being created. Larger values reduce the likelihood of diagonal edges. Defaults to 15. |
15
|
allow_circles
|
bool
|
If True, attempts to detect polygons that are nearly circular and replaces them with perfect circles. Defaults to True. |
True
|
circle_threshold
|
float
|
Intersection over Union (IoU) threshold used for circle detection
(if |
0.9
|
num_cores
|
int
|
Number of CPU cores to use for parallel processing. If 1, processing is done sequentially. Defaults to 1. |
1
|
include_metadata
|
bool
|
If True, includes metadata about the regularization process in the output GeoDataFrame. Defaults to False. |
False
|
output_path
|
Optional[str]
|
Path to save the output GeoDataFrame. If None, the output is not saved. Defaults to None. |
None
|
**kwargs
|
Any
|
Additional keyword arguments to pass to the |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
gpd.GeoDataFrame: A new GeoDataFrame with regularized polygon geometries. Original attributes are |
Any
|
preserved. Geometries that failed processing might be dropped. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input data is not a GeoDataFrame or a file path, or if the input GeoDataFrame is empty. |
Source code in geoai/utils/geometry.py
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 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 | |
rowcol_to_xy(src_fp, rows=None, cols=None, boxes=None, zs=None, offset='center', output=None, dst_crs='EPSG:4326', **kwargs)
¶
Converts a list of (row, col) coordinates to (x, y) coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src_fp
|
str
|
The source raster file path. |
required |
rows
|
list
|
A list of row coordinates. Defaults to None. |
None
|
cols
|
list
|
A list of col coordinates. Defaults to None. |
None
|
boxes
|
list
|
A list of (row, col) coordinates in the format of [[left, top, right, bottom], [left, top, right, bottom], ...] |
None
|
zs
|
Optional[List[float]]
|
zs (list or float, optional): Height associated with coordinates. Primarily used for RPC based coordinate transformations. |
None
|
offset
|
str
|
Determines if the returned coordinates are for the center of the pixel or for a corner. |
'center'
|
output
|
str
|
The output vector file path. Defaults to None. |
None
|
dst_crs
|
str
|
The destination CRS. Defaults to "EPSG:4326". |
'EPSG:4326'
|
**kwargs
|
Any
|
Additional keyword arguments to pass to rasterio.transform.xy. |
{}
|
Returns:
| Type | Description |
|---|---|
Tuple[List[float], List[float]]
|
A list of (x, y) coordinates. |
Source code in geoai/utils/conversion.py
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 | |
smooth_vector(vector_data, output_path=None, segment_length=None, smooth_iterations=3, num_cores=0, merge_collection=True, merge_field=None, merge_multipolygons=True, preserve_area=True, area_tolerance=0.01, **kwargs)
¶
Smooth a vector data using the smoothify library. See https://github.com/DPIRD-DMA/Smoothify for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_data
|
Union[str, GeoDataFrame]
|
The vector data to smooth. |
required |
output_path
|
str
|
The path to save the smoothed vector data. If None, returns the smoothed vector data. |
None
|
segment_length
|
float
|
Resolution of the original raster data in map units. If None (default), automatically detects by finding the minimum segment length (from a data sample). Recommended to specify explicitly when known. |
None
|
smooth_iterations
|
int
|
The number of iterations to smooth the vector data. |
3
|
num_cores
|
int
|
Number of cores to use for parallel processing. If 0 (default), uses all available cores. |
0
|
merge_collection
|
bool
|
Whether to merge/dissolve adjacent geometries in collections before smoothing. |
True
|
merge_field
|
str
|
Column name to use for dissolving geometries. Only valid when merge_collection=True. If None, dissolves all geometries together. If specified, dissolves geometries grouped by the column values. |
None
|
merge_multipolygons
|
bool
|
Whether to merge adjacent polygons within MultiPolygons before smoothing |
True
|
preserve_area
|
bool
|
Whether to restore original area after smoothing via buffering (applies to Polygons only) |
True
|
area_tolerance
|
float
|
Percentage of original area allowed as error (e.g., 0.01 = 0.01% error = 99.99% preservation). Only affects Polygons when preserve_area=True |
0.01
|
Returns:
| Type | Description |
|---|---|
GeoDataFrame
|
gpd.GeoDataFrame: The smoothed vector data. |
Examples:
1 2 3 4 5 | |
Source code in geoai/utils/vector.py
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 | |
stack_bands(input_files, output_file, resolution=None, dtype=None, temp_vrt='stack.vrt', overwrite=False, compress='DEFLATE', output_format='COG', extra_gdal_translate_args=None)
¶
Stack bands from multiple images into a single multi-band GeoTIFF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_files
|
List[str]
|
List of input image paths. |
required |
output_file
|
str
|
Path to the output stacked image. |
required |
resolution
|
float
|
Output resolution. If None, inferred from first image. |
None
|
dtype
|
str
|
Output data type (e.g., "UInt16", "Float32"). |
None
|
temp_vrt
|
str
|
Temporary VRT filename. |
'stack.vrt'
|
overwrite
|
bool
|
Whether to overwrite the output file. |
False
|
compress
|
str
|
Compression method. |
'DEFLATE'
|
output_format
|
str
|
GDAL output format (default is "COG"). |
'COG'
|
extra_gdal_translate_args
|
List[str]
|
Extra arguments for gdal_translate. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the output file. |
Source code in geoai/utils/raster.py
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 | |
temp_file_path(ext)
¶
Returns a temporary file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ext
|
str
|
The file extension. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The temporary file path. |
Source code in geoai/utils/device.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | |
train_segmentation_landcover(images_dir, labels_dir, output_dir, input_format='directory', architecture='unet', encoder_name='resnet34', encoder_weights='imagenet', num_channels=3, num_classes=2, batch_size=8, num_epochs=50, learning_rate=0.001, weight_decay=0.0001, seed=42, val_split=0.2, print_freq=10, verbose=True, save_best_only=True, plot_curves=False, device=None, checkpoint_path=None, resume_training=False, target_size=None, resize_mode='resize', num_workers=None, loss_function='crossentropy', ignore_index=0, use_class_weights=False, focal_alpha=1.0, focal_gamma=2.0, custom_multipliers=None, max_class_weight=50.0, use_inverse_frequency=True, validation_iou_mode='standard', boundary_alpha=1.0, background_class=0, training_callback=None, **kwargs)
¶
Train a semantic segmentation model with landcover-specific enhancements.
This is a standalone version that wraps geoai.train.train_segmentation_model with landcover-specific loss functions, class weights, and metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images_dir
|
str
|
Directory containing training images |
required |
labels_dir
|
str
|
Directory containing training labels |
required |
output_dir
|
str
|
Directory to save model checkpoints and training history |
required |
input_format
|
str
|
Data format ("directory", "COCO", "YOLO") |
'directory'
|
architecture
|
str
|
Model architecture (default: "unet") |
'unet'
|
encoder_name
|
str
|
Encoder backbone (default: "resnet34") |
'resnet34'
|
encoder_weights
|
Optional[str]
|
Pretrained weights ("imagenet" or None) |
'imagenet'
|
num_channels
|
int
|
Number of input channels (default: 3) |
3
|
num_classes
|
int
|
Number of output classes (default: 2) |
2
|
batch_size
|
int
|
Training batch size (default: 8) |
8
|
num_epochs
|
int
|
Number of training epochs (default: 50) |
50
|
learning_rate
|
float
|
Initial learning rate (default: 0.001) |
0.001
|
weight_decay
|
float
|
Weight decay for optimizer (default: 1e-4) |
0.0001
|
seed
|
int
|
Random seed for reproducibility (default: 42) |
42
|
val_split
|
float
|
Validation split ratio (default: 0.2) |
0.2
|
print_freq
|
int
|
Frequency of training progress prints (default: 10) |
10
|
verbose
|
bool
|
Enable verbose output (default: True) |
True
|
save_best_only
|
bool
|
Only save best model checkpoint (default: True) |
True
|
plot_curves
|
bool
|
Plot training curves at end (default: False) |
False
|
device
|
Optional[device]
|
Torch device (auto-detected if None) |
None
|
checkpoint_path
|
Optional[str]
|
Path to checkpoint for resuming training |
None
|
resume_training
|
bool
|
Whether to resume from checkpoint (default: False) |
False
|
target_size
|
Optional[Tuple[int, int]]
|
Target size for resizing images (H, W) or None |
None
|
resize_mode
|
str
|
How to resize ("resize", "crop", or "pad") |
'resize'
|
num_workers
|
Optional[int]
|
Number of dataloader workers (default: auto) |
None
|
loss_function
|
str
|
Loss function name ("crossentropy", "focal") |
'crossentropy'
|
ignore_index
|
Union[int, bool]
|
Class index to ignore during training. (default: 0) - If int: pixels with this label value will be ignored during training - If False: no pixels will be ignored (all pixels contribute to loss) |
0
|
use_class_weights
|
bool
|
Whether to compute and use class weights (default: False) |
False
|
focal_alpha
|
float
|
Focal loss alpha parameter (default: 1.0) |
1.0
|
focal_gamma
|
float
|
Focal loss gamma parameter (default: 2.0) |
2.0
|
custom_multipliers
|
Optional[Dict[int, float]]
|
Custom class weight multipliers {class_id: multiplier} |
None
|
max_class_weight
|
float
|
Maximum allowed class weight (default: 50.0) |
50.0
|
use_inverse_frequency
|
bool
|
Use inverse frequency for weights (default: True) |
True
|
validation_iou_mode
|
str
|
IoU calculation mode for validation (default: "standard") - "standard": Unweighted mean IoU (all classes equal importance) - "perclass_frequency": Frequency-weighted IoU (classes weighted by pixel count) - "boundary_weighted": Boundary-distance weighted IoU (wIoU, focus on edges) - "sparse_labels": For incomplete ground truth - predictions in background areas are NOT penalized. Uses custom training loop with sparse IoU for model selection. BEST FOR INCOMPLETE/SPARSE HABITAT MASKS. |
'standard'
|
boundary_alpha
|
float
|
Boundary importance factor for wIoU mode (default: 1.0) Higher values = more focus on boundaries (0.01-100 range) |
1.0
|
background_class
|
int
|
Class ID for background/unlabeled pixels in sparse_labels mode (default: 0). Predictions in this class area are NOT counted as false positives. |
0
|
training_callback
|
Optional[callable]
|
Optional callback function for automatic metric tracking |
None
|
**kwargs
|
Any
|
Additional arguments passed to base training function |
{}
|
Returns:
| Type | Description |
|---|---|
Module
|
Trained model |
Example
from landcover_train import train_segmentation_landcover
model = train_segmentation_landcover( ... images_dir="tiles/images", ... labels_dir="tiles/labels", ... output_dir="models/landcover_001", ... num_classes=5, ... loss_function="focal", ... ignore_index=0, # Ignore background ... use_class_weights=True, ... custom_multipliers={1: 1.5, 4: 0.8}, # Boost class 1, reduce class 4 ... max_class_weight=50.0, ... use_inverse_frequency=True, # Use inverse frequency weighting ... validation_iou_mode="boundary_weighted", # Focus on boundaries ... boundary_alpha=2.0, # Moderate boundary emphasis ... )
Source code in geoai/landcover_train.py
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 | |
vector_to_geojson(filename, output=None, **kwargs)
¶
Converts a vector file to a geojson file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
The vector file path. |
required |
output
|
str
|
The output geojson file path. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
str
|
The geojson dictionary. |
Source code in geoai/utils/vector.py
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 | |
vector_to_raster(vector_path, output_path=None, reference_raster=None, attribute_field=None, output_shape=None, transform=None, pixel_size=None, bounds=None, crs=None, all_touched=False, fill_value=0, dtype=np.uint8, nodata=None, plot_result=False)
¶
Convert vector data to a raster.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str or GeoDataFrame
|
Path to the input vector file or a GeoDataFrame. |
required |
output_path
|
str
|
Path to save the output raster file. If None, returns the array without saving. |
None
|
reference_raster
|
str
|
Path to a reference raster for dimensions, transform and CRS. |
None
|
attribute_field
|
str
|
Field name in the vector data to use for pixel values. If None, all vector features will be burned with value 1. |
None
|
output_shape
|
tuple
|
Shape of the output raster as (height, width). Required if reference_raster is not provided. |
None
|
transform
|
Affine
|
Affine transformation matrix. Required if reference_raster is not provided. |
None
|
pixel_size
|
float or tuple
|
Pixel size (resolution) as single value or (x_res, y_res). Used to calculate transform if transform is not provided. |
None
|
bounds
|
tuple
|
Bounds of the output raster as (left, bottom, right, top). Used to calculate transform if transform is not provided. |
None
|
crs
|
str or CRS
|
Coordinate reference system of the output raster. Required if reference_raster is not provided. |
None
|
all_touched
|
bool
|
If True, all pixels touched by geometries will be burned in. If False, only pixels whose center is within the geometry will be burned in. |
False
|
fill_value
|
int
|
Value to fill the raster with before burning in features. |
0
|
dtype
|
dtype
|
Data type of the output raster. |
uint8
|
nodata
|
int
|
No data value for the output raster. |
None
|
plot_result
|
bool
|
Whether to plot the resulting raster. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
numpy.ndarray: The rasterized data array if output_path is None, else None. |
Source code in geoai/utils/raster.py
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 | |
visualize_vector_by_attribute(vector_path, attribute_name, cmap='viridis', figsize=(10, 8))
¶
Create a thematic map visualization of vector data based on an attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_path
|
str
|
Path to the vector file |
required |
attribute_name
|
str
|
Name of the attribute to visualize |
required |
cmap
|
str
|
Matplotlib colormap name. Defaults to 'viridis'. |
'viridis'
|
figsize
|
tuple
|
Figure size as (width, height). Defaults to (10, 8). |
(10, 8)
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if visualization was successful, False otherwise |
Source code in geoai/utils/vector.py
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 | |
write_colormap(image, colormap, output=None)
¶
Write a colormap to an image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Union[str, ndarray]
|
The image to write the colormap to. |
required |
colormap
|
Union[str, Dict]
|
The colormap to write to the image. |
required |
output
|
Optional[str]
|
The output file path. |
None
|
Source code in geoai/utils/raster.py
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 | |