-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcheck_accuracy_2cat_landsat.py
295 lines (250 loc) · 10.5 KB
/
check_accuracy_2cat_landsat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
#import resources
from osgeo import gdal
import imageio
import numpy as np
from PIL import Image
import json
import rasterio
from rasterio.mask import mask
from json import loads
import os, sys
from os import listdir
from os.path import isfile, join
import shutil
from groundtruth_preprocessing import *
#######################################################################################################################
'''
Method to convert .png into .tif files
.tiff files need to have WGS84 coordinate system
'''
def CovertPNGtoTIFF(mainFolder, inputFolder):
# load GDAL (Geospatial Data Abstraction Library) driver for tiff files
driver = gdal.GetDriverByName('GTiff')
# Get one tif file of this district for reference. This can be the initial tif files downloaded from GEE
for infile in os.listdir(mainFolder+'/2018'):
if (infile[-4:] == ".tif"):
filepath = mainFolder+"/2018/"+infile
#print(filepath)
break
reference_image = gdal.Open(filepath)
#1 because we have information in a single band (prediction classes)
pixel_predictions = (reference_image.GetRasterBand(1)).ReadAsArray()
[cols, rows] = pixel_predictions.shape
#print("Rows: ",rows," Cols: ",cols)
path_for_final_prediction_pngs = inputFolder
#print(path_for_final_prediction_pngs)
#print(os.getcwd())
os.makedirs(path_for_final_prediction_pngs+'/tifs',exist_ok=True)
for infile in os.listdir(path_for_final_prediction_pngs):
#print(infile)
if infile[-4:] == ".png":
#print(infile)
pngImage = np.array( Image.open( path_for_final_prediction_pngs+'/'+infile ))
#print("The unique labels in png image are: ", np.unique(pngImage) )
#print("The shape of png image is: ", pngImage.shape )
destination_filename = path_for_final_prediction_pngs+'/tifs/'+infile[:-4]+'.tif'
#Setting the structure for the destination tif file
dst_ds = driver.Create(destination_filename, rows, cols, 1, gdal.GDT_UInt16)
dst_ds.SetGeoTransform(reference_image.GetGeoTransform())
dst_ds.SetProjection(reference_image.GetProjection())
dst_ds.GetRasterBand(1).WriteArray(pngImage)
dst_ds.FlushCache()
# #Checking the validity of created tif file
# tiffImage = np.asarray( Image.open(destination_filename) )
# print("The unique labels in png image are: ", np.unique(tiffImage) )
# print("The shape of png image is: ", tiffImage.shape )
##############################################################################################################################
def combine_bu_nbu_tifs(tif_folder_path):
nbu_list=['Bareland','Water','Greenery']
i=0
for cat in nbu_list:
for infile in os.listdir(tif_folder_path+'/'+cat):
i=i+1
if infile[-4:] == ".tif":
os.makedirs(tif_folder_path+"/2cat/NBU",exist_ok=True)
shutil.copy(tif_folder_path+'/'+cat+'/'+infile, tif_folder_path+"/2cat/NBU/"+str(i)+'_'+infile)
for infile in os.listdir(tif_folder_path+'/Builtup'):
if infile[-4:] == ".tif":
os.makedirs(tif_folder_path+"/2cat/BU",exist_ok=True)
shutil.copy(tif_folder_path+"/Builtup"+'/'+infile, tif_folder_path+"/2cat/BU/"+infile)
def CutTifffile(folder_tifffiles,folder_groundtruth_shapefiles):
for infile in listdir(folder_tifffiles):
if '2018' in infile:
tiff_file_name = infile
#print(tiff_file_name)
i = 0
for shapefile in listdir(folder_groundtruth_shapefiles):
if shapefile[-5:]=='.json':
#print(shapefile)
json_data = json.loads(open(folder_groundtruth_shapefiles+'/'+shapefile).read())
#print(json_data)
output_directory = folder_tifffiles+'/'+shapefile[:-5]
os.makedirs(output_directory, exist_ok=True)
for currFeature in json_data["features"]:
#print(currFeature)
i += 1
try:
geoms = [currFeature["geometry"]]
#print(geoms)
with rasterio.open(folder_tifffiles+'/'+tiff_file_name) as src:
#print(src)
out_image, out_transform = mask(src, geoms, crop = True)
out_meta = src.meta
# save the resulting raster
out_meta.update({ "driver": "GTiff", "height": out_image.shape[1], "width": out_image.shape[2], "transform": out_transform})
saveFileName = output_directory+"/"+str(i)+".tif"
with rasterio.open(saveFileName, "w", **out_meta) as dest:
dest.write(out_image)
except:
continue
print('done')
combine_bu_nbu_tifs(folder_tifffiles)
######################################################Methods for calculating Accuracy##############################################
def precision(label, confusion_matrix):
col = confusion_matrix[:, label]
return (confusion_matrix[label, label] / col.sum())*100
def recall(label, confusion_matrix):
row = confusion_matrix[label, :]
return (confusion_matrix[label, label] / row.sum())*100
def precision_macro_average(confusion_matrix):
rows, columns = confusion_matrix.shape
sum_of_precisions = 0
for label in range(rows):
sum_of_precisions += precision(label, confusion_matrix)
return sum_of_precisions / rows
def recall_macro_average(confusion_matrix):
rows, columns = confusion_matrix.shape
sum_of_recalls = 0
for label in range(columns):
sum_of_recalls += recall(label, confusion_matrix)
return sum_of_recalls / columns
def write_to_file(file_name, text_to_append):
"""Append given text as a new line at the end of file"""
# Open the file in append & read mode ('a+')
with open(file_name, "a+") as file_object:
# Move read cursor to the start of file.
file_object.seek(0)
# If file is not empty then append '\n'
data = file_object.read(100)
if len(data) > 0:
file_object.write("\n")
# Append text at the end of file
file_object.write(text_to_append)
def write_listoflist_to_file(file_name,input_list):
with open(file_name, 'a+') as f:
for _list in input_list:
for _string in _list:
#f.seek(0)
f.write(str(_string) + ', ')
f.write('\n')
def ComputeAccuracy(cropped_images_folder, text_file):
# specifying integer code of land cover classes
green = 1
water = 2
builtup = 3
barrenland = 4
landcover_classes = ['BU','NBU']
confusion_matrix = []
for landcover in landcover_classes:
landcover_predicted_class_count = [0, 0] # [bu, nbu (green + water + bareland)]
tif_files_path = cropped_images_folder+'/'+landcover
for tif_file in os.listdir(tif_files_path):
tif_image = np.asarray(Image.open(tif_files_path+'/'+tif_file))
if green in np.unique(tif_image, return_counts=True)[0]:
landcover_predicted_class_count[1] += np.unique(tif_image, return_counts=True)[1][np.where(np.unique(tif_image,return_counts=True)[0]==green)[0][0]]
if water in np.unique(tif_image, return_counts=True)[0]:
landcover_predicted_class_count[1] += np.unique(tif_image, return_counts=True)[1][np.where(np.unique(tif_image,return_counts=True)[0]==water)[0][0]]
if builtup in np.unique(tif_image, return_counts=True)[0]:
landcover_predicted_class_count[0] += np.unique(tif_image, return_counts=True)[1][np.where(np.unique(tif_image,return_counts=True)[0]==builtup)[0][0]]
if barrenland in np.unique(tif_image, return_counts=True)[0]:
landcover_predicted_class_count[1] += np.unique(tif_image, return_counts=True)[1][np.where(np.unique(tif_image,return_counts=True)[0]==barrenland)[0][0]]
confusion_matrix.append(landcover_predicted_class_count)
cm = np.array(confusion_matrix)
write_to_file(text_file,'Confusion Matrix (BU, NBU): \n')
write_listoflist_to_file(text_file,confusion_matrix)
print("Confusion Matrix (BU, NBU): \n",confusion_matrix,"\n")
print("label precision recall avg_precision avg_recall")
write_to_file(text_file,'label precision recall avg_precision avg_recall')
for label in range(2):
s = f"{label:5d} {precision(label, cm):9.3f} {recall(label, cm):6.3f} {precision_macro_average(cm):6.3f} {recall_macro_average(cm):6.3f}"
write_to_file(text_file,s)
print(s)
######################################## main method #########################################################################
def main():
input_folder = sys.argv[1] #we have stored monthly predections in a folder named by district name
year = '2018'
#print(os.path.isfile(input_folder))
if input_folder.split('/')[-1]=='':
input_folder = input_folder[:-1]
district_name = input_folder.split('/')[-1]
else:
district_name = input_folder.split('/')[-1]
print('Name of Area/District - ',district_name)
choice = input(
'''
Please enter one of the following choices(1,2,3 or 4) :
Enter 1 - for Direct Application
Enter 2 - for Temp Corrected Direct Application
Enter 3 - for Rule based Approach
Enter 4 - for Temp corrected Rule based Approach
''')
if choice == '1':
chosen_folder = input_folder + '/results/'+'direct_application'
heading = '''
-------------------------
Direct Aplication
-------------------------
'''
elif choice == '2':
chosen_folder = input_folder + '/results/'+'direct_application_temp_corrected'
heading = '''
-----------------------------------------
Temporal Correction on Direct Aplication
-----------------------------------------
'''
elif choice == '3':
chosen_folder = input_folder + '/results/'+'combined_yearly_prediction'
heading = '''
-------------------------
Rule Based Approach
-------------------------
'''
elif choice =='4':
chosen_folder = input_folder + '/results/'+'combined_yearly_prediction_temp_corrected'
heading = '''
-------------------------------------------
Temporal Correction on Rule based approach
-------------------------------------------
'''
else:
print('''
Wrong choice entered!
Please try again.
''')
sys.exit("Wrong Input")
print ('''
Step1 - Converting png files into tif files with WGS84 coordinated system
''')
CovertPNGtoTIFF(input_folder,chosen_folder)
print('''
Step2 - Cut district/area .tif files(classification) using groundtruth shapefiles.
''')
folder_tifffiles = chosen_folder + '/tifs'
folder_groundtruth_shapefiles = 'groundtruth/'+district_name
output_cut_tiffiles=''
print(folder_tifffiles)
print(folder_groundtruth_shapefiles)
CutTifffile(folder_tifffiles,folder_groundtruth_shapefiles)
print('''
Step3 - Calulate accuracy for all classes.
''')
# Name of the containing folder of cropped_images where the cropped tif files of predictions are stored
cropped_images_folder=chosen_folder + '/tifs/2cat'
text_file_path = input_folder+'/'+district_name+'_accuracy_2cat.txt'
text_file_heading = "District - " + district_name
write_to_file(text_file_path,text_file_heading)
write_to_file(text_file_path,heading)
groundtruth_preprocessing(cropped_images_folder)
ComputeAccuracy(cropped_images_folder+'_cropped',text_file_path)
if __name__ == '__main__':
main()