save multiple sat images to mask

PHOTO EMBED

Sun Jul 21 2024 08:34:17 GMT+0000 (Coordinated Universal Time)

Saved by @samaymalik7

Modified Script
python
Copy code
import os
import rasterio
import geopandas as gpd
from rasterio.mask import mask
import matplotlib.pyplot as plt

def convert_images_to_masks(input_image_dir, building_footprints_path, output_mask_dir):
    """
    Convert multiple satellite images to masks based on building footprints.
    """
    # Load the building footprints as a GeoDataFrame
    building_footprints = gpd.read_file(building_footprints_path)

    # Ensure both the raster and vector data are in the same CRS
    # Temporarily load the first image to get CRS
    first_image_path = os.path.join(input_image_dir, os.listdir(input_image_dir)[0])
    with rasterio.open(first_image_path) as src:
        satellite_meta = src.meta
    building_footprints = building_footprints.to_crs(crs=satellite_meta['crs'])

    # Iterate through each image in the input directory
    for file_name in os.listdir(input_image_dir):
        if file_name.endswith('.tif'):
            input_image_path = os.path.join(input_image_dir, file_name)
            output_mask_path = os.path.join(output_mask_dir, file_name.replace('.tif', '_mask.tif'))

            # Open the raster image
            with rasterio.open(input_image_path) as src:
                satellite_image = src.read()  # Read all bands
                satellite_meta = src.meta  # Metadata of the raster

            # Create a geometry mask from the building footprints
            geometries = building_footprints['geometry'].values

            # Clip the raster with the building footprints mask
            with rasterio.open(input_image_path) as src:
                out_image, out_transform = mask(src, geometries, crop=True)
                out_meta = src.meta.copy()
                out_meta.update({
                    "driver": "GTiff",
                    "height": out_image.shape[1],
                    "width": out_image.shape[2],
                    "transform": out_transform
                })

            # Save the clipped image
            with rasterio.open(output_mask_path, "w", **out_meta) as dest:
                dest.write(out_image)

            print(f"Processed and saved mask for {file_name}")

            # Display the result (optional)
            plt.figure(figsize=(10, 10))
            if out_image.shape[0] == 1:
                plt.imshow(out_image[0], cmap='gray')
            else:
                plt.imshow(out_image.transpose(1, 2, 0))
            plt.title(f'Clipped Satellite Image - {file_name}')
            plt.axis('off')  # Turn off axis labels
            plt.show()

# Example usage
input_directory = 'E:/isrooooooo/marchassam/satimgmarch/'  # Path to directory with TIFF images
building_footprints_path = 'C:/project isro/assambuildingfoot.shp'  # Path to building footprints
output_directory = 'E:/isrooooooo/marchassam/maskmarch/'  # Path to save masks

convert_images_to_masks(input_directory, building_footprints_path, output_directory)
Explanation
convert_images_to_masks Function:

Takes in the directory containing satellite images, the path to building footprints, and the output directory for masks.
Loads building footprints and ensures CRS alignment with the first image.
Processing Each Image:

Loops through all TIFF files in the input directory.
For each image, it applies the clipping process and saves the resulting mask.
Visualization:

Optionally displays the clipped image for each processed file.
File Handling:

Ensures each processed mask is saved with a unique name, corresponding to the original image file.
By following this script, you can efficiently process multiple satellite images and generate corresponding masks in one go. Adjust the directory paths and filenames as needed for your specific use case. If you encounter any issues or need further assistance, let me know!
content_copyCOPY