### Install S2Mosaic using uv Source: https://github.com/dpird-dma/s2mosaic/blob/main/README.md Install the S2Mosaic package using uv, a fast Python package installer. ```bash uv add s2mosaic ``` -------------------------------- ### Install S2Mosaic using pip or uv Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Install the S2Mosaic package using either pip or uv package managers. ```bash # Using pip pip install s2mosaic ``` ```bash # Using uv uv add s2mosaic ``` -------------------------------- ### Install S2Mosaic using pip Source: https://github.com/dpird-dma/s2mosaic/blob/main/README.md Install the S2Mosaic package using pip. This is the standard method for installing Python packages. ```bash pip install s2mosaic ``` -------------------------------- ### Monthly Mosaic Configuration Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Configure a monthly mosaic by specifying the start date and a duration of one month. ```python from s2mosaic import mosaic # Monthly mosaic array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=6, start_day=1, duration_months=1, # June 1 to July 1 ) ``` -------------------------------- ### S2Mosaic Usage Example with NumPy Array Output Source: https://github.com/dpird-dma/s2mosaic/blob/main/README.md Generate a Sentinel-2 mosaic for a specific grid area and time range, returning the result as a NumPy array and rasterio profile. This example uses specific spectral bands (B04, B03, B02, B08) for the mosaic. ```python from s2mosaic import mosaic # Create a mosaic for a specific grid area and time range array, rio_profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, sort_method="valid_data", mosaic_method="mean", required_bands=["B04", "B03", "B02", "B08"], no_data_threshold=0.001 ) print(f"Mosaic array shape: {array.shape}") ``` -------------------------------- ### Basic S2Mosaic Usage Example Source: https://github.com/dpird-dma/s2mosaic/blob/main/README.md Create a Sentinel-2 mosaic for a specific grid area and time range, saving the output as a GeoTIFF file. Scenes are sorted by valid data percentage, and the mosaic is created using the mean of valid pixels. The process stops when the no_data_threshold is met. ```python from s2mosaic import mosaic from pathlib import Path # Create a mosaic for a specific grid area and time range result = mosaic( grid_id="50HMH", # Sentinel-2 scene grid ID start_year=2022, start_month=1, start_day=1, duration_months=2, # Duration to collect data from output_dir=Path("output"), # Output directory for mosaic TIFF files sort_method="valid_data", # Method to sort potential scenes before download mosaic_method="mean", # Approach used to combine scenes required_bands=['visual'], # Required Sentinel-2 bands no_data_threshold=0.001 # Threshold for early stopping ) print(f"Mosaic saved to: {result}") ``` -------------------------------- ### Mosaic with sort_method='oldest' Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Processes scenes starting from the oldest available. This is useful for historical baseline comparisons and is often used with mosaic_method='first'. ```python array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=6, sort_method="oldest", mosaic_method="first", # Use first valid pixel (oldest) ) ``` -------------------------------- ### Mosaic with sort_method='newest' Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Processes scenes starting from the most recent. This method is useful for capturing the latest land cover conditions and is often used with mosaic_method='first'. ```python array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=6, sort_method="newest", mosaic_method="first", # Use first valid pixel (newest) ) ``` -------------------------------- ### Mosaic with custom sort function Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Allows for advanced sorting logic by providing a custom Python function. This example sorts scenes by 'good_data_pct' in descending order. ```python def custom_sort_function(items): """Sort by cloud shadow percentage (lowest first).""" return items.sort_values( by="good_data_pct", # Built-in column combining clouds + data coverage ascending=False ).reset_index(drop=True) array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, sort_function=custom_sort_function, # Overrides sort_method ) ``` -------------------------------- ### Mosaic with combined STAC query filters Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Applies multiple filters to the STAC query, such as cloud cover percentage, to refine the selection of Sentinel-2 scenes. This example selects scenes with less than 50% cloud cover for a specific date range. ```python # Combine multiple filters array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=6, start_day=1, duration_months=3, additional_query={ "eo:cloud_cover": {"lt": 50}, }, ) ``` -------------------------------- ### Get Multispectral Array for Analysis Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Retrieves a multispectral array (16-bit bands) for a specified grid and time range, using the newest scene sorting method and a median mosaic approach. Useful for further analysis in tools like NumPy. ```python # Example 2: Get multispectral array for analysis (16-bit bands) array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=6, start_day=1, duration_months=3, sort_method="newest", mosaic_method="median", # Median reduces outlier effects required_bands=["B04", "B03", "B02", "B08"], # Red, Green, Blue, NIR no_data_threshold=0.01, ) print(f"Array shape: {array.shape}") # (4, 10980, 10980) print(f"CRS: {profile['crs']}") # EPSG code for the tile ``` -------------------------------- ### Set Up Matplotlib and Output Directory Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Configures matplotlib for better plot aesthetics and creates an output directory for saved mosaics. Ensure the output directory exists before saving. ```python # Set up matplotlib for better plots plt.rcParams["figure.figsize"] = (15, 10) plt.rcParams["font.size"] = 12 # Create output directory for saved mosaics output_dir = Path("visual_test_outputs") output_dir.mkdir(exist_ok=True) ``` -------------------------------- ### Configure Logging (Commented Out) Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb This commented-out section shows how to configure basic logging for the application. ```python # logging.basicConfig( # level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s" # ) ``` -------------------------------- ### Mosaic with mosaic_method='first' Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Creates a mosaic using the first valid pixel encountered based on the scene's sort order. This is the fastest method as it only downloads necessary pixels. ```python # mosaic_method="first" # Uses first valid pixel encountered (based on sort order) # Fastest method - only downloads pixels that are needed array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, sort_method="newest", mosaic_method="first", # First valid = newest in this case ) ``` -------------------------------- ### Compare Mosaic Methods Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Compares different mosaicking methods ('mean', 'first') for creating a mosaic. This is useful for understanding how different aggregation strategies affect the output. Requires the 'mosaic' and 'compare_mosaics' functions. ```python print("Comparing different mosaic methods...") mosaic_methods = ["mean", "first"] mosaic_arrays = [] mosaic_titles = [] for mosaic_method in mosaic_methods: print(f"Creating mosaic with method: {mosaic_method}") array, profile = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_days=8, debug_cache=True, required_bands=["B04"], # Red band sort_method="valid_data", mosaic_method=mosaic_method, ) mosaic_arrays.append(array) mosaic_titles.append(f"Method: {mosaic_method}") # Compare the different mosaic methods compare_mosaics(mosaic_arrays, mosaic_titles, band_index=0) ``` -------------------------------- ### Create Visual Mosaic with Output Directory Source: https://github.com/dpird-dma/s2mosaic/blob/main/Example use.ipynb Generates a visual mosaic for a specified grid and time range, saving the output to a directory. It uses the 'first' mosaic method and filters for scenes with less than 50% cloud cover. ```python from s2mosaic import mosaic from pathlib import Path import rasterio as rio from matplotlib import pyplot as plt ``` ```python result = mosaic( grid_id="50HNG", start_year=2023, start_month=1, start_day=1, duration_months=1, output_dir=Path("output"), sort_method="valid_data", mosaic_method="first", required_bands=["visual"], no_data_threshold=0.001, additional_query={"eo:cloud_cover": {"lt": 50}}, ) print(f"Visual mosaic saved to: {result}") ``` -------------------------------- ### Seasonal Mosaic Configuration Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Create a seasonal mosaic by setting duration_months to 3 for a three-month period. ```python # Seasonal mosaic (3 months) array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=6, start_day=1, duration_months=3, # Summer: June-August ) ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Imports the required libraries for mosaic generation and visualization, including numpy, matplotlib, pathlib, and rasterio. ```python import numpy as np import matplotlib.pyplot as plt from pathlib import Path import rasterio as rio from s2mosaic import mosaic ``` -------------------------------- ### Compare Mosaics Over Different Time Periods Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Analyzes how data coverage changes by creating mosaics for different time durations (3 days, 1 week, 2 weeks) and comparing the resulting data coverage percentages. It visualizes these comparisons. ```python print("Testing different time periods...") time_configs = [ {"duration_days": 3, "label": "3 days"}, {"duration_days": 7, "label": "1 week"}, {"duration_days": 14, "label": "2 weeks"}, ] time_arrays = [] time_titles = [] for config in time_configs: print(f"Creating mosaic for {config['label']}...") array, profile = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_days=config["duration_days"], debug_cache=True, required_bands=["B04"], # Red band sort_method="valid_data", mosaic_method="mean", ) time_arrays.append(array) time_titles.append(config["label"]) # Calculate data coverage valid_pixels = np.sum(array[0] > 0) total_pixels = array[0].size coverage = (valid_pixels / total_pixels) * 100 print(f" Data coverage: {coverage:.1f}%") # Compare different time periods compare_mosaics(time_arrays, time_titles, band_index=0) ``` -------------------------------- ### Mosaic with mosaic_method='median' Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Generates a mosaic using the median value of all valid pixels. This method is robust against outliers and provides a good representation of typical conditions. ```python # mosaic_method="median" # Median value across all valid pixels - robust to outliers # Shorthand for percentile with value=50 array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, mosaic_method="median", ) ``` -------------------------------- ### Create RGB Visual Mosaic and Save to File Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Generates an RGB visual mosaic for a specified grid and time range, saving the output as a GeoTIFF file. Prioritizes scenes with the most valid data and uses a mean mosaic method. Stops processing when less than 0.1% of pixels are no-data. ```python from s2mosaic import mosaic from pathlib import Path # Example 1: Create RGB visual mosaic and save to file output_path = mosaic( grid_id="50HMH", # Sentinel-2 MGRS grid tile ID start_year=2022, start_month=1, start_day=1, duration_months=2, # Collect scenes over 2 months output_dir=Path("output"), # Save as GeoTIFF sort_method="valid_data", # Prioritize scenes with most valid data mosaic_method="mean", # Average valid pixels across scenes required_bands=["visual"], # RGB true color composite (8-bit) no_data_threshold=0.001, # Stop when <0.1% pixels are no-data ocm_batch_size=4, # GPU batch size for cloud masking ocm_inference_dtype="bf16", # Use bfloat16 for fast GPU inference ) print(f"Mosaic saved to: {output_path}") # Output: Mosaic saved to: output/50HMH_2022-01-01_to_2022-03-01_valid_data_mean_visual.tif ``` -------------------------------- ### Annual Mosaic Configuration Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Generate an annual mosaic by setting duration_years to 1 for a full year. ```python # Annual mosaic array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_years=1, # Full year ) ``` -------------------------------- ### Create High-Quality Visual Mosaic with Percentile Source: https://github.com/dpird-dma/s2mosaic/blob/main/Example use.ipynb Generates a high-quality visual mosaic using a longer duration, percentile mosaic method (25th percentile), and strict cloud cover filtering (less than 10%). No data threshold is applied. ```python array, rio_profile = mosaic( grid_id="50HNG", start_year=2023, start_month=1, start_day=1, duration_months=3, # Use a longer duration to get more data sort_method="valid_data", mosaic_method="percentile", # Use percentile method to mosaic percentile_value=25, # Use 25th percentile to remove light clouds required_bands=["visual"], no_data_threshold=None, # No threshold so process all images additional_query={"eo:cloud_cover": {"lt": 10}}, # Filter for low cloud cover ) ``` -------------------------------- ### Mosaic with mosaic_method='percentile' Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Creates a mosaic using a specified percentile value of valid pixels. This is useful for specialized analysis, with lower percentiles emphasizing darker features and higher percentiles emphasizing brighter features. ```python # mosaic_method="percentile" # Specific percentile value for specialized analysis # Lower values (e.g., 10-25) emphasize darker/shadowed features # Higher values (e.g., 75-90) emphasize brighter features array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=3, mosaic_method="percentile", percentile_value=25.0, # 25th percentile no_data_threshold=None, # Must process all scenes for percentile ) ``` -------------------------------- ### Create Raw Bands Mosaic as Array Source: https://github.com/dpird-dma/s2mosaic/blob/main/Example use.ipynb Generates a mosaic using specified raw bands without an output directory, returning the mosaic as a numpy array and its rasterio profile. It uses the 'mean' mosaic method. ```python required_bands = ["B04", "B03", "B02", "B06", "B08", "B11"] array, rio_profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, sort_method="valid_data", mosaic_method="mean", required_bands=required_bands, no_data_threshold=0.001, ) print(f"Mosaic array shape: {array.shape}, profile: {rio_profile}") ``` -------------------------------- ### Compare Sort Methods for Mosaic Creation Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Compares different sorting methods ('valid_data', 'oldest', 'newest') when creating a mosaic. This helps in understanding how scene selection impacts the final mosaic. Requires the 'mosaic' and 'compare_mosaics' functions. ```python print("Comparing different sort methods...") sort_methods = ["valid_data", "oldest", "newest"] sort_arrays = [] sort_titles = [] for sort_method in sort_methods: print(f"Creating mosaic with sort method: {sort_method}") array, profile = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_months=1, debug_cache=True, required_bands=["B04"], # Just Red band for comparison sort_method=sort_method, mosaic_method="mean", no_data_threshold=None, ) sort_arrays.append(array) sort_titles.append(f"Sort: {sort_method}") # Compare the different sort methods compare_mosaics(sort_arrays, sort_titles, band_index=0) ``` -------------------------------- ### Create Multi-band Mosaic for Analysis Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Creates a multi-band mosaic using the 'mean' mosaicking method with specified bands (Red, Green, Blue, NIR). It then plots each band separately using matplotlib for visual analysis. Requires the 'mosaic' function and matplotlib. ```python print("Creating multi-band mosaic for analysis...") # Create a mosaic with multiple bands for analysis multi_array, multi_profile = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_months=1, debug_cache=True, required_bands=["B04", "B03", "B02", "B08"], # Red, Green, Blue, NIR sort_method="valid_data", mosaic_method="mean", ) print(f"Multi-band Array shape: {multi_array.shape}") band_names = ["Red (B04)", "Green (B03)", "Blue (B02)", "NIR (B08)"] # Plot each band separately fig, axes = plt.subplots(2, 2, figsize=(15, 12)) axes = axes.flatten() for i, band_name in enumerate(band_names): band_data = multi_array[i] masked_data = np.ma.masked_where(band_data == 0, band_data) im = axes[i].imshow(masked_data, cmap="viridis") axes[i].set_title(band_name) axes[i].axis("off") plt.colorbar(im, ax=axes[i], shrink=0.6) plt.tight_layout() plt.show() ``` -------------------------------- ### Mosaic with CPU OmniCloudMask settings Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Configures OmniCloudMask for CPU inference using float32 data type. A batch size of 1 is recommended for CPU performance. ```python # CPU fallback settings array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, ocm_batch_size=1, # Lower batch size for CPU ocm_inference_dtype="fp32", # float32 for CPU inference ) ``` -------------------------------- ### Display Visual Mosaic Source: https://github.com/dpird-dma/s2mosaic/blob/main/Example use.ipynb Opens the generated visual mosaic file using rasterio and displays it using matplotlib. ```python visual_array = rio.open(result).read() plt.imshow(visual_array.transpose(1, 2, 0)) ``` -------------------------------- ### Create Basic RGB Mosaic Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Generates a standard RGB mosaic using the 'mean' mosaic method and 'valid_data' sorting. It specifies required bands B04, B03, B02 (Red, Green, Blue) and prints the resulting array's shape, dtype, and value range. ```python print("Creating basic RGB mosaic...") # Create a standard RGB mosaic rgb_array, rgb_profile = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_days=14, debug_cache=True, required_bands=["B04", "B03", "B02"], # Red, Green, Blue sort_method="valid_data", mosaic_method="mean", ) print(f"RGB Array shape: {rgb_array.shape}") print(f"RGB Array dtype: {rgb_array.dtype}") print(f"RGB Array range: {rgb_array.min()} to {rgb_array.max()}") # Plot the RGB mosaic plot_mosaic_rgb(rgb_array, "Basic RGB Mosaic (Mean, Valid Data Sort)") ``` -------------------------------- ### Percentile Mosaic with Cloud Cover Filter Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Creates a percentile mosaic using specific spectral bands (NIR + SWIR) for a given grid and time range. It filters scenes to include only those with less than 50% cloud cover and uses the 25th percentile to emphasize darker pixel values. ```python # Example 3: Percentile mosaic with cloud cover filter array, profile = mosaic( grid_id="32TQM", start_year=2023, start_month=4, start_day=1, duration_months=1, mosaic_method="percentile", percentile_value=25.0, # 25th percentile (darker values) required_bands=["B08", "B11", "B12"], # NIR + SWIR bands additional_query={"eo:cloud_cover": {"lt": 50}}, # Only <50% cloudy scenes no_data_threshold=None, # Process all available scenes ) ``` -------------------------------- ### Save RGB and Visual Mosaics Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Generates and saves both RGB and visual band mosaics for a specified area and time period. It then verifies the saved files and prints their properties like shape, band count, CRS, data type, and file size. ```python print("Saving mosaics to files...") # Save RGB mosaic rgb_path = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_days=7, output_dir=output_dir, debug_cache=True, required_bands=["B04", "B03", "B02"], sort_method="valid_data", mosaic_method="mean", ) print(f"RGB mosaic saved to: {rgb_path}") # Save visual mosaic visual_path = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_days=7, output_dir=output_dir, debug_cache=True, required_bands=["visual"], sort_method="valid_data", mosaic_method="mean", ) print(f"Visual mosaic saved to: {visual_path}") # Verify files exist and show their properties for path in [rgb_path, visual_path]: if path.exists(): with rio.open(path) as src: print(f"\nFile: {path.name}") print(f" Shape: {src.shape}") print(f" Bands: {src.count}") print(f" CRS: {src.crs}") print(f" Data type: {src.dtypes[0]}") print(f" File size: {path.stat().st_size / (1024 * 1024):.1f} MB") ``` -------------------------------- ### Create Visual Band Mosaic with Incomplete Coverage Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Generates a visual band mosaic for an area known to have incomplete data coverage. It then prints the shape, data type, and value range of the resulting array to understand the output characteristics. ```python print("Creating visual band mosaic over an area with incomplete coverage...") # Create a visual band mosaic (this should be RGB in uint8) visual_array, visual_profile = mosaic( "56KQB", 2023, start_month=6, start_day=4, duration_months=1, debug_cache=True, required_bands=["visual"], sort_method="valid_data", mosaic_method="mean", ) print(f"Visual Array shape: {visual_array.shape}") print(f"Visual Array dtype: {visual_array.dtype}") print(f"Visual Array range: {visual_array.min()} to {visual_array.max()}") ``` -------------------------------- ### Standard GeoTIFF Export Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Export a mosaic to a GeoTIFF file with automatic filename generation. Set overwrite to True to replace existing files. ```python from s2mosaic import mosaic from pathlib import Path # Standard export with automatic filename output_path = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, output_dir=Path("output"), overwrite=True, # Replace existing file ) # Filename format: {grid}_{start}_to_{end}_{sort}_{mosaic}_{bands}.tif # Example: 50HMH_2022-01-01_to_2022-03-01_valid_data_mean_B04_B03_B02_B08.tif ``` -------------------------------- ### Custom Duration Mosaic Configuration Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Define a custom mosaic duration by combining duration_years, duration_months, and duration_days. ```python # Custom duration combining years, months, and days array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=3, start_day=15, duration_years=0, duration_months=2, duration_days=15, # March 15 to June 1 ) ``` -------------------------------- ### Multi-Year Compositing Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Perform multi-year compositing by specifying a duration in years and a no_data_threshold. ```python # Multi-year compositing array, profile = mosaic( grid_id="50HMH", start_year=2020, start_month=1, start_day=1, duration_years=2, # 2020-2021 no_data_threshold=0.0001, ) ``` -------------------------------- ### Control Duplicate Scene Handling Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Set ignore_duplicate_items to True to keep only the latest processing baseline when generating mosaics. ```python array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, ignore_duplicate_items=True, # Default: keep only latest processing baseline ) ``` -------------------------------- ### Mosaic with mosaic_method='mean' Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Generates a mosaic by averaging all valid pixels from overlapping scenes. This method provides smoothed results and is suitable for general-purpose use. ```python from s2mosaic import mosaic # mosaic_method="mean" (default) # Average of all valid pixels - smooths noise, good general purpose array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, mosaic_method="mean", ) ``` -------------------------------- ### Standard RGBN Composite for Vegetation Analysis Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Generates a standard RGBN (Red, Green, Blue, Near-Infrared) composite mosaic for vegetation analysis. This uses the 'visual' band for RGB and 'B08' for NIR, suitable for assessing vegetation health. ```python # Standard RGBN composite for vegetation analysis array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, required_bands=["B04", "B03", "B02", "B08"], # Red, Green, Blue, NIR ) ``` -------------------------------- ### Mosaic with GPU-optimized OmniCloudMask settings Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Configures the OmniCloudMask for GPU inference using bfloat16 data type for maximum speed on modern GPUs. Adjust ocm_batch_size based on your GPU memory. ```python from s2mosaic import mosaic # GPU-optimized settings (NVIDIA CUDA or Apple MPS) array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, ocm_batch_size=6, # Higher batch size for GPU (try 4-8) ocm_inference_dtype="bf16", # bfloat16 - fastest on modern GPUs ) ``` -------------------------------- ### Mosaic with sort_method='valid_data' Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Uses the default 'valid_data' sort method, prioritizing scenes with the highest percentage of valid data. This is the recommended and fastest method when combined with no_data_threshold. ```python array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=3, sort_method="valid_data", no_data_threshold=0.001, # Stop early when mosaic is nearly complete ) ``` -------------------------------- ### Mosaic with alternative GPU OmniCloudMask settings Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Uses float16 data type for OmniCloudMask inference, offering wider GPU compatibility than bfloat16. The batch size is set to 4. ```python # Alternative dtype options if bf16 not supported array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, ocm_batch_size=4, ocm_inference_dtype="fp16", # float16 - wider GPU support ) ``` -------------------------------- ### Create Visual Band Mosaic Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Generates a mosaic using the 'visual' band, which is typically RGB and expected to be in uint8 format. It uses the same date range and sorting method as the basic RGB mosaic. The output array's shape, dtype, and value range are printed. ```python print("Creating visual band mosaic...") # Create a visual band mosaic (this should be RGB in uint8) visual_array, visual_profile = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_days=14, debug_cache=True, required_bands=["visual"], sort_method="valid_data", mosaic_method="mean", ) print(f"Visual Array shape: {visual_array.shape}") print(f"Visual Array dtype: {visual_array.dtype}") print(f"Visual Array range: {visual_array.min()} to {visual_array.max()}") ``` -------------------------------- ### Plot Visual Mosaic Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Plots a visual mosaic from a given array. Ensure the visual_array is pre-processed before plotting. Percentile stretch is disabled by default. ```python plot_mosaic_rgb(visual_array, "Visual Band Mosaic", percentile_stretch=False) ``` -------------------------------- ### GeoTIFF Export with Overwrite Disabled Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Export a mosaic to GeoTIFF, setting overwrite to False to return the existing path if the file already exists without reprocessing. ```python # Skip if output already exists output_path = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, output_dir=Path("output"), overwrite=False, # Return existing path without reprocessing ) ``` -------------------------------- ### Calculate and Plot NDVI Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Calculates the Normalized Difference Vegetation Index (NDVI) from red and near-infrared bands and visualizes it. Ensures division by zero is handled and masks out areas with zero red or NIR values. ```python red = multi_array[0].astype(float) nir = multi_array[3].astype(float) # Calculate NDVI ndvi = np.divide(nir - red, nir + red, out=np.zeros_like(nir), where=(nir + red) != 0) plt.figure(figsize=(10, 8)) ndvi_masked = np.ma.masked_where((red == 0) | (nir == 0), ndvi) im = plt.imshow(ndvi_masked, cmap="RdYlGn", vmin=-1, vmax=1) plt.colorbar(im, shrink=0.6) plt.title("NDVI (Normalized Difference Vegetation Index)") plt.axis("off") plt.tight_layout() plt.show() print(f"NDVI range: {ndvi_masked.min():.3f} to {ndvi_masked.max():.3f}") ``` -------------------------------- ### Display Percentile Mosaic Source: https://github.com/dpird-dma/s2mosaic/blob/main/Example use.ipynb Displays the resulting percentile mosaic array using matplotlib. ```python plt.imshow(array.transpose(1, 2, 0)) ``` -------------------------------- ### Multispectral GeoTIFF Export Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Export a multispectral mosaic (16-bit) with nodata=0 by specifying the desired spectral bands in required_bands. ```python # Multispectral export (16-bit, nodata=0) output_path = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, output_dir=Path("output"), required_bands=["B04", "B03", "B02", "B08"], # 16-bit, nodata=0 ) # Output GeoTIFF includes: # - LZW compression # - Band descriptions matching required_bands # - CRS and transform from source scenes # - Nodata value (0 for 16-bit, None for visual) ``` -------------------------------- ### Compare Mosaics Function Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb A function to display multiple mosaics side by side for comparison. It plots a specified band from each mosaic with a common colorbar and title. ```python def compare_mosaics(arrays, titles, band_index=0, vmin=0, vmax=6000): """Compare multiple mosaics side by side""" n_mosaics = len(arrays) fig, axes = plt.subplots(1, n_mosaics, figsize=(5 * n_mosaics, 5)) if n_mosaics == 1: axes = [axes] for i, (array, title) in enumerate(zip(arrays, titles)): if array.shape[0] > band_index: band_data = array[band_index] masked_data = np.ma.masked_where(band_data == 0, band_data) im = axes[i].imshow(masked_data, cmap="viridis", vmin=vmin, vmax=vmax) axes[i].set_title(title) axes[i].axis("off") plt.colorbar(im, ax=axes[i], shrink=0.6) plt.tight_layout() plt.show() ``` -------------------------------- ### Test Percentile Mosaics Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Tests percentile mosaicking with different percentile values (25, 50, 75). This method is useful for creating mosaics that represent specific statistical values within a time series. Requires the 'mosaic' and 'compare_mosaics' functions. ```python print("Testing percentile mosaics...") percentiles = [25, 50, 75] percentile_arrays = [] percentile_titles = [] for percentile in percentiles: print(f"Creating {percentile}th percentile mosaic...") array, profile = mosaic( "50HMH", 2023, start_month=6, start_day=1, duration_months=2, # Longer period for percentile comparison debug_cache=True, required_bands=["B8A"], # NIR at 20m faster sort_method="valid_data", mosaic_method="percentile", percentile_value=percentile, no_data_threshold=None, # do all the scenes ) percentile_arrays.append(array) percentile_titles.append(f"{percentile}th percentile") # Compare percentile mosaics compare_mosaics(percentile_arrays, percentile_titles, band_index=0, vmin=0, vmax=4000) ``` -------------------------------- ### Visual RGB GeoTIFF Export Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Export a visual RGB mosaic (8-bit) with no nodata value by setting required_bands to ['visual']. ```python # Visual RGB export (8-bit, no nodata value) output_path = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, output_dir=Path("output"), required_bands=["visual"], # 8-bit RGB, nodata=None ) ``` -------------------------------- ### Visual Array Properties Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb Inspect the shape, data type, and range of the visual array after plotting the mosaic. This helps understand the data's characteristics. ```python Visual Array shape: (3, 10980, 10980) Visual Array dtype: uint8 Visual Array range: 0 to 255 ``` -------------------------------- ### Mosaic with STAC query filtering by cloud cover Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Filters Sentinel-2 scenes to include only those with less than 30% cloud cover using the 'additional_query' parameter. This is a common way to ensure data quality. ```python from s2mosaic import mosaic # Filter by cloud cover percentage array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, additional_query={ "eo:cloud_cover": {"lt": 30}, # Only scenes with <30% cloud cover }, ) # Default query (if additional_query not specified) # {"eo:cloud_cover": {"lt": 100}} - accepts all scenes ``` -------------------------------- ### False Color Infrared Composite Source: https://context7.com/dpird-dma/s2mosaic/llms.txt Creates a false color infrared composite mosaic using Near-Infrared (NIR), Red, and Green bands. This combination is useful for highlighting vegetation and differentiating land cover types. ```python # False color infrared composite array, profile = mosaic( grid_id="50HMH", start_year=2022, start_month=1, start_day=1, duration_months=2, required_bands=["B08", "B04", "B03"], # NIR, Red, Green ) ``` -------------------------------- ### Display Raw Bands Mosaic Source: https://github.com/dpird-dma/s2mosaic/blob/main/Example use.ipynb Displays each band of the raw bands mosaic array in separate subplots using matplotlib. ```python fig, axs = plt.subplots(3, 2, figsize=(10, 10)) for i, ax in enumerate(axs.flat): ax.imshow(array[i, :, :]) ax.set_title(f"Band {required_bands[i]}") ax.set_xticks([]) ax.set_yticks([]) ``` -------------------------------- ### Plot RGB Mosaic Function Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb A function to plot an RGB mosaic. It handles moving bands to the correct axis for matplotlib and optionally applies a 2-98 percentile stretch for better visualization. It prints a message if the array does not have 3 bands. ```python def plot_mosaic_rgb(array, title="Mosaic", percentile_stretch=True): """Plot RGB mosaic with optional percentile stretch""" if array.shape[0] == 3: # RGB # Move bands to last dimension for matplotlib rgb = np.moveaxis(array, 0, -1) if percentile_stretch: # Apply 2-98 percentile stretch for better visualization for i in range(3): band = rgb[:, :, i] p2, p98 = np.percentile(band[band > 0], [2, 98]) rgb[:, :, i] = np.clip((band - p2) / (p98 - p2) * 255, 0, 255) plt.figure(figsize=(12, 8)) plt.imshow(rgb.astype(np.uint8)) plt.title(title) plt.axis("off") plt.tight_layout() plt.show() else: print(f"Cannot plot RGB - array has {array.shape[0]} bands, need 3") ``` -------------------------------- ### Plot Single Band Function Source: https://github.com/dpird-dma/s2mosaic/blob/main/Visual test.ipynb A function to plot a single band of a mosaic. It allows specifying the band index, colormap, and value range (vmin, vmax). Zero values are masked for better visualization. ```python def plot_single_band( array, band_index=0, title="Single Band", cmap="viridis", vmin=0, vmax=6000 ): """Plot a single band with colormap""" plt.figure(figsize=(10, 8)) band_data = array[band_index] # Mask out zero values for better visualization masked_data = np.ma.masked_where(band_data == 0, band_data) im = plt.imshow(masked_data, cmap=cmap, vmin=vmin, vmax=vmax) plt.colorbar(im, shrink=0.6) plt.title(f"{title} - Band {band_index}") plt.axis("off") plt.tight_layout() plt.show() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.