-
Notifications
You must be signed in to change notification settings - Fork 0
/
labellize.py
142 lines (118 loc) · 4.58 KB
/
labellize.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
#!/usr/bin/python
import os
import sys
import warnings
import rasterio
import numpy as np
import geopandas as gpd
import glob
import json
from rasterio.mask import mask
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import resources
class Tile():
"""
Creates the Object Tile plot
"""
def __init__(self, footprint, ax):
"""
Parameters
----------
footprint : list
Dicionaries of all the object tiles existing in the JSON file
ax : matplotlib.axes._subplots.AxesSubplot
"""
self.footprint = footprint
self.ind = 0
self.ax = ax
def on_press(self, event):
if event.key == ' ' or event.key == 'enter':
if self.ind < len(self.footprint):
self.ax.set_visible("True")
img = self.ax.imshow(self.footprint[self.ind]["Object Tile"][0])
plt.title(self.footprint[self.ind]["Label"])
plt.draw()
self.ind += 1
else:
plt.close()
sys.exit(0)
def labellize():
args = sys.argv
if len(args) != 4:
print("Usage : labellize.py [Image Id] [Data folder] [JSON file of labels]")
sys.exit()
else:
dataPath = args[2]+"/ICEYE_X*_GRD_*_"+args[1]+"_*.tif"
dataList = glob.glob(dataPath)
if dataList == []:
print("No image with ID "+ args[1] + " was found!")
sys.exit()
try:
labelsFile = open(args[3])
except OSError:
print("Could not open/read file:", labelsFile)
sys.exit()
try:
labels= json.load(labelsFile)
except Exception as e:
print("Exception: %s" % str(e))
sys.exit()
warnings.filterwarnings("ignore", category=rasterio.errors.NotGeoreferencedWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)
for imagePath in dataList:
image = imagePath.split('/')[2]
imageName = image.split('.')[0]
try:
rastFile = rasterio.open(imagePath)
except rasterio.errors.RasterioIOError:
print("Error opening ",image)
continue
rasterArray = rastFile.read()[0]
cf = float(rastFile.tags()['CALIBRATION_FACTOR'])
norm = np.linalg.norm(rasterArray)
normalArray = rasterArray/norm
sigmaNought = np.dot(cf,np.square(np.abs(normalArray)))
sigmaNoughtdB = np.float32(np.dot(10,np.log10(sigmaNought)))
sigmaNoughtdB16 = sigmaNoughtdB.astype(np.uint16)
if not os.path.exists("outPNG"):
os.mkdir("outPNG")
if not os.path.exists("outGTiff"):
os.mkdir("outGTiff")
resources.writeImage(sigmaNoughtdB16,rastFile.transform,rastFile.crs,imageName,"PNG",1)
resources.writeImage(sigmaNoughtdB,rastFile.transform,rastFile.crs,imageName,"GTiff",1)
resources.writeImage(sigmaNoughtdB,rastFile.transform,rastFile.crs,imageName,"GTiff",0)
rastFile.close()
snGTIFF = "./outGTiff/*.tif"
snList = glob.glob(snGTIFF)
features = []
for imagePath in snList:
backScatter = rasterio.open(imagePath)
features.extend(resources.getFeatures(labels,backScatter))
backScatter.close()
gdf = gpd.GeoDataFrame.from_features(features)
footprint = []
for imagePath in snList:
backScatter = rasterio.open(imagePath)
#print(backScatter.name, " opened")
features.extend(resources.getFeatures(labels,backScatter))
for item in gdf.index:
object = gdf.iloc[item]
if object["External ID"] == imagePath.split('/')[2].strip("_sigmaNoughtdB.tif"):
objectTiles = resources.getObjectTiles(object,backScatter)
footprint.append(objectTiles)
backScatter.close()
"""
Display the sequence of object tiles with their respective labels,
and navigate to the next object tile when pressing space or enter,
until all have been shown.
"""
fig, ax = plt.subplots()
ax.axis("off")
plt.title("Pess Enter or Space bar to start navigating")
callback = Tile(footprint,ax)
fig.canvas.mpl_connect('key_press_event', callback.on_press)
plt.show()
if __name__ == "__main__":
labellize()