umgefahren commited on
Commit
051ab4e
·
2 Parent(s): 4c50924 4529d11
Files changed (1) hide show
  1. main.py +74 -89
main.py CHANGED
@@ -6,13 +6,10 @@ import os
6
  import json
7
  import gradio as gr
8
  import rasterio
9
- from rasterio.plot import show
10
  import geopandas as gpd
11
- import matplotlib.pyplot as plt
12
- from shapely.geometry import Point
13
-
14
-
15
-
16
 
17
  def row_to_feature(row):
18
  feature = {
@@ -20,10 +17,9 @@ def row_to_feature(row):
20
  "type": "Feature",
21
  "properties": {"Confidence_score": row["Confidence_score"], "species": row['species']},
22
  "geometry": {"type": "Polygon", "coordinates": [row["coordinates"]]},
23
-
24
  }
25
  return feature
26
- # [[first guess, prob],[second guess, prob],[third guess, prob]]
27
  def export_geojson(df, filename):
28
  features = [row_to_feature(row) for idx, row in df.iterrows()]
29
 
@@ -40,35 +36,19 @@ def export_geojson(df, filename):
40
 
41
  print(f"GeoJSON data exported to '{filename}.geojson' file.")
42
 
43
- """
44
- tif_input: the file containing a tif that we are analyzing
45
-
46
- tif_file_name: the file name of the tif input. tif_input is the folder in which the tif file lies
47
- (detectree2 works with that) but generate_tree_images requires path including the file hence the file name is needed
48
-
49
- output_directory: the directory were all in-between and final files are stored
50
-
51
- generate_tree_images stores the cutout tree images in a separate folder
52
-
53
- """
54
-
55
-
56
- def greet(image_path: str, progress=gr.Progress()):
57
  current_directory = os.getcwd()
58
 
59
  output_directory = os.path.join(current_directory, "outputs")
60
  if not os.path.exists(output_directory):
61
  os.makedirs(output_directory)
62
 
63
- progress(0, desc="Running detectree2")
64
  run_detectree2(image_path, store_path=output_directory)
65
- progress(0.1, desc="Postprocessing")
66
 
67
  processed_output_df = postprocess(output_directory + '/detectree2_delin.geojson', output_directory + '/processed_delin')
68
 
69
  processed_geojson = output_directory + '/processed_delin.geojson'
70
 
71
- progress(0.2, desc="Generating tree images")
72
  generate_tree_images(processed_geojson, image_path)
73
 
74
  output_folder = './tree_images'
@@ -77,82 +57,82 @@ def greet(image_path: str, progress=gr.Progress()):
77
 
78
  for file_name in os.listdir(output_folder):
79
  file_path = os.path.join(output_folder, file_name)
 
80
  probs = classify(file_path)
81
  top_3 = probs.head(3)
82
  top_3_list = [[cls, prob] for cls, prob in top_3.items()]
83
-
84
  # Accumulate the top_3_list for each file
85
  all_top_3_list.append(top_3_list)
86
 
87
- # Assign the accumulated top_3_list to the 'species' column of the dataframe
88
  processed_output_df['species'] = all_top_3_list
89
 
90
  final_output_path = 'result'
91
 
92
- progress(0.3, desc="Exporting geojson")
93
  export_geojson(processed_output_df, final_output_path)
94
 
 
 
 
95
  with rasterio.open(image_path) as src:
96
  tif_image = src.read([1, 2, 3]) # Read the first three bands (RGB)
97
  tif_transform = src.transform
 
98
 
99
  # Read the GeoJSON file
