forestaiUs/treeextraction-ndvi
0
1import os2import logging3import uuid4import numpy as np5from PIL import Image6import json7 8# Try to import GDAL, but provide fallback for environments without it9try:10 from osgeo import gdal, ogr, osr11 HAS_GDAL = True12except ImportError:13 logging.warning("GDAL not available. Using simplified GeoJSON conversion.")14 HAS_GDAL = False15 16def convert_to_geojson(image_path):17 """18 Convert a processed image to GeoJSON format.19 This function extracts features from the processed image and converts them20 to GeoJSON polygons or linestrings.21 22 Args:23 image_path (str): Path to the processed image24 25 Returns:26 dict: GeoJSON object27 """28 try:29 logging.info(f"Converting image to GeoJSON: {image_path}")30 31 # Open the image32 img = Image.open(image_path)33 img_array = np.array(img)34 35 # Create a simple GeoJSON structure36 geojson = {37 "type": "FeatureCollection",38 "features": []39 }40 41 # Extract contours from the image42 # In a real application, we would use OpenCV's findContours here43 # Since we're simulating it, we'll create a simplified process44 height, width = img_array.shape45 46 # Create a random bounding box as a demo47 # In a real application, this would be based on actual image analysis48 feature_id = 049 50 # Process the image to find contours51 # (For simplicity, we'll simulate finding features by looking at non-zero pixels)52 visited = np.zeros_like(img_array, dtype=bool)53 54 for y in range(0, height, 10): # Step by 10 for performance55 for x in range(0, width, 10): # Step by 10 for performance56 if img_array[y, x] > 0 and not visited[y, x]:57 # Found a feature, trace its boundary58 feature_id += 159 60 # Simplified feature extraction - in a real app this would be more sophisticated61 # Here we'll just create a small polygon around the point62 coords = []63 size = min(20, min(width-x, height-y))64 65 # Create a simple polygon66 polygon = [67 [x, y],68 [x + size, y],69 [x + size, y + size],70 [x, y + size],71 [x, y] # Close the polygon72 ]73 74 # Convert pixel coordinates to approximate geo-coordinates75 # In a real application, this would use proper geo-referencing76 # Here we'll just normalize to [0,1] range and then to fake lat/long77 geo_polygon = []78 for px, py in polygon:79 # Convert to fake geographic coordinates (for demo purposes)80 lon = (px / width) * 0.1 - 74.0 # Fake longitude centered around New York81 lat = (py / height) * 0.1 + 40.7 # Fake latitude centered around New York82 geo_polygon.append([lon, lat])83 84 # Add the feature to GeoJSON85 feature = {86 "type": "Feature",87 "id": feature_id,88 "properties": {89 "name": f"Feature {feature_id}",90 "value": int(img_array[y, x])91 },92 "geometry": {93 "type": "Polygon",94 "coordinates": [geo_polygon]95 }96 }97 98 geojson["features"].append(feature)99 100 # Mark this area as visited101 for cy in range(y, min(y + size, height)):102 for cx in range(x, min(x + size, width)):103 visited[cy, cx] = True104 105 logging.info(f"Converted image to GeoJSON with {feature_id} features")106 return geojson107 108 except Exception as e:109 logging.error(f"Error in GeoJSON conversion: {str(e)}")110 # Return a minimal valid GeoJSON if there's an error111 return {"type": "FeatureCollection", "features": []}112 