import requests import io from PIL import Image import geopandas as gpd import numpy as np import rasterio from rasterio.features import shapes from shapely.geometry import shape import tensorflow as tf # Replace with your Google Maps API key GOOGLE_MAPS_API_KEY = "AIzaSyDnM_35WfYwhJmTSPxyyiMIcYte65mPitc" # Replace with the coordinates of your location north = 26.605766 #east = ... #south = ... west = 92.056496 # Step 1: Retrieve a map image using Google Maps Static API url = f"https://maps.googleapis.com/maps/api/staticmap?center={north},{west}&zoom=15&size=640x480&maptype=satellite&key={GOOGLE_MAPS_API_KEY}" response = requests.get(url) image = Image.open(io.BytesIO(response.content)) # Step 2: Convert the image into a GeoTIFF # You might need to install the `rasterio` library for this step with rasterio.open("map_image.tif", "w", driver="GTiff", width=image.width, height=image.height, count=3, dtype="uint8", crs="EPSG:4326") as dst: image_data = np.array(image) #dst.write(image_data, indexes=[1, 2, 3]) dst.write(image_data, indexes = 1) # Step 3: Use the Segment Anything model on the GeoTIFF file # Load the pre-trained model (replace with the actual model path) model = tf.keras.models.load_model("segment_model.h5") # Open the GeoTIFF file for reading and writing with rasterio.open("map_image.tif") as src: profile = src.profile image_data = src.read() # Normalize the image data if needed normalized_image_data = image_data / 255.0 # Predict segments using the model predicted_segments = model.predict(np.expand_dims(normalized_image_data, axis=0)) # Step 4: Generate a GeoJSON of all the segments identified segment_shapes = [] for i, class_probs in enumerate(predicted_segments[0]): if class_probs.max() > 0.5: # Adjust the threshold as needed segment_mask = (predicted_segments[0].argmax(axis=-1) == i).astype(np.uint8) for segment, val in shapes(segment_mask, transform=profile["transform"]): segment_shapes.append(shape(segment)) # Create a GeoDataFrame from the segment shapes gdf = gpd.GeoDataFrame({"geometry": segment_shapes}) # Save the GeoDataFrame as a GeoJSON file gdf.to_file("segments.geojson", driver="GeoJSON")