import numpy as np import cv2 import json from sentinelhub import SHConfig, MimeType, BBox, SentinelHubRequest, SentinelHubDownloadClient, DataCollection, geo_utils def detect_deforestation(bbox, time_interval, output_dir, config=None): if config is None: # Configure SentinelHub with your credentials config = SHConfig() config.sh_client_id = '3e9277b3-aa11-4f98-a160-3bf006130cc7' config.sh_client_secret = 'CY>imU7J,97EniGj5jyRtz:l13@XL2*gfY+pvqRw' # Define the SentinelHub request parameters evalscript = """ // Import Sentinel-2 bands return [B02, B03, B04, B08]; """ request = SentinelHubRequest( evalscript=evalscript, input_data=[ SentinelHubRequest.input_data( data_collection=DataCollection.SENTINEL2_L1C, time_interval=time_interval, maxcc=0.2 ) ], responses=[ SentinelHubRequest.output_response('default', MimeType.TIFF), ], bbox=bbox, config=config, ) # Fetch Sentinel imagery sentinel_data = request.get_data() sentinel_data = np.array(sentinel_data[0]) # Calculate the NDVI (Normalized Difference Vegetation Index) nir = sentinel_data[:, :, 3] red = sentinel_data[:, :, 2] ndvi = (nir - red) / (nir + red) # Apply a threshold to identify deforested areas threshold = 0.2 deforestation_mask = (ndvi < threshold) # Create a color-coded PNG image deforestation_image = np.zeros_like(sentinel_data) deforestation_image[deforestation_mask] = [0, 0, 255, 255] # Red color for deforestation # Save the PNG image png_path = f"{output_dir}/deforestation.png" cv2.imwrite(png_path, deforestation_image) # Create a GeoJSON object to represent deforested areas # geojson_features = [] # rows, cols = deforestation_mask.shape # for row in range(rows): # for col in range(cols): # if deforestation_mask[row, col]: # # Convert pixel coordinates to geographical coordinates # #lon, lat = request.get_bbox().pixel_to_utm((row, col)) # #lon, lat = geo_utils.epsg_to_wgs84((bbox.min_x + col * request.resolution_x, bbox.min_y + row * request.resolution_y)) # lon, lat = bbox.pixel_to_utm((col, row)) # geojson_features.append({ # "type": "Feature", # "geometry": { # "type": "Point", # "coordinates": [lon, lat] # } # }) # geojson = { # "type": "FeatureCollection", # "features": geojson_features # } # # Save the GeoJSON object # geojson_path = f"{output_dir}/deforestation.geojson" # with open(geojson_path, "w") as geojson_file: # json.dump(geojson, geojson_file) return png_path#, geojson_path # Example usage: longitude_min, latitude_min, longitude_max, latitude_max = 103.88372272,-2.34602829,103.94000217,-2.41710372 bbox = BBox([longitude_min, latitude_min, longitude_max, latitude_max], crs="EPSG:4326") time_interval = ('2022-01-01', '2023-07-31') output_directory = 'SFTP' result = detect_deforestation(bbox, time_interval, output_directory) print(result)