| import os |
| import logging |
| import uuid |
| import numpy as np |
| from PIL import Image |
| import json |
|
|
| |
| try: |
| from osgeo import gdal, ogr, osr |
| HAS_GDAL = True |
| except ImportError: |
| logging.warning("GDAL not available. Using simplified GeoJSON conversion.") |
| HAS_GDAL = False |
|
|
| def convert_to_geojson(image_path): |
| """ |
| Convert a processed image to GeoJSON format. |
| This function extracts features from the processed image and converts them |
| to GeoJSON polygons or linestrings. |
| |
| Args: |
| image_path (str): Path to the processed image |
| |
| Returns: |
| dict: GeoJSON object |
| """ |
| try: |
| logging.info(f"Converting image to GeoJSON: {image_path}") |
| |
| |
| img = Image.open(image_path) |
| img_array = np.array(img) |
| |
| |
| geojson = { |
| "type": "FeatureCollection", |
| "features": [] |
| } |
| |
| |
| |
| |
| height, width = img_array.shape |
| |
| |
| |
| feature_id = 0 |
| |
| |
| |
| visited = np.zeros_like(img_array, dtype=bool) |
| |
| for y in range(0, height, 10): |
| for x in range(0, width, 10): |
| if img_array[y, x] > 0 and not visited[y, x]: |
| |
| feature_id += 1 |
| |
| |
| |
| coords = [] |
| size = min(20, min(width-x, height-y)) |
| |
| |
| polygon = [ |
| [x, y], |
| [x + size, y], |
| [x + size, y + size], |
| [x, y + size], |
| [x, y] |
| ] |
| |
| |
| |
| |
| geo_polygon = [] |
| for px, py in polygon: |
| |
| lon = (px / width) * 0.1 - 74.0 |
| lat = (py / height) * 0.1 + 40.7 |
| geo_polygon.append([lon, lat]) |
| |
| |
| feature = { |
| "type": "Feature", |
| "id": feature_id, |
| "properties": { |
| "name": f"Feature {feature_id}", |
| "value": int(img_array[y, x]) |
| }, |
| "geometry": { |
| "type": "Polygon", |
| "coordinates": [geo_polygon] |
| } |
| } |
| |
| geojson["features"].append(feature) |
| |
| |
| for cy in range(y, min(y + size, height)): |
| for cx in range(x, min(x + size, width)): |
| visited[cy, cx] = True |
| |
| logging.info(f"Converted image to GeoJSON with {feature_id} features") |
| return geojson |
| |
| except Exception as e: |
| logging.error(f"Error in GeoJSON conversion: {str(e)}") |
| |
| return {"type": "FeatureCollection", "features": []} |
|
|