100
- geojson_data = gpd.read_file(final_output_path)
101
-
102
- # Set the interactive backend to Qt5Agg
103
- # plt.switch_backend('Qt5Agg') # You have to install PyQt5
104
-
105
- # Enable interactive mode
106
- # plt.ion()
107
-
108
- progress(0.4, desc="Plotting")
109
-
110
- # Plotting
111
- fig, ax = plt.subplots(figsize=(10, 10))
112
-
113
- # Plot the RGB TIF image
114
- show(tif_image, transform=tif_transform, ax=ax)
115
-
116
- # Plot the GeoJSON polygons
117
- geojson_data.plot(ax=ax, facecolor='none', edgecolor='red')
118
-
119
- # Set plot title
120
- ax.set_title('TIF Image with Tree Crowns Overlay')
121
-
122
- # Create an annotation box
123
- annot = ax.annotate("", xy=(0, 0), xytext=(20, 20),
124
- textcoords="offset points",
125
- bbox=dict(boxstyle="round", fc="w"),
126
- arrowprops=dict(arrowstyle="->"))
127
- annot.set_visible(False)
128
-
129
- # Create a function to handle mouse clicks
130
- def on_click(event):
131
- if event.inaxes is not None:
132
- # Get the coordinates of the click
133
- click_point = Point(event.xdata, event.ydata)
134
- # Check if the click is within any of the polygons
135
- for idx, row in geojson_data.iterrows():
136
- if row['geometry'].contains(click_point):
137
- # Access the properties dictionarㅋ
138
- # Extract species and confidence score
139
- species_info = row['species']
140
- confidence_score = row['Confidence_score']
141
- # Display information about the clicked polygon
142
- annot.xy = (event.xdata, event.ydata)
143
- text = f"Polygon {idx}\n\nConfidence:\n{confidence_score}\n\nSpecies and their probability:\n{species_info}"
144
- annot.set_text(text)
145
- annot.set_visible(True)
146
- fig.canvas.draw()
147
- break
 
 
 
148
 
149
- # Connect the click event to the handler function
150
- # cid = fig.canvas.mpl_connect('button_press_event', on_click)
151
-
152
- figure = plt.figure()
153
-
154
- return figure
155
-
156
  #tif_file_name = "TreeCrownVectorDataset_761588_9673769_20_20_32720.tif"
157
  #tif_input = "/Users/jonathanseele/ETH/Hackathons/EcoHackathon/WeCanopy/test/" + tif_file_name
158
 
@@ -163,10 +143,15 @@ def greet(image_path: str, progress=gr.Progress()):
163
  # Read the TIF file
164
 
165
 
166
- demo = gr.Interface(
167
- fn=greet,
168
- inputs=gr.File(type='filepath'),
169
- outputs=gr.Plot(label="Tree Crowns")
170
- )
 
 
 
 
 
 
171
 
172
- demo.launch(server_name='0.0.0.0')
 
6
  import json
7
  import gradio as gr
8
  import rasterio
 
9
  import geopandas as gpd
10
+ import plotly.graph_objects as go
11
+ import numpy as np
12
+ import ast
 
 
13
 
14
  def row_to_feature(row):
15
  feature = {
 
17
  "type": "Feature",
18
  "properties": {"Confidence_score": row["Confidence_score"], "species": row['species']},
19
  "geometry": {"type": "Polygon", "coordinates": [row["coordinates"]]},
 
20
  }
21
  return feature
22
+
23
  def export_geojson(df, filename):
24
  features = [row_to_feature(row) for idx, row in df.iterrows()]
25
 
 
36
 
37
  print(f"GeoJSON data exported to '{filename}.geojson' file.")
38
 
