babypoby commited on
Commit
4529d11
·
1 Parent(s): 2f43acb

It finally works

Browse files
Files changed (1) hide show
  1. main.py +63 -87
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,20 +36,7 @@ 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):
57
  current_directory = os.getcwd()
58
 
59
  output_directory = os.path.join(current_directory, "outputs")
@@ -78,94 +61,87 @@ def greet(image_path: str):
78
  probs = classify(file_path)
79
  top_3 = probs.head(3)
80
  top_3_list = [[cls, prob] for cls, prob in top_3.items()]
81
-
82
  # Accumulate the top_3_list for each file
83
  all_top_3_list.append(top_3_list)
84
 
85
- # Assign the accumulated top_3_list to the 'species' column of the dataframe
86
  processed_output_df['species'] = all_top_3_list
87
 
88
  final_output_path = 'result'
89
  export_geojson(processed_output_df, final_output_path)
90
 
 
 
 
91
  with rasterio.open(image_path) as src:
92
  tif_image = src.read([1, 2, 3]) # Read the first three bands (RGB)
93
  tif_transform = src.transform
 
94
 
95
  # Read the GeoJSON file
96
- geojson_data = gpd.read_file(final_output_path + '.geojson')
97
-
98
- # Set the interactive backend to Qt5Agg
99
- plt.switch_backend('Qt5Agg') # You have to install PyQt5
100
-
101
- # Enable interactive mode
102
- plt.ion()
103
-
104
- # Plotting
105
- fig, ax = plt.subplots(figsize=(10, 10))
106
-
107
- # Plot the RGB TIF image
108
- show(tif_image, transform=tif_transform, ax=ax)
109
-
110
- # Plot the GeoJSON polygons
111
- geojson_data.plot(ax=ax, facecolor='none', edgecolor='red')
112
-
113
- # Set plot title
114
- ax.set_title('TIF Image with Tree Crowns Overlay')
115
-
116
- # Create an annotation box
117
- annot = ax.annotate("", xy=(0, 0), xytext=(20, 20),
118
- textcoords="offset points",
119
- bbox=dict(boxstyle="round", fc="w"),
120
- arrowprops=dict(arrowstyle="->"))
121
- annot.set_visible(False)
122
-
123
- # Create a function to handle mouse clicks
124
- def on_click(event):
125
- if event.inaxes is not None:
126
- # Get the coordinates of the click
127
- click_point = Point(event.xdata, event.ydata)
128
- # Check if the click is within any of the polygons
129
- for idx, row in geojson_data.iterrows():
130
- if row['geometry'].contains(click_point):
131
- # Access the properties dictionarㅋ
132
- # Extract species and confidence score
133
- species_info = row['species']
134
- confidence_score = row['Confidence_score']
135
- # Display information about the clicked polygon
136
- annot.xy = (event.xdata, event.ydata)
137
- text = f"Polygon {idx}\n\nConfidence:\n{confidence_score}\n\nSpecies and their probability:\n{species_info}"
138
- annot.set_text(text)
139
- annot.set_visible(True)
140
- fig.canvas.draw()
141
- break
142
-
143
- # Connect the click event to the handler function
144
- cid = fig.canvas.mpl_connect('button_press_event', on_click)
145
 
146
- figure = plt.figure()
 
147
 
148
- return figure
 
149
 
150
- #tif_file_name = "TreeCrownVectorDataset_761588_9673769_20_20_32720.tif"
151
- #tif_input = "/Users/jonathanseele/ETH/Hackathons/EcoHackathon/WeCanopy/test/" + tif_file_name
 
 
152
 
153
- # File paths
154
- #tif_file_path = '/Users/taekim/ecohackathon/WeCanopy/test/TreeCrownVectorDataset_761588_9673769_20_20_32720.tif'
155
- #geojson_file_path = '/Users/taekim/ecohackathon/WeCanopy/test/result.geojson'
156
 
157
- # Read the TIF file
 
 
 
 
 
 
158
 
 
 
 
 
 
 
 
 
 
159
 
160
- demo = gr.Interface(
161
- fn=greet,
162
- inputs=gr.File(type='filepath'),
163
- outputs=gr.Plot(label="Tree Crowns")
164
- )
 
165
 
166
- demo.launch()
167
 
168
 
169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
 
 
171
 
 
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")
 
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
  export_geojson(processed_output_df, final_output_path)
73
 
74
+ return final_output_path, image_path
75
+
76
+ def plot_results(geojson_path, image_path):
77
  with rasterio.open(image_path) as src:
78
  tif_image = src.read([1, 2, 3]) # Read the first three bands (RGB)
79
  tif_transform = src.transform
80
+ height, width = tif_image.shape[1], tif_image.shape[2]
81
 
82
  # Read the GeoJSON file
83
+ geojson_data = gpd.read_file(geojson_path + '.geojson')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ # Create Plotly figure
86
+ fig = go.Figure()
87
 
88
+ # Add image to the figure
89
+ fig.add_trace(go.Image(z=tif_image.transpose((1, 2, 0)), hoverinfo = 'none'))
90
 
91
+ # Add polygons to the plot
92
+ for idx, row in geojson_data.iterrows():
93
+ coordinates = row['geometry'].exterior.coords.xy
94
+ x, y = list(coordinates[0]), list(coordinates[1]) # Convert to list
95
 
96
+ # Transform coordinates to match image pixel space
97
+ x_transformed = [(xi - tif_transform.c) / tif_transform.a for xi in x]
98
+ y_transformed = [(yi - tif_transform.f) / tif_transform.e for yi in y]
99
 
100
+ species_info_str = row['species']
101
+ species_info = ast.literal_eval(species_info_str)
102
+ first_array = species_info[0]
103
+ second_array = species_info[1]
104
+ third_array = species_info[2]
105
+ confidence_score = row['Confidence_score']
106
+ 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}"
107
 
108
+ fig.add_trace(go.Scatter(
109
+ x=x_transformed,
110
+ y=y_transformed,
111
+ mode='lines',
112
+ name = '',
113
+ line=dict(color='red'),
114
+ hovertemplate=hovertemplate,
115
+ hoverinfo='text'
116
+ ))
117
 
118
+ fig.update_layout(
119
+ title='TIF Image with Tree Crowns Overlay',
120
+ xaxis_title='X',
121
+ yaxis_title='Y',
122
+ showlegend=False, # Hide the legend
123
+ )
124
 
125
+ return fig
126
 
127
 
128
 
129
+ def greet(image_path: str):
130
+ geojson_path, image_path = process_image(image_path)
131
+ fig = plot_results(geojson_path, image_path)
132
+
133
+ return fig
134
+
135
+
136
+ def main():
137
+ demo = gr.Interface(
138
+ fn=greet,
139
+ inputs=gr.File(type='filepath'),
140
+ outputs=gr.Plot(label="Tree Crowns")
141
+ )
142
+
143
+ demo.launch(share=True)
144
 
145
+ if __name__ == "__main__":
146
+ main()
147