-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
370 lines (235 loc) · 8.25 KB
/
Copy pathmain.py
File metadata and controls
370 lines (235 loc) · 8.25 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import cv2
import numpy as np
import matplotlib.pyplot as plt
import time
import io
import requests
from PIL import Image
import xlsxwriter
import xlwt
from xlwt import Workbook
def show(img,title):
plt.imshow(img)
plt.title(title)
plt.xticks([])
plt.yticks([])
plt.show()
def segmented_image(img):
Z = img.reshape((-1,3))
Z = np.float32(Z)
K=35
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
ret, label1, center1 = cv2.kmeans(Z, K, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
center1 = np.uint8(center1)
res1 = center1[label1.flatten()]
output2 = res1.reshape((img.shape))
return output2
def graythresh(array,level):
import numpy as np
maxVal = np.max(array)
minVal = np.min(array)
if maxVal <= 1:
array = array*255
elif maxVal >= 256:
array = np.int((array - minVal)/(maxVal - minVal))
# print "New min value is %s" %(np.min(array))
# turn the negative to natural number
negIdx = np.where(array < 0)
array[negIdx] = 0
# calculate the hist of 'array'
dims = np.shape(array)
hist = np.histogram(array,range(257))
P_hist = hist[0]*1.0/np.sum(hist[0])
omega = P_hist.cumsum()
temp = np.arange(256)
mu = P_hist*(temp+1)
mu = mu.cumsum()
n = len(mu)
mu_t = mu[n-1]
sigma_b_squared = (mu_t*omega - mu)**2/(omega*(1-omega))
# try to found if all sigma_b squrered are NaN or Infinity
indInf = np.where(sigma_b_squared == np.inf)
CIN = 0
if len(indInf[0])>0:
CIN = len(indInf[0])
maxval = np.max(sigma_b_squared)
IsAllInf = CIN == 256
if IsAllInf !=1:
index = np.where(sigma_b_squared==maxval)
idx = np.mean(index)
threshold = (idx - 1)/255.0
else:
threshold = level
if np.isnan(threshold):
threshold = level
return threshold
def VegetationClassification(Img):
#import pymeanshift as pms
import numpy as np
I = segmented_image(Img)/255.0
# show(segmented_image(Img),"segmented image")
# show(I,"next image")
red = I[:,:,0]
green = I[:,:,1]
blue = I[:,:,2]
# calculate the difference between green band with other two bands
green_red_Diff = green - red
green_blue_Diff = green - blue
# show(green_red_Diff,"green_red_Diff")
# show(green_blue_Diff,"green_blue_Diff")
ExG = green_red_Diff + green_blue_Diff
diffImg = green_red_Diff*green_blue_Diff
# show(diffImg,"diffImg")
redThreImgU = red < 0.6
greenThreImgU = green < 0.9
blueThreImgU = blue < 0.6
shadowRedU = red < 0.3
shadowGreenU = green < 0.3
shadowBlueU = blue < 0.3
del red, blue, green, I
greenImg1 = redThreImgU * blueThreImgU*greenThreImgU
greenImgShadow1 = shadowRedU*shadowGreenU*shadowBlueU
del redThreImgU, greenThreImgU, blueThreImgU
del shadowRedU, shadowGreenU, shadowBlueU
greenImg3 = diffImg > 0.0
greenImg4 = green_red_Diff > 0
threshold = graythresh(ExG, 0.1)
if threshold > 0.1:
threshold = 0.1
elif threshold < 0.05:
threshold = 0.05
greenImg2 = ExG > threshold
greenImgShadow2 = ExG > 0.05
greenImg = greenImg1*greenImg2 + greenImgShadow2*greenImgShadow1
# show(greenImgShadow2,"greenImgShadow2")
show(greenImg,"greenImg")
del ExG,green_blue_Diff,green_red_Diff
del greenImgShadow1,greenImgShadow2
# calculate the percentage of the green vegetation
greenPxlNum = len(np.where(greenImg != 0)[0])
greenPercent = greenPxlNum/(400.0*400)*100
del greenImg1,greenImg2
del greenImg3,greenImg4
return greenPercent
#Globals
allImages=[]
lattitudes=[]
longitudes=[]
try:
apikey="******************************" #write API key
except:
print("File not Found")
allImagesGVI=[]
def getImage(lattitude,longitude,heading,pitch):
URL="https://maps.googleapis.com/maps/api/streetview?size=400x400&location={},{}&fov=60&heading={}&pitch={}&key={}"
URL=URL.format(lattitude,longitude,heading,pitch,apikey)
time.sleep(1)
try:
response = requests.get(URL)
img = np.array(Image.open(io.BytesIO(response.content))) #converting byte array to nparray
return img
except:
print("Response not given ")
return
def loadImages():
global lattitudes,longitudes
#file format
# latitude longitude
try:
locationFile=open("./locationdata.txt")
except:
print("File not Found")
return
print("Hello")
allLocations=locationFile.readlines() #read all the locations in file and returns list[lat,long]
locationFile.close()
allLocations=list(map(lambda location:location[:-1].split(","),allLocations))#removing all \n
print(allLocations)
lattitudes=list(map(lambda location:location[0],allLocations))
longitudes=list(map(lambda location:location[1],allLocations))
allHeaders=[] #contains all heading angles
for i in range(6):
allHeaders.append(i*60)
allPitch=[-45,0,45]
for i in range(len(allLocations)):
headerImg=[]
for heading in allHeaders:
pitchImg=[]
for pitch in allPitch:
pitchImg.append( getImage(lattitudes[i],longitudes[i],heading,pitch) )
headerImg.append(pitchImg)
allImages.append(headerImg)
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
def removeFaultyObjects(image):
global net
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))
# Loading image
img=image
height, width, channels = img.shape
# Detecting objects
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)
# Showing informations on the screen
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
# Object detected
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
# Rectangle coordinates
x = int(center_x - w / 2)
y = int(center_y - h / 2)
img[y:y+h,x:x+w] = [255,255,255]
#cv2.destroyAllWindows()
return img
#def showImages(images):
loadImages()
#showImages(allImages)
total=len(allImages)
for i in allImages:
green=0
for j in i:
for k in j:
plt.title("Original Image")
plt.imshow(k)
plt.show()
k=removeFaultyObjects(k)
plt.title("After Processing Image")
plt.imshow(k)
plt.show()
green+=VegetationClassification(k)
allImagesGVI.append(green/18)
print(sum(allImagesGVI)/total)
def store():
# workbook=xlsxwriter.Workbook('./Example.xlsx')
#
# worksheet=workbook.add_worksheet("sheet1")
wb=Workbook()
worksheet=wb.add_sheet("sheet 1")
row=2
col=0
worksheet.write(0,0,"RCOEM DATA")
worksheet.write(1,0,"lattitude")
worksheet.write(1,1,"longitude")
worksheet.write(1,2,"GVI")
#worksheet.write(0,0,"L")
for i in range(len(allImages)):
worksheet.write(row,col,lattitudes[i])
worksheet.write(row,col+1,longitudes[i])
worksheet.write(row,col+2,allImagesGVI[i])
row+=1
worksheet.write(row,col,"Total")
worksheet.write(row,col+1,sum(allImagesGVI)/total)
wb.save('xlwt rcoemdatafinal.xls')
store()