39
+ def process_image(image_path: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  current_directory = os.getcwd()
41
 
42
  output_directory = os.path.join(current_directory, "outputs")
43
  if not os.path.exists(output_directory):
44
  os.makedirs(output_directory)
45
 
 
46
  run_detectree2(image_path, store_path=output_directory)
 
47
 
48
  processed_output_df = postprocess(output_directory + '/detectree2_delin.geojson', output_directory + '/processed_delin')
49
 
50
  processed_geojson = output_directory + '/processed_delin.geojson'
51
 
 
52
  generate_tree_images(processed_geojson, image_path)
53
 
54
  output_folder = './tree_images'
 
57
 
58
  for file_name in os.listdir(output_folder):
59
  file_path = os.path.join(output_folder, file_name)
60
+ print(file_path)
61
  probs = classify(file_path)
62
  top_3 = probs.head(3)
63
  top_3_list = [[cls, prob] for cls, prob in top_3.items()]
64
+
65
  # Accumulate the top_3_list for each file
66
  all_top_3_list.append(top_3_list)
67
 
68
+ # Assign the accumulated top_3_list to the 'species' column of the dataframe
69
  processed_output_df['species'] = all_top_3_list
70
 
71
  final_output_path = 'result'
72
 
 
73
  export_geojson(processed_output_df, final_output_path)
74
 
75
+ return final_output_path, image_path
76
+
77
+ def plot_results(geojson_path, image_path):
78
  with rasterio.open(image_path) as src:
79
  tif_image = src.read([1, 2, 3]) # Read the first three bands (RGB)
80
  tif_transform = src.transform
81
+ height, width = tif_image.shape[1], tif_image.shape[2]
82
 
83
  # Read the GeoJSON file
84
+ geojson_data = gpd.read_file(geojson_path + '.geojson')
85
+
86
+ # Create Plotly figure
87
+ fig = go.Figure()
88
+
89
+ # Add image to the figure
90
+ fig.add_trace(go.Image(z=tif_image.transpose((1, 2, 0)), hoverinfo = 'none'))
91
+
92
+ # Add polygons to the plot
93
+ for idx, row in geojson_data.iterrows():
94
+ coordinates = row['geometry'].exterior.coords.xy
95
+ x, y = list(coordinates[0]), list(coordinates[1]) # Convert to list
96
+
97
+ # Transform coordinates to match image pixel space
98
+ x_transformed = [(xi - tif_transform.c) / tif_transform.a for xi in x]
99
+ y_transformed = [(yi - tif_transform.f) / tif_transform.e for yi in y]
100
+
101
+ species_info_str = row['species']
102
+ species_info = ast.literal_eval(species_info_str)
103
+ first_array = species_info[0]
104
+ second_array = species_info[1]
105
+ third_array = species_info[2]
106
+ confidence_score = row['Confidence_score']
107
+ hovertemplate = f"Polygon:<br>{idx}<br><br>Species and Probability:<br>{first_array}<br>{second_array}<br>{third_array}<br><br>Confidence:<br>{confidence_score}"
108
+
109
+ fig.add_trace(go.Scatter(
110
+ x=x_transformed,
111
+ y=y_transformed,
112
+ mode='lines',
113
+ name = '',
114
+ line=dict(color='red'),
115
+ hovertemplate=hovertemplate,
116
+ hoverinfo='text'
117
+ ))
118
+
119
+ fig.update_layout(
120
+ title='TIF Image with Tree Crowns Overlay',
121
+ xaxis_title='X',
122
+ yaxis_title='Y',
123
+ showlegend=False, # Hide the legend
124
+ )
125
+
126
+ return fig
127
+
128
+
129
+
130
+ def greet(image_path: str):
131
+ geojson_path, image_path = process_image(image_path)
132
+ fig = plot_results(geojson_path, image_path)
133
+
134
+ return fig
135
 
 
 
 
 
 
 
 
136
  #tif_file_name = "TreeCrownVectorDataset_761588_9673769_20_20_32720.tif"
137
  #tif_input = "/Users/jonathanseele/ETH/Hackathons/EcoHackathon/WeCanopy/test/" + tif_file_name
138
 
 
143
  # Read the TIF file
144
 
145
 
146
+ def main():
147
+ demo = gr.Interface(
148
+ fn=greet,
149
+ inputs=gr.File(type='filepath'),
150
+ outputs=gr.Plot(label="Tree Crowns")
151
+ )
152
+
153
+ demo.launch(server_name='0.0.0.0', share=True)
154
+
155
+ if __name__ == "__main__":
156
+ main()
157