CoolFace
Apppublic

forestaiUs/treeextraction-ndvi

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
geospatial.cpython-310.pyc161 linesDownload Raw Back to __pycache__
1o

2&�hYN�@s�dZddlZddlZddlZddlZddlZddlmZm	Z	m3Z4ddlZddlZddl
mZmZmZddlmZddd	�Zddd�Zd
d�Zddd�Zdd�Z	ddd�Zddd�ZdS)z�5Geospatial utilities for image processing and GeoJSON generation.6This module adapts techniques from the geoai library for better polygon generation7with simplified dependencies.8�N)�Image�TiffTags�TiffImagePlugin)�Polygon�MultiPolygon�mapping)�ops�2�����Mb`?c9CsRz�t�|tj�}|durt�|��d�}t�|�}t�|ddtj	�\}}t�10|tjtj�\}}g}|D]T}	t�
|	�}11|12|kr?q3|t�|	d�}t�|	|d�}t|�dkr�g}
|D]}|d\}}|
�t|�t|�f�qX|
d|
dkr{|
�|
d�t|
�}|jr�|�|�q3|WSty�}zt�d	t|����gWYd}~Sd}~ww)13a�14    Extract contours from an image and convert them to polygons.15    Uses OpenCV's contour detection with douglas-peucker simplification.16 17    Args:18        image_path (str): Path to the processed image19        min_area (int): Minimum contour area to keep20        epsilon_factor (float): Simplification factor for douglas-peucker algorithm21 22    Returns:23        list: List of polygon objects24    N�L���T�r�����zError extracting contours: )�cv2�imreadZIMREAD_GRAYSCALEr�open�convert�np�array�	thresholdZ
THRESH_BINARYZfindContoursZ
RETR_EXTERNALZCHAIN_APPROX_SIMPLEZcontourAreaZ	arcLengthZapproxPolyDP�len�append�floatr�is_valid�	Exception�logging�error�str)�25image_path�min_areaZepsilon_factor�img�pil_img�_�thresh�contours�polygons�contour�area�epsilon�approxZpolygon_points�point�x�y�polygon�e�r0�M/Users/dynamicpacific/Dropbox/DEV/ForestAI-TreeExtraction/utils/geospatial.py�extract_contourss>
262728���r2��?cCs6g}|D]}|j|dd�}|jr|js|�|�q|S)z�29    Apply polygon simplification to reduce the number of vertices.30 31    Args:32        polygons (list): List of shapely Polygon objects33        tolerance (float): Simplification tolerance34 35    Returns:36        list: List of simplified polygons37    T)�preserve_topology)�simplifyr�is_emptyr)r&�	tolerance�38simplifiedr.Zsimpr0r0r1�simplify_polygonsNs39�r9cCs�g}|D]f}zC|j}|d|d}|d|d}|j||}|dkrC|j\}}}	}40|�t||f|	|f|	|41f||42f||fg��n|�|�Wqtyj}zt�dt|����|�|�WYd}~qd}~ww|S)z�43    Regularize polygons to make them more rectangular when appropriate.44 45    Args:46        polygons (list): List of shapely Polygon objects47 48    Returns:49        list: List of regularized polygons50    �rr�g�������?zError regularizing polygon: N)�boundsr(rrrr�warningr)r&Zregularizedr.r<�width�heightZ51area_ratio�minx�miny�maxx�maxyr/r0r0r1�regularize_polygonsbs*5253�54���rD�@csL|sgS�fdd�|D�}t�|�}t|t�r|gSt|t�r$t|j�SgS)a
55    Merge polygons that are close to each other to reduce the polygon count.56 57    Args:58        polygons (list): List of shapely Polygon objects59        distance_threshold (float): Distance threshold for merging60 61    Returns:62        list: List of merged polygons63    csg|]}|����qSr0)�buffer)�.0r.��distance_thresholdr0r1�64<listcomp>�sz)merge_nearby_polygons.<locals>.<listcomp>)r�unary_union�65isinstancerr�list�geoms)r&rI�buffered�unionr0rHr1�merge_nearby_polygons�s66676869rQc.Cs��z�|���d�r�zqddl}ddlm}t�d|���|�|��P}|jdurj|j	}|j�70�dkrD||jd|j|j|j
|j�\}}}}n|\}}}}t�d|�d	|�d71|�d	|���||||fWd�WWSWd�n1stwYWnty�}	zt�dt|	��d��WYd}	~	nd}	~	wwt�|�}72t|73d
��r�|74j�r�t�d�d}d}t|75jd�r�|76j��ni}
d}|
s�|r�t�d|���d}d}d}d}t�d|�d	|�d77|�d	|���||||fWS|
D]*\}}tj�|t|��}t�d|�d|�d|���|dk�r|}q�|dk�r|}q�gd�}d}|D]}|t|78j�v�r6d}t�d|���n�q d}t�|t|79j��}|�sI|�r~|�s~t�d �z|�r_t�d!|d���Wnt�y}}	zt�d"t|	����WYd}	~	nd}	~	ww|�r�|�r�t|d�}t|d#�}t|d�t|d#�t|d$�}}}t|d%�t|d&�t|d'�} }!}"|80j\}#}$| }|!}| |#|}|!|$|}t�d(|�d	|�d81|�d	|���||||fWSt�d)�n�t|82d*��r�|83���r�|84��}%|%�r�d+|%v�r�|%d+}&d#|&v�r�d$|&v�r�d%|&v�r�d&|&v�r�|&d#}'|&d$}(|(dd|(dd#|(d#d|(d#d#d,|(d$d|(d$d#d-})|'d.k�rR|)})|&d%}*|&d&}+|+dd|+dd#|+d#d|+d#d#d,|+d$d|+d$d#d-},|*d/k�r�|,},d0}-|)|-}|,|-}|)|-}|,|-}t�d1|�d	|�d85|�d	|���||||fWSt�d2�t�d3�WdSt�y�}	zt�d4t|	����WYd}	~	dSd}	~	ww)5a86    Extract geographic coordinates from image metadata (EXIF, GeoTIFF).87    Uses rasterio for more reliable GeoTIFF handling.88 89    Args:90        image_path (str): Path to the image file91 92    Returns:93        tuple: (min_lat, min_lon, max_lat, max_lon) or None if not found94    ��.tif�.tiffrN��transform_boundsz+Using rasterio to extract coordinates from ���	EPSG:4326z$Extracted coordinates from GeoTIFF: �,� to zRasterio extraction failed: z, falling back to PIL�tagz:Detected image with tags, checking for geospatial metadata�itemsFz+Special case for Brazil image detected in: g�(\���6�gq=95ף�E�gq=96ף�6�g�G�z�E�z Using known Brazil coordinates: z97TIFF tag: z (z): i�i��)ZModelPixelScaleZ
ModelTiepointZGeoKeyZGeoAsciiTzFound GeoTIFF indicator: z$ModelPixelScaleTag.*?value: b'(.*?)'z$GeoTIFF indicators detected in imagezFound raw pixel scale data: zError parsing raw tag data: r;r:r��zExtracted geo bounds: z*No valid geospatial metadata found in TIFF�_getexifi%��<i�S�Wg{�G�z�?zExtracted EXIF GPS bounds: z#No valid GPS metadata found in EXIFz3Could not extract geospatial coordinates from imagez"Error extracting geo coordinates: ) �lower�endswith�rasterio�
rasterio.warprVr�infor�crsr<�to_epsg�left�bottom�right�toprr=rr�hasattrr[r\r�TAGS�get�debug�re�findallrr�sizer_).rrerV�srcr<�west�south�east�northr/r!Zpixel_scale_tagZtiepoint_tagZtag_dictZis_brazil_image�min_lat�min_lon�max_lat�max_lonZtag_id�value�tag_nameZgeotiff_indicatorsZhas_geotiff_indicators�	indicatorZlog_patternZlog_matches�x_scale�y_scale�i�j�kr,r-�zr>r?�exifZgps_infoZlat_ref�latZlat_valZlon_ref�lonZlon_val�deltar0r0r1�"extract_geo_coordinates_from_image�s�98�"99���"��100101"102103��104� ��((105"(P106P107"108109��r�cs�d����fvrt�d�d\��d\��dgd�}������fdd��t|�D]0\}}	t|	jj�}110�fd	d111�|112D�}d|gd�}d
|ddd|d��i|d�}
|d�|
�q)|S)aQ113    Convert polygons to GeoJSON with proper geographic transformation.114 115    Args:116        polygons (list): List of shapely Polygon objects117        image_height (int): Height of the source image118        image_width (int): Width of the source image119        min_lat (float, optional): Minimum latitude for geographic bounds120        min_lon (float, optional): Minimum longitude for geographic bounds121        max_lat (float, optional): Maximum latitude for geographic bounds122        max_lon (float, optional): Maximum longitude for geographic bounds123 124    Returns:125        dict: GeoJSON object126    NzTNo geographic coordinates provided for GeoJSON transformation. Using default values.)��X��@@)�X��A@�FeatureCollection��type�featurescs0�|���}�|���}||fS)Nr0)r,r-r�r�)�image_height�image_widthr|r}rzr{r0r1�transform_pointjsz:convert_to_geojson_with_transform.<locals>.transform_pointcsg|]	\}}�||��qSr0r0)rGr,r-)r�r0r1rJwsz5convert_to_geojson_with_transform.<locals>.<listcomp>r)r��coordinates�Featurer;�namezFeature )r��id�127properties�geometryr�)rr=�	enumeraterM�exterior�coordsr)r&r�r�rzr{r|r}�geojsonr�r.r�Z128geo_coordsr��featurer0)r�r�r|r}rzr{r�r1�!convert_to_geojson_with_transformKs,129����	r��	buildingscCs��zYt�|�}|j\}}ddlm}||d|dddd�\}}|s+t�d�d	gd130�WS|}	|	sZd|vrZ|�dd�}	tj	�131|	�sZ|	�d
d�d}132dD]}tj	�133|134|�rY|135|}	nqIt�d|	���d}|	rxtj	�136|	�rxt�d|	���t
|	�}|s�t�d�t
|�}|r�|\}
}}}t�d|�d|
�d|�d|���n�|	�r@tj	�137|	��r@|	���d��r@zfddl}ddlm}|�|	��L}|jdu�r|j}|j��dkr�||jd|j|j|j|j�\}}}}n|\}}}}||||f\}
}}}t�d|�d|
�d|�d|���Wd�n	1�swYWn7t�y?}zt�dt|����t�d�d\}
}d\}}WYd}~nd}~wwt�d�d\}
}d\}}t||||
|||d�}|WSt�y|}zt�d t|����d	gd138�WYd}~Sd}~ww)!ad139    Complete pipeline to convert an image to a simplified GeoJSON.140 141    Args:142        image_path (str): Path to the processed image143        feature_type (str): Type of features to extract ("buildings", "trees", "water", "roads")144        original_file_path (str, optional): Path to the original uploaded file145 146    Returns:147        dict: GeoJSON object148    r)�segment_and_extract_featuresNr	g@rE)Zoutput_mask_path�feature_typer �simplify_toleranceZmerge_distancez1No polygons found in the image after segmentationr�r�Z149_processed��.r;)rSrTz.jpgz.jpegz.pngzUsing original image path: z-Checking original image for geospatial data: z,Checking processed image for geospatial datazUsing extracted coordinates: rYrZrRrUrWrXz!Using coordinates from rasterio: z-Failed to extract coordinates with rasterio: zCNo coordinates found in image, using default location in Central US)r�r�)r�r�)rzr{r|r}zError in GeoJSON processing: )rrrtZutils.segmentationr�rr=�replace�os�path�exists�rsplitrgr�rcrdrerfrVrhr<rirjrkrlrmrrr�r)rr��original_file_pathr!r>r?r�r#r&Zoriginal_image_path�	base_path�extr�rzr{r|r}rerVrur<rvrwrxryr/r�r0r0r1�process_image_to_geojson�s�150151152�	153�154$$�"���
155��156���r�)r	r157)r3)rE)NNNN)r�N)�__doc__r�r�uuid�numpyrr�PILrrr�jsonrr�shapely.geometryrrr�shapelyrr2r9rDrQr�r�r�r0r0r0r1�<module>s(158159<160#,161�B