forked from amitibo/cameranetwork
-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.py
1733 lines (1500 loc) · 57.3 KB
/
controller.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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (C) 2017, Amit Aides, all rights reserved.
#
# This file is part of Camera Network
# (see https://bitbucket.org/amitibo/cameranetwork_git).
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1) The software is provided under the terms of this license strictly for
# academic, non-commercial, not-for-profit purposes.
# 2) Redistributions of source code must retain the above copyright notice, this
# list of conditions (license) and the following disclaimer.
# 3) Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions (license) and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 4) The name of the author may not be used to endorse or promote products derived
# from this software without specific prior written permission.
# 5) As this software depends on other libraries, the user must adhere to and keep
# in place any licensing terms of those libraries.
# 6) Any publications arising from the use of this software, including but not
# limited to academic journal and conference publications, technical reports and
# manuals, must cite the following works:
# Dmitry Veikherman, Amit Aides, Yoav Y. Schechner and Aviad Levis,
# "Clouds in The Cloud" Proc. ACCV, pp. 659-674 (2014).
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
# EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import division
import bisect
from CameraNetwork.arduino_utils import ArduinoAPI
from CameraNetwork.calibration import RadiometricCalibration
from CameraNetwork.calibration import VignettingCalibration
from CameraNetwork.cameras import IDSCamera
import CameraNetwork.global_settings as gs
from CameraNetwork.image_utils import calcHDR
from CameraNetwork.image_utils import FisheyeProxy
from CameraNetwork.image_utils import Normalization
import CameraNetwork.sunphotometer as spm
from CameraNetwork.utils import cmd_callback
from CameraNetwork.utils import DataObj
from CameraNetwork.utils import find_camera_orientation_ransac
from CameraNetwork.utils import find_centroid
from CameraNetwork.utils import getImagesDF
from CameraNetwork.utils import IOLoop
from CameraNetwork.utils import mean_with_outliers
from CameraNetwork.utils import name_time
from CameraNetwork.utils import object_direction
from CameraNetwork.utils import RestartException
import copy
import cPickle
import cv2
from dateutil import parser as dtparser
from datetime import datetime
from datetime import timedelta
import ephem
import fisheye
try:
import futures
except:
#
# Support also python 2.7
#
from concurrent import futures
import glob
import json
try:
from PIL import Image
except:
# In case of old version
import Image
import logging
import numpy as np
import os
import pandas as pd
import pkg_resources
import Queue
from scipy import signal
import scipy.io as sio
import shutil
from sklearn import linear_model
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
import StringIO
import subprocess
import sys
import time
import thread
from tornado import gen
from tornado.concurrent import Future
from tornado.concurrent import run_on_executor
from tornado.queues import PriorityQueue as tPriorityQueue
import traceback
def interpolate_dark_images(exposure, exposures, dark_images):
"""Interpolate the corresponding dark image."""
ri = np.searchsorted(exposures, exposure)
#
# Check if index in bounds
#
if ri == len(exposures):
return dark_images[-1]
elif ri == 0:
return dark_images[0]
re = exposures[ri]
#
# Check if we measured exactly the same exposure.
#
if exposure == re:
return dark_images[ri]
li = ri - 1
le = exposures[li]
#
# Estimate dark image using linear interpolation.
#
dark_image = dark_images[li] + (dark_images[ri] - dark_images[li]) * (exposure - le) / (re - le)
return dark_image
def time2seconds(dt):
"""Convert datetime object to seconds."""
seconds = (dt.hour * 60 + dt.minute) * 60 + dt.second + dt.microsecond * 1e-6
return seconds
class Controller(object):
#
# Thread pull
#
executor = futures.ThreadPoolExecutor(4)
def __init__(self, offline=False, local_path=None):
gs.initPaths(local_path)
#
# Queues for communicating with the server.
#
self._in_queue = tPriorityQueue()
#
# Hardware
#
if not offline:
self.start_camera()
self._arduino_api = ArduinoAPI()
else:
self._camera = None
self._offline = offline
#
# Set the last calibration path.
# Note:
# The calibration path handles the case of multiple calibration dates.
#
self._last_calibration_path = None
#
# Load the camera calibration information.
#
if self._camera is not None:
self.loadCameraCalibration()
#
# Load dark images.
#
self.loadDarkImages()
#
# Load today's celestial position measurements
#
if not os.path.exists(gs.SUN_POSITIONS_PATH):
os.makedirs(gs.SUN_POSITIONS_PATH)
else:
self.loadSunMeasurements()
self.sunshader_angle_model = make_pipeline(
PolynomialFeatures(2),
linear_model.RANSACRegressor(random_state=0, residual_threshold=5)
)
#
# Set the last sunshader scan to "old" time.
#
self.last_sunshader_time = None
self.sunshader_fit = False
#
# Sky mask
#
if os.path.exists(gs.MASK_PATH):
try:
self.sky_mask_base = sio.loadmat(gs.MASK_PATH)['mask_base']
except Exception, e:
logging.error("Failed loading sky mask.")
logging.error("{}".format(traceback.print_exc()))
self.sky_mask_base = None
else:
self.sky_mask_base = None
def loadCameraCalibration(self, capture_date=None, serial_num=None):
"""Load camera calibration data
Load the intrinsic and radiometric calibration data.
Args:
capture_date (datetime object, optional): Date of capture. If
None (default), now will be assumed.
serial_num (str, optional): serial number of sensor. If None
(default), will be taken directly from the sensor.
"""
logging.debug("Loading Camera Calibration.")
if serial_num is None:
logging.debug("Serial number not given.")
if capture_date is not None:
#
# Read the serial number from an arbitrary image from the
# requested dat.
#
day_path = os.path.join(gs.CAPTURE_PATH, capture_date.strftime("%Y_%m_%d"))
datas_list = sorted(glob.glob(os.path.join(day_path, '*.pkl')))
#
# I search the inverted datas_list for the case that the
# function was called to handle intrinsic calibration. This
# handles the case that the sensor was replaced during the day.
#
for data_path in datas_list[::-1]:
try:
with open(data_path, "rb") as f:
data = cPickle.load(f)
serial_num = data.camera_info["serial_num"]
logging.debug(
"Serial number {} taken from: {}".format(serial_num, data_path)
)
break
except:
pass
else:
#
# Not loading a previously saved image use the camera sensor num.
#
serial_num = self._camera.info['serial_num']
logging.debug(
"Serial number {} taken from Camera sensor.".format(serial_num)
)
self.base_calibration_path = os.path.join(
pkg_resources.resource_filename(__name__, '../data/calibration/'),
serial_num
)
#
# Get the list of calibration dates.
#
calibration_dates_paths = sorted(glob.glob(os.path.join(self.base_calibration_path, "20*")))
if len(calibration_dates_paths) == 0:
calibration_path = self.base_calibration_path
else:
calibration_dates = [os.path.split(cdp)[-1] for cdp in calibration_dates_paths]
calibration_dates = [datetime.strptime(d, "%Y_%m_%d") for d in calibration_dates]
#
# Check the relevant calibration date.
#
if capture_date is None:
#
# Live capture, take the most updated index.
#
calibration_index = -1
else:
calibration_index = bisect.bisect(calibration_dates, capture_date) - 1
calibration_path = calibration_dates_paths[calibration_index]
logging.debug("Calibration path is: {}".format(calibration_path))
if self._last_calibration_path is not None and \
self._last_calibration_path == calibration_path:
#
# No need to load new calibration data.
#
logging.debug("Calibration data previously loaded.")
return
self._last_calibration_path = calibration_path
#
# Check if the data exists in the data folder of the code.
# If so, the data is copied to the home folder.
# Note:
# This is done to support old cameras that were not calibrated
# using the test bench.
#
if os.path.exists(self.base_calibration_path):
for base_path, file_name, dst_path in zip(
(calibration_path, calibration_path, self.base_calibration_path),
(gs.INTRINSIC_SETTINGS_FILENAME, gs.VIGNETTING_SETTINGS_FILENAME, gs.RADIOMETRIC_SETTINGS_FILENAME),
(gs.INTRINSIC_SETTINGS_PATH, gs.VIGNETTING_SETTINGS_PATH, gs.RADIOMETRIC_SETTINGS_PATH)
):
try:
shutil.copyfile(
os.path.join(base_path, file_name),
dst_path)
except Exception as e:
logging.error("Failed copying calibration data: {}\n{}".format(
file_name, traceback.format_exc()))
#
# Try to load calibration data.
#
self._fe = None
ocam_path = os.path.join(calibration_path, "ocamcalib.pkl")
print("Searching for ocam path: {}".format(ocam_path))
logging.info("Will search for ocamcalib in path: ".format(ocam_path))
if os.path.exists(ocam_path):
#
# Found an ocamcalib model load it.
#
print("Found ocam path: {}".format(ocam_path))
logging.info("Loading an ocamcalib model from:".format(ocam_path))
with open(ocam_path, "rb") as f:
self._fe = cPickle.load(f)
elif os.path.exists(gs.INTRINSIC_SETTINGS_PATH):
#
# Found an opencv2 fisheye model.
#
logging.info("Loading a standard opencv fisheye model")
self._fe = fisheye.load_model(
gs.INTRINSIC_SETTINGS_PATH, calib_img_shape=(1200, 1600))
if self._fe is not None:
#
# Creating the normalization object.
#
self._normalization = Normalization(
gs.DEFAULT_NORMALIZATION_SIZE, FisheyeProxy(self._fe)
)
if os.path.exists(gs.EXTRINSIC_SETTINGS_PATH):
self._normalization.R = np.load(
gs.EXTRINSIC_SETTINGS_PATH
)
else:
self._normalization = None
#
# Load vignetting settings.
#
try:
self._vignetting = VignettingCalibration.load(gs.VIGNETTING_SETTINGS_PATH)
except:
self._vignetting = VignettingCalibration()
logging.error(
"Failed loading vignetting data:\n{}".format(
traceback.format_exc()))
#
# Load radiometric calibration.
#
try:
self._radiometric = RadiometricCalibration.load(gs.RADIOMETRIC_SETTINGS_PATH)
except:
self._radiometric = RadiometricCalibration(gs.DEFAULT_RADIOMETRIC_SETTINGS)
logging.debug("Failed loading radiometric data. Will use the default values.")
def loadDarkImages(self):
"""Load dark images from disk.
Dark images are used for reducing dark current noise.
"""
di_paths = sorted(glob.glob(os.path.join(gs.DARK_IMAGES_PATH, '*.mat')))
if di_paths:
self._dark_images = {
False: {'exposures': [], 'images': []},
True: {'exposures': [], 'images': []},
}
#
# Load the dark images from disk
#
for path in di_paths:
d = sio.loadmat(path)
gain_boost = d['gain_boost'][0][0] == 1
self._dark_images[gain_boost]['exposures'].append(d['exposure'][0][0])
self._dark_images[gain_boost]['images'].append(d['image'])
#
# Sort the images according to exposures.
#
for gain_boost in (False, True):
exposures = np.array(self._dark_images[gain_boost]['exposures'])
indices = np.argsort(exposures)
self._dark_images[gain_boost]['exposures'] = exposures[indices]
dark_images = self._dark_images[gain_boost]['images']
self._dark_images[gain_boost]['images'] = [dark_images[i] for i in indices]
else:
logging.info("No dark images available")
self._dark_images = None
def loadSunMeasurements(self):
"""Load previously stored sun measurements."""
try:
#
# Check past measurements.
# TODO:
# Add filtering based on date (i.e. not look too further back).
#
past_measurements_paths = sorted(
glob.glob(os.path.join(gs.SUN_POSITIONS_PATH, '*.csv')))
if past_measurements_paths:
angles = []
for path in past_measurements_paths[-2:]:
try:
data = pd.read_csv(path, index_col=0, parse_dates=True)
except Exception as e:
logging.error('Error parsing sun measurements file. The file will be deleted:\n{}'.format(
traceback.format_exc()))
os.remove(path)
continue
#
# Limit the data to sun measurements only.
#
data = data[data['object'] == 'Sun']
#
# Limit the data to angles between a range of "valid"
# angles.
#
data = data[
(data['sunshader_angle'] > gs.SUNSHADER_MIN_MEASURED) &
(data['sunshader_angle'] < gs.SUNSHADER_MAX_MEASURED)
]
data.index = data.index.time
angles.append(data['sunshader_angle'])
# pandas backwards compatibility + silence sort warning
if pd.__version__ < '0.23.0':
self.sunshader_angles_df = pd.concat(angles, axis=1).mean(axis=1).to_frame(name='angle')
else:
self.sunshader_angles_df = pd.concat(angles, axis=1, sort=True).mean(axis=1).to_frame(name='angle')
else:
self.sunshader_angles_df = pd.DataFrame(dict(angle=[]))
except Exception as e:
logging.error('Error while loading past sun measurements:\n{}'.format(
traceback.format_exc()))
self.sunshader_angles_df = pd.DataFrame(dict(angle=[]))
def __del__(self):
self.delete_camera()
@property
def cmd_queue(self):
return self._in_queue
def start(self):
#
# Start the loop of reading commands of the cmd queue.
#
IOLoop.current().spawn_callback(self.process_cmds)
def start_camera(self):
logging.info("Starting camera")
self._camera = IDSCamera()
def delete_camera(self):
if hasattr(self, '_camera'):
logging.info("Deleting camera")
self._camera.close()
del self._camera
def safe_capture(self, settings, frames_num=1,
max_retries=gs.MAX_CAMERA_RETRIES):
"""A wrapper around the camera capture.
It will retry to capture a frame handling
a predetermined amount of failures before
raising an error.
"""
retries = max_retries
while True:
try:
img_array, real_exposure_us, real_gain_db = \
self._camera.capture(settings, frames_num)
break
except Exception as e:
if retries <= 0:
logging.exception(
'The camera failed too many consecutive times. Reboot.'
)
logging.shutdown()
os.system('sudo reboot')
retries -= 1
logging.error(
"The camera raised an Exception:\n{}".format(
traceback.format_exc()
)
)
try:
self.delete_camera()
time.sleep(gs.CAMERA_RESTART_PERIOD)
self.start_camera()
except Exception as e:
logging.exception(
'The camera failed restarting. Rebooting.'
)
logging.shutdown()
time.sleep(120)
os.system('sudo reboot')
return img_array, real_exposure_us, real_gain_db
@cmd_callback
@gen.coroutine
def handle_sunshader_update(self, sunshader_min, sunshader_max):
"""Update the sunshader position."""
current_time = datetime.utcnow()
if self.last_sunshader_time is not None:
#
# Calculate time from last scan.
#
dt = (current_time - self.last_sunshader_time)
else:
#
# Take value large enough to force scan
#
dt = timedelta(seconds=2 * gs.SUNSHADER_SCAN_PERIOD_LONG)
#
# current_time_only is without date, and used for interpolating
# sunshader position.
#
current_time_only = datetime.time(current_time)
#
# Set some parameters according to whether the model is already
# fitting.
#
if self.sunshader_fit:
#
# The model is already fitting.
#
current_angle = self._arduino_api.getAngle()
sunshader_scan_min = max(
current_angle - gs.SUNSHADER_SCAN_DELTA_ANGLE, sunshader_min
)
sunshader_scan_max = min(
current_angle + gs.SUNSHADER_SCAN_DELTA_ANGLE, sunshader_max
)
sunshader_scan_period = gs.SUNSHADER_SCAN_PERIOD_LONG
else:
sunshader_scan_min = sunshader_min
sunshader_scan_max = sunshader_max
sunshader_scan_period = gs.SUNSHADER_SCAN_PERIOD
#
# Is it time to do a scan?
#
measured_angle = None
if dt > timedelta(seconds=sunshader_scan_period):
self.last_sunshader_time = current_time
logging.info('Time to scan')
#
# Do a scan.
#
future = Future()
yield self.handle_sunshader_scan(future, reply=False,
sunshader_min=sunshader_scan_min,
sunshader_max=sunshader_scan_max
)
measured_angle, _ = future.result()
logging.info("Measured angle: {}".format(measured_angle))
#
# Update database with new measurement
# First, add new measurement to dataframe of angles.
#
if gs.SUNSHADER_MIN_MEASURED < measured_angle < gs.SUNSHADER_MAX_MEASURED:
self.sunshader_angles_df.loc[current_time_only] = measured_angle
self.sunshader_angles_df = self.sunshader_angles_df.sort_index()
#
# Refit model.
#
if len(self.sunshader_angles_df) >= 10:
X = np.array(
[time2seconds(dt) for dt in self.sunshader_angles_df.index]
).reshape(-1, 1)
y = self.sunshader_angles_df['angle'].values
try:
self.sunshader_angle_model.fit(X, y)
self.sunshader_fit = True
except Exception as e:
logging.info('Sunshader failed to fit:\n{}'.format(e))
self.sunshader_fit = False
#
# If model fitting failed or there are not enough measurements for
# interpolation angle use measured angle.
#
if (not self.sunshader_fit) or \
len(self.sunshader_angles_df) < gs.SUNSHADER_MIN_ANGLES:
logging.info("Either failed fitting or not enough measurements")
if measured_angle is not None:
logging.info("Using measured angle: {}".format(measured_angle))
self._arduino_api.setAngle(measured_angle)
else:
logging.debug("Sunshader not moved.")
return
#
# Interpolate angle.
#
X = np.array((time2seconds(current_time_only),)).reshape(-1, 1)
estimated_angle = self.sunshader_angle_model.predict(X)[0]
logging.info("Interpolating angle: {}".format(estimated_angle))
self._arduino_api.setAngle(estimated_angle)
@cmd_callback
@run_on_executor
def handle_sunshader_scan(self, reply, sunshader_min, sunshader_max):
"""Scan with the sunshader to find sun position."""
#
# Change camera to small size.
#
self._camera.small_size()
#
# 'Reset' the sunshader.
#
self._arduino_api.setAngle(sunshader_min)
time.sleep(1)
#
# Capture an image for the sky mask.
#
img, _, _ = self.safe_capture(
settings={
"exposure_us": 500,
"gain_db": None,
"gain_boost": False,
"color_mode": gs.COLOR_RGB
}
)
self.update_sky_mask(img)
#
# Sunshader scan loop.
#
saturated_array = []
centers = []
for i in range(sunshader_min, sunshader_max):
self._arduino_api.setAngle(i)
time.sleep(0.1)
img, e, g = self.safe_capture(
settings={
"exposure_us": 200,
"gain_db": None,
"gain_boost": False,
"color_mode": gs.COLOR_RGB
}
)
# TODO CONST 128 and why 128 and not something else?
val = img[img > 128].sum() / img.size
logging.debug(
"Exp.: {}, Gain: {}, image range: [{}, {}], Value: {}".format(
e, g, img.min(), img.max(), val
)
)
if np.isnan(val):
np.save('/home/odroid/nan_img.npy', img)
saturated_array.append(val)
centers.append(find_centroid(img))
#
# Change camera back to large size.
#
self._camera.large_size()
#
# Calculate centroid of sun in images.
#
centers = np.array(centers)
centroid = mean_with_outliers(centers)[0] * 4
logging.debug("Centroid of suns: {}".format(centroid))
#
# Calculate the required sunshader angle.
# Note:
# The saturated_array is smoothed with a butterworth filter. The order
# of the filter is set so that it will not cause filtfilt to throw the
# error:
# ValueError: The length of the input vector x must be at least padlen, which is 27.
#
saturated_array = pd.Series(saturated_array).fillna(method='bfill').values
N = min(8, int((len(saturated_array) - 1) / 3) - 1)
if N >= 4:
b, a = signal.butter(N, 0.125)
sun_signal = signal.filtfilt(b, a, saturated_array)
else:
sun_signal = saturated_array
measured_angle = sunshader_min + np.argmin(sun_signal)
#
# Update sun positions file
#
today_positions_path = os.path.join(
gs.SUN_POSITIONS_PATH,
datetime.utcnow().strftime("%Y_%m_%d.csv"))
if os.path.exists(today_positions_path):
positions_df = pd.read_csv(today_positions_path, index_col=0)
else:
positions_df = pd.DataFrame(columns=('object', 'pos_x', 'pos_y', 'sunshader_angle'))
positions_df.loc[datetime.utcnow()] = ('Sun', centroid[0], centroid[1], measured_angle)
positions_df.to_csv(today_positions_path)
#
# Set the new angle of the sunshader.
#
self._arduino_api.setAngle(measured_angle)
#
# Send back the analysis.
#
if reply:
angles = np.arange(sunshader_min, sunshader_max)
return angles, np.array(saturated_array), sun_signal, measured_angle, centroid
return measured_angle, centroid
def update_sky_mask(self, img):
"""Update the sky mask.
Args:
img (array): RGB image.
"""
#
# Calculate the mask factor
#
mat = img.astype(np.float)
r = mat[..., 0]
g = mat[..., 1]
b = mat[..., 2]
new_mask = (b > 30) & (b > 1.5 * r)
#
# Accumulate the mask factor
#
if self.sky_mask_base is None:
self.sky_mask_base = new_mask
else:
tmp = np.dstack((self.sky_mask_base, new_mask))
self.sky_mask_base = tmp.max(axis=2)
#
# Calculate the mask.
#
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
mask = cv2.morphologyEx(
self.sky_mask_base.astype(np.uint8), cv2.MORPH_OPEN,
kernel, iterations=1)
_, contours, _ = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) == 0:
logging.info('No sky mask contours found.')
return
contour = sorted(contours, key=cv2.contourArea, reverse=True)[0]
self.sky_mask = np.zeros_like(mask)
self.sky_mask = cv2.drawContours(self.sky_mask, [contour], -1, 255, -1)
#
# Store the masks
#
logging.info('Updating the sun mask.')
sio.savemat(
gs.MASK_PATH,
dict(mask_base=self.sky_mask_base, mask=self.sky_mask),
do_compression=True)
@cmd_callback
@run_on_executor
def handle_calibration(self, nx, ny, imgs_num, delay, exposure_us,
gain_db, gain_boost, sunshader_min):
"""Start the geometric calibration."""
logging.debug(
"Handling calibration: nx: {}, ny: {}, imgs_num: {}, delay: {}".format(
nx, ny, imgs_num, delay
)
)
#
# Create debug imgs folder.
#
DEBUG_IMGS_PATH = os.path.expanduser('~/calibration_imgs')
if os.path.exists(DEBUG_IMGS_PATH):
shutil.rmtree(DEBUG_IMGS_PATH)
os.makedirs(DEBUG_IMGS_PATH)
logging.debug("Setting the sunshader away")
#
# Put the sunshader away.
#
self._arduino_api.setAngle(sunshader_min)
time.sleep(1)
#
# Capture the calibration images.
#
imgs = []
for i in range(imgs_num):
self._arduino_api.setAngle(sunshader_min + 2)
img, real_exposure_us, real_gain_db = self._camera.capture(
settings={
"exposure_us": exposure_us,
"gain_db": gain_db,
"gain_boost": gain_boost,
"color_mode": gs.COLOR_RGB
}
)
self._arduino_api.setAngle(sunshader_min)
imgs.append(img)
logging.debug(
"dtype: {}, min: {}, max: {}, shape: {}, exposure: {}, gain_db: {}".format(
img.dtype, img.min(), img.max(), img.shape,
real_exposure_us, real_gain_db
)
)
cv2.imwrite(
os.path.join(DEBUG_IMGS_PATH, 'img_{}.jpg'.format(i)), img
)
time.sleep(delay)
#
# Calibrate the camera
#
logging.debug("Starting calibration")
self._fe = fisheye.FishEye(nx=nx, ny=ny, verbose=True)
rms, K, D, rvecs, tvecs = self._fe.calibrate(
imgs=imgs,
show_imgs=False
)
logging.debug("Finished calibration. RMS: {}.".format(rms))
self._fe.save(gs.INTRINSIC_SETTINGS_PATH)
#
# Creating the normalization object.
#
self._normalization = Normalization(
gs.DEFAULT_NORMALIZATION_SIZE, FisheyeProxy(self._fe)
)
normalized_img = self._normalization.normalize(img)
#
# Send back calibration results and normalized image example.
#
return normalized_img, K, D, rms, rvecs, tvecs
@cmd_callback
@gen.coroutine
def handle_sunshader(self, angle, sunshader_min, sunshader_max):
"""Set the sunshader to an angle"""
if angle < sunshader_min or angle > sunshader_max:
raise ValueError(
"Sunshader angle ({}) not in range ({},{})".format(
angle, sunshader_min, sunshader_max
)
)
self._arduino_api.setAngle(angle)
@cmd_callback
@gen.coroutine
def handle_sprinkler(self, period):
"""Activate the sprinkler for a given period."""
self._arduino_api.setSprinkler(True)
yield gen.sleep(period)
self._arduino_api.setSprinkler(False)
@cmd_callback
@run_on_executor
def handle_moon(self, sunshader_min):
"""Measure Moon position"""
self._arduino_api.setAngle(sunshader_min)
time.sleep(0.1)
img, _, _ = self.safe_capture(
settings={
"exposure_us": 1000000,
"gain_db": None,
"gain_boost": True,
"color_mode": gs.COLOR_RGB
}
)
centroid = find_centroid(img)
#
# Update positions file
#
today_positions_path = os.path.join(
gs.SUN_POSITIONS_PATH,
datetime.utcnow().strftime("%Y_%m_%d.csv"))
if os.path.exists(today_positions_path):
positions_df = pd.read_csv(today_positions_path, index_col=0)
else:
positions_df = pd.DataFrame(columns=('object', 'pos_x', 'pos_y', 'sunshader_angle'))
positions_df.loc[datetime.utcnow()] = ('Moon', centroid[0], centroid[1], -1)
positions_df.to_csv(today_positions_path)
@cmd_callback
@run_on_executor
def handle_extrinsic(
self,
date,
latitude,
longitude,
altitude,
residual_threshold,
save):
"""Handle extrinsic calibration"""
#
# Update the calibration data.
#
try:
self.loadCameraCalibration(
capture_date=datetime.strptime(date, "%Y_%m_%d")
)
except:
logging.warn(
"Failed loading calibration for extrinsic date {}\n{}".format(
date, traceback.format_exc())
)
#
# Load sun measurements.
#
today_positions_path = os.path.join(
gs.SUN_POSITIONS_PATH, "{}.csv".format(date))
if not os.path.exists(today_positions_path):
raise Exception('No sun positions for date: {}'.format(date))
#
# Calibration is done using the sun position.
#
positions_df = pd.read_csv(today_positions_path, index_col=0, parse_dates=True)