-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCameraController.py
More file actions
222 lines (174 loc) · 5.84 KB
/
CameraController.py
File metadata and controls
222 lines (174 loc) · 5.84 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
#!/usr/bin/python
from threading import Lock
from flask import Flask
from flask_restful import Resource, Api
from flask import send_file
from shutil import copyfile
import http
# import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import sys
import numpy as numpy
from PIL import Image
import gc
import http.client
import io
import urllib
import imghdr
import gdal
from gdal import Open
from ndvi import ndvi
# import picamera
app = Flask(__name__)
api = Api(app)
camLock = Lock()
tmp_file_name = "cam_temp.data"
mode_vis_str = "VIS"
mode_ir_str = "IR"
self_url = "http://127.0.0.1:5000/IR"
cam_str = "cam"
ndvi_str = "ndvi"
class Cammock:
__src = ""
__img_type = ""
def __init__(self, srcfilename):
self.__src = srcfilename
def capture(self, filename, img_type):
self.__img_type = img_type
copyfile(self.__src, filename)
def close(self):
a = ""
class PiCameraController(Resource):
__mode = ""
def __init__(self, mode):
self.__mode = mode
def get(self):
attachFileName = self.__mode + '.data'
with camLock:
# camera = picamera.PiCamera()
camera = Cammock(attachFileName)
camera.resolution = (1024, 768)
try:
camera.capture(tmp_file_name, 'rgb')
return send_file(tmp_file_name,mimetype='image/x-rgb', attachment_filename=attachFileName , as_attachment=True)
finally:
camera.close()
class NDVIController(Resource):
__irURL = ""
__visURL = ""
def __init__(self, visURL, irURL):
self.__visURL = visURL # + "/" + cam_str
self.__irURL = irURL # + "/" + cam_str
def get(self):
photosynscore(self.__visURL, self.__irURL)
def readImageFromServer(IMG_URL):
conn = http.client.HTTPConnection(IMG_URL)
conn.request("GET", "/")
response = conn.getresponse()
return response.read()
# function for generating NDVI imagery from NGB or NBG input files
def photosynscore(VIS_IMG_URL, IR_IMG_URL, vmin = -1.0, vmax = 1.0, output= 'plt.png'):
vis_img_temp_file = 'vis_tmp.data'
ir_img_temp_file = 'ir_tmp.data'
type = imghdr.what(ir_img_temp_file)
with urllib.request.urlopen(VIS_IMG_URL) as url:
vis_img_data = url.read()
with urllib.request.urlopen(IR_IMG_URL) as url:
ir_img_data = url.read()
# f = open(vis_img_temp_file, 'wb')
# f.write(vis_img_data)
#
# f = open(ir_img_temp_file, 'wb')
# f.write(ir_img_data)
# if isinstance(vis_img_temp_file,str): # treat as a filename
byteSteam = io.BytesIO(vis_img_data)
byteSteam.seek(0)
img_vis = Image.frombuffer('RGB',(1024,768),vis_img_data)
# if isinstance(ir_img_temp_file,str): # treat as a filename
byteSteam = io.BytesIO(ir_img_data)
byteSteam.seek(0)
img_ir = Image.frombuffer('RGB',(1024,768),ir_img_data)
# create the matplotlib figure
img_w,img_h=img_vis.size
# imgV, _, _ = img_vis.split() # get channels
imgI, _, imgV = img_ir.split() # get channels
# del img_vis, img_ir
# compute the NDVI
arrV = numpy.asarray(imgV).astype('float64')
arrI = numpy.asarray(imgI).astype('float64')
plt.imshow(imgV)
plt.imshow(imgI)
num = (arrI - arrV)
denom = (arrI + arrV)
del arrV
del arrI
with numpy.errstate(divide='ignore', invalid='ignore'):
arr_ndvi = numpy.true_divide(num,denom)
arr_ndvi[arr_ndvi == numpy.inf] = 0
arr_ndvi = numpy.nan_to_num(arr_ndvi)
if output!=None:
# Needs to be floating point
colormap = plt.cm.spectral #plt.cm.gist_gray
dpi=600.0
fig_w=img_w
fig_h=img_h
fig=plt.figure(figsize=(fig_w,fig_h),dpi=dpi)
fig.set_frameon(False)
ax_rect = [0.0, #left
0.0, #bottom
1.0, #width
1.0] #height
ax = fig.add_axes(ax_rect)
ax.yaxis.set_ticklabels([])
ax.xaxis.set_ticklabels([])
ax.set_axis_off()
ax.axes.get_yaxis().set_visible(False)
ax.patch.set_alpha(0.0)
axes_img = ax.imshow(arr_ndvi,
cmap=colormap,
vmin = vmin,
vmax = vmax,
aspect = 'equal',
interpolation="nearest"
)
del axes_img
fig.savefig(output,
dpi=dpi,
bbox_inches='tight',
pad_inches=0.0,
)
del fig
threshold = arr_ndvi[ numpy.where(arr_ndvi>=vmin) ]
del arr_ndvi
normalized = numpy.multiply(numpy.add(threshold,1.0),1/2.0)
del threshold
print(numpy.median(normalized)*100.0)
gc.collect()
def main():
mode = ""
if len(sys.argv) <= 1:
print("Missing argument Mode")
return
mode = sys.argv[1]
if ((mode != mode_ir_str) & (mode != mode_vis_str)):
print("Mode is not valid. Modes available: IR, VIS")
return
api.add_resource(PiCameraController, '/VIS', endpoint="viscam", resource_class_kwargs={'mode': "VIS"})
api.add_resource(PiCameraController, '/IR', endpoint="ircam", resource_class_kwargs={'mode': "IR"})
slaveURL = ""
if (len(sys.argv)) > 2:
slaveURL = sys.argv[2]
# try:
# conn = http.client.HTTPConnection(slaveURL)
# conn.request("GET", "/")
# except:
# print("URL is not working")
# return
if (slaveURL != ""):
if(mode == mode_ir_str):
api.add_resource(NDVIController, '/ndvi', resource_class_kwargs={'visURL': slaveURL, 'irURL': self_url})
if(mode == mode_vis_str):
api.add_resource(NDVIController, '/ndvi', resource_class_kwargs={'visURL': self_url, 'irURL': slaveURL})
app.run(host='127.0.0.1', debug=True, threaded=True)
if __name__ == '__main__':
main()