WeCanopy / polygons_processing /polygons_test.py
moritzmoritzmoritzmoritz
initial commit for logic problem
a957001
raw
history blame
2.78 kB
# -*- coding: utf-8 -*-
"""
Created on Tue May 21 13:44:53 2024
@author: morit
"""
import json
from shapely.geometry import Polygon
from shapely.ops import unary_union
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon as MplPolygon
import numpy as np
import pandas as pd
with open('../data_subset/Tree Crown vector datasets-20240520T095639Z-001/Tree Crown vector datasets/manaus_800.geojson', 'r') as file:
data = json.load(file)
print(len(data))
data_list = data['features']
print(data['features'][0])
# Define the coordinates of the two polygons
polygon1_coords = data_list[0]['geometry']['coordinates'][0] #[(0, 0),(1,-1), (2, 0), (2, 2), (1, 2)]
polygon2_coords = data_list[1]['geometry']['coordinates'][0] #[(0.5, -1), (3, 1), (3, 3), (1, 3)]
def add_extreme_coordinates(polygon_data):
polygon_coords = np.array(data_list[0]['geometry']['coordinates'][0])
polygon_data['geometry']['max_lat'] = max(polygon_coords[:,1])
polygon_data['geometry']['min_lat'] = min(polygon_coords[:,1])
polygon_data['geometry']['max_lon'] = max(polygon_coords[:,0])
polygon_data['geometry']['min_lon'] = min(polygon_coords[:,0])
for i in range(len(data_list)):
add_extreme_coordinates(data_list[i])
print(data['features'][0])
# Create Polygon objects
list_polygons = []
N = 50
for i in range(N):
polygon_coords = data_list[i]['geometry']['coordinates'][0] #[(0, 0),(1,-1), (2, 0), (2, 2), (1, 2)]
polygon = Polygon(polygon_coords)
list_polygons.append(polygon)
# Calculate the intersection of the two polygons
#intersection = polygon1.intersection(polygon2)
# Function to plot a polygon
def plot_polygon(ax, polygon, color, label):
if not polygon.is_empty:
x, y = polygon.exterior.xy
ax.fill(x, y, color=color, alpha=0.5, label=label)
# Plot the polygons and their intersection
fig, ax = plt.subplots()
# Plot polygon1
for i,polygon in enumerate(list_polygons):
plot_polygon(ax, polygon, 'blue', f"polygon {i}")
# Plot the intersection
#plot_polygon(ax, intersection, 'red', 'Intersection')
# Add legend
#ax.legend()
# Set axis limits
ax.set_aspect('equal')
#ax.set_xlim(-1, 4)
#ax.set_ylim(-1, 4)
# Set title
ax.set_title('Polygons and their Intersection')
plt.ylabel('lat')
plt.ylabel('lon')
plt.show()
df = pd.DataFrame(data_list).drop(columns='type')
dict_cols = ['properties', 'geometry']
for dict_col in dict_cols:
dict_df = pd.json_normalize(df[dict_col])
# Merge the new columns back into the original DataFrame
df = df.drop(columns=[dict_col]).join(dict_df)
print(dict_df)
print(df)
print(df.columns)
# Calculate and print the area of the intersection
#intersection_area = intersection.area
#print(f"The area of intersection is: {intersection_area}")