Skip to content

Commit 7e3abf3

Browse files
committed
switch print to propper logging
1 parent 3a90386 commit 7e3abf3

File tree

6 files changed

+56
-38
lines changed

6 files changed

+56
-38
lines changed

micasense/capture.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@
4444
import micasense.imageutils as imageutils
4545
import micasense.plotutils as plotutils
4646

47+
logger = logging.getLogger(__name__)
48+
4749

4850
class Capture(object):
4951
"""
@@ -814,7 +816,7 @@ def SIFT_align_capture(self, ref=5, min_matches=10, verbose=0, err_red=10.0, err
814816
keypoints_ref = descriptor_extractor.keypoints
815817
descriptor_ref = descriptor_extractor.descriptors
816818
if verbose > 1:
817-
print('found {:d} keypoints in the reference image'.format(len(keypoints_ref)))
819+
logger.info('found %d keypoints in the reference image', len(keypoints_ref))
818820
match_images = []
819821
ratio = []
820822
filter_tr = []
@@ -844,8 +846,7 @@ def SIFT_align_capture(self, ref=5, min_matches=10, verbose=0, err_red=10.0, err
844846
descriptors.append(descriptor_extractor.descriptors)
845847
if verbose > 1:
846848
for k, ix in zip(keypoints, img_index):
847-
print('found {:d} keypoints for band {:} '.format(len(k), self.images[ix].band_name))
848-
print(' in the remaining stack')
849+
logger.info('found %d keypoints for band %s in the remainig stack', len(k), self.images[ix].band_name)
849850

850851
matches = [match_descriptors(d, descriptor_ref, max_ratio=r)
851852
for d, r in zip(descriptors, ratio)]
@@ -865,7 +866,7 @@ def SIFT_align_capture(self, ref=5, min_matches=10, verbose=0, err_red=10.0, err
865866
keypoints[posBLUE], keypoints_ref, matches[posBLUE])
866867
# we trust this match to work
867868
if len(kpi) < min_matches:
868-
print('we have just {:d} matching keypoints -the match of BLUE camera to RED failed!!'.format(len(kpi)))
869+
logger.error('we have just {:d} matching keypoints -the match of BLUE camera to RED failed!!'.format(len(kpi))) # OWN
869870
# if it worked, scale it and get the transform
870871
scale_i = np.array(self.images[iBlueREF].raw().shape) / np.array(rest_shape)
871872
P = estimate_transform('projective', (scale * kpr)[:, ::-1], (scale_i * kpi)[:, ::-1])
@@ -889,7 +890,7 @@ def SIFT_align_capture(self, ref=5, min_matches=10, verbose=0, err_red=10.0, err
889890
scale_i,
890891
threshold=t)
891892
if verbose > 0:
892-
print('found {:d} matching keypoints for index {:d}'.format(len(filtered_match), ix))
893+
logger.info('found %d matching keypoints for index %d', len(filtered_match), ix)
893894
# if we have enough SIFT matches that actually correspond, compute a model
894895
if len(filtered_match) > min_matches:
895896
kpi, kpr, imatch, model = self.find_inliers(filtered_kpi,
@@ -904,15 +905,15 @@ def SIFT_align_capture(self, ref=5, min_matches=10, verbose=0, err_red=10.0, err
904905
else:
905906
P = ProjectiveTransform(matrix=warp_matrices_calibrated[ix])
906907
if verbose > 0:
907-
print('no match for index {:d}'.format(ix))
908+
logger.info('no match for index %d', ix)
908909
models.append(P)
909910
kp_image.append(kpi)
910911
kp_ref.append(kpr)
911912
img = self.images[ix].undistorted(self.images[ix].raw())
912913

913914
# no need for the upsampled stacks here
914915
if verbose > 0:
915-
print("Finished aligning band", ix)
916+
logger.info("Finished aligning band %d", ix)
916917

917918
self.__sift_aligned_capture = [np.eye(3)] * len(self.images)
918919
for ix, m in zip(img_index, models):

micasense/dls.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,11 @@
2323
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2424
"""
2525

26+
import logging
27+
2628
import numpy as np
2729

30+
logger = logging.getLogger(__name__)
2831
# for DLS correction, we need the sun position at the time the image was taken
2932
# this can be computed using the pysolar package (ver 0.6)
3033
# https://pypi.python.org/pypi/Pysolar/0.6
@@ -49,7 +52,7 @@
4952
havePysolar = True
5053
finally:
5154
if not havePysolar:
52-
print("Unable to import pysolar")
55+
logger.error("Unable to import pysolar")
5356

5457

5558
def fresnel(phi):

micasense/image.py

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828

2929
import math
3030
import os
31+
import logging
3132

3233
import cv2
3334
import numpy as np
@@ -36,6 +37,8 @@
3637
import micasense.metadata as metadata
3738
import micasense.plotutils as plotutils
3839

40+
logger = logging.getLogger(__name__)
41+
3942

4043
# helper function to convert euler angles to a rotation matrix
4144
def rotations_degrees_to_rotation_matrix(rotation_degrees):
@@ -46,15 +49,15 @@ def rotations_degrees_to_rotation_matrix(rotation_degrees):
4649
sy = np.sin(np.deg2rad(rotation_degrees[1]))
4750
sz = np.sin(np.deg2rad(rotation_degrees[2]))
4851

49-
Rx = np.mat([1, 0, 0,
50-
0, cx, -sx,
51-
0, sx, cx]).reshape(3, 3)
52-
Ry = np.mat([cy, 0, sy,
53-
0, 1, 0,
54-
-sy, 0, cy]).reshape(3, 3)
55-
Rz = np.mat([cz, -sz, 0,
56-
sz, cz, 0,
57-
0, 0, 1]).reshape(3, 3)
52+
Rx = np.asmatrix([1, 0, 0,
53+
0, cx, -sx,
54+
0, sx, cx]).reshape(3, 3)
55+
Ry = np.asmatrix([cy, 0, sy,
56+
0, 1, 0,
57+
-sy, 0, cy]).reshape(3, 3)
58+
Rz = np.asmatrix([cz, -sz, 0,
59+
sz, cz, 0,
60+
0, 0, 1]).reshape(3, 3)
5861
R = Rx * Ry * Rz
5962
return R
6063

@@ -68,7 +71,7 @@ class Image(object):
6871
def __init__(self, image_path: str, exiftool_obj=None, allow_uncalibrated=False):
6972
if not os.path.isfile(image_path):
7073
raise IOError("Provided path is not a file: {}".format(image_path))
71-
self.path = image_path
74+
self.path = str(image_path)
7275
self.meta = metadata.Metadata(self.path, exiftool_obj=exiftool_obj)
7376

7477
if self.meta.band_name() is None:
@@ -228,7 +231,7 @@ def raw(self):
228231
except ImportError:
229232
self.__raw_image = cv2.imread(self.path, -1)
230233
except IOError:
231-
print(("Could not open image at path {}".format(self.path)))
234+
logger.error("Could not open image at path %s", self.path)
232235
raise
233236
return self.__raw_image
234237

micasense/imageutils.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
import multiprocessing
2727
import os
28+
import logging
2829

2930
import cv2
3031
import exiftool
@@ -35,6 +36,8 @@
3536
from skimage.transform import warp
3637
from skimage.util import img_as_ubyte
3738

39+
logger = logging.getLogger(__name__)
40+
3841

3942
# start helper functions for finding a "hole"-free rectangle
4043
def get_longest_sequence(b):
@@ -206,7 +209,7 @@ def align(pair):
206209
nol = pair['pyramid_levels']
207210

208211
if pair['debug']:
209-
print(("number of pyramid levels: {}".format(nol)))
212+
logger.info("number of pyramid levels: %s", nol)
210213

211214
warp_matrix[0][2] /= (2 ** nol)
212215
warp_matrix[1][2] /= (2 ** nol)
@@ -244,7 +247,7 @@ def align(pair):
244247
plotutils.plotwithcolorbar(gray2_pyr[level], "match level {}".format(level))
245248
plotutils.plotwithcolorbar(grad1, "ref grad level {}".format(level))
246249
plotutils.plotwithcolorbar(grad2, "match grad level {}".format(level))
247-
print(("Starting warp for level {} is:\n {}".format(level, warp_matrix)))
250+
logger.info(("Starting warp for level %s is:\n %s", level, warp_matrix)
248251

249252
try:
250253
cc, warp_matrix = cv2.findTransformECC(grad1, grad2, warp_matrix, warp_mode, criteria, inputMask=None,
@@ -253,7 +256,7 @@ def align(pair):
253256
cc, warp_matrix = cv2.findTransformECC(grad1, grad2, warp_matrix, warp_mode, criteria)
254257

255258
if show_debug_images:
256-
print(("Warp after alignment level {} is \n{}".format(level, warp_matrix)))
259+
logger.info("Warp after alignment level %s is \n%s", level, warp_matrix)
257260

258261
if level != nol: # scale up only the offset by a factor of 2 for the next (larger image) pyramid level
259262
if warp_mode == cv2.MOTION_HOMOGRAPHY:
@@ -326,15 +329,15 @@ def align_capture(capture, ref_index=None, warp_mode=cv2.MOTION_HOMOGRAPHY, max_
326329
pool = multiprocessing.Pool(processes=multiprocessing.cpu_count())
327330
for _, mat in enumerate(pool.imap_unordered(align, alignment_pairs)):
328331
warp_matrices[mat['match_index']] = mat['warp_matrix']
329-
print(("Finished aligning band {}".format(mat['match_index'])))
332+
logger.info("Finished aligning band %s", mat['match_index'])
330333
pool.close()
331334
pool.join()
332335
else:
333336
# Single-threaded alternative
334337
for pair in alignment_pairs:
335338
mat = align(pair)
336339
warp_matrices[mat['match_index']] = mat['warp_matrix']
337-
print(("Finished aligning band {}".format(mat['match_index'])))
340+
logger.info(("Finished aligning band %s", mat['match_index'])
338341

339342
if capture.images[-1].band_name == 'LWIR':
340343
img = capture.images[-1]
@@ -509,7 +512,7 @@ def min_max(pts):
509512

510513
def map_points(pts, image_size, warpMatrix, distortion_coeffs, camera_matrix, warp_mode=cv2.MOTION_HOMOGRAPHY):
511514
# extra dimension makes opencv happy
512-
pts = np.array([pts], dtype=float)
515+
pts = np.array([pts], dtype=np.float)
513516
new_cam_mat, _ = cv2.getOptimalNewCameraMatrix(camera_matrix, distortion_coeffs, image_size, 1)
514517
new_pts = cv2.undistortPoints(pts, camera_matrix, distortion_coeffs, P=new_cam_mat)
515518
if warp_mode == cv2.MOTION_AFFINE:
@@ -588,7 +591,7 @@ def radiometric_pan_sharpen(capture, warp_matrices=None, panchro_band=5, irradia
588591
# for comparison
589592
# use the warp matrices we have for the stack, if not user supplied
590593
if warp_matrices is None:
591-
print("No SIFT warp matrices provided.")
594+
logger.warning("No SIFT warp matrices provided.")
592595
warp_matrices = capture.get_warp_matrices(ref_index=panchro_band)
593596
h, w = capture.images[panchro_band].raw().shape
594597
if irradiance_list is None:
@@ -688,6 +691,8 @@ def write_exif_to_stack(thecapture=None, thefilename=None, existing_exif_list=No
688691
raise Exception(
689692
"Please provide an existing capture object and filename or a list of existing exif data for batch processing")
690693
exif_bytes_list = []
694+
logger.debug("EXIF_DATA %s", exif_data)
695+
691696
for exif in exif_data:
692697
for key, val in exif.items():
693698
if key != 'Capture ID' and key != 'Filename':

micasense/metadata.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,13 @@
2828
import math
2929
import os
3030
from datetime import datetime, timedelta
31+
import logging
3132

3233
import exiftool
3334
import pytz
3435

36+
logger = logging.getLogger(__name__)
37+
3538

3639
class Metadata(object):
3740
""" Container for Micasense image metadata"""
@@ -74,10 +77,10 @@ def get_item(self, item, index=None):
7477
except KeyError:
7578
pass
7679
except IndexError:
77-
print("Item {0} is length {1}, index {2} is outside this range.".format(
80+
logger.error("Item %s is length %s, index %s is outside this range.",
7881
item,
79-
len(self.exif[item]),
80-
index))
82+
len(self.exif[0][item]),
83+
index)
8184
return val
8285

8386
def size(self, item):
@@ -98,7 +101,7 @@ def size(self, item):
98101

99102
def print_all(self):
100103
for item in self.get_all():
101-
print("{}: {}".format(item, self.get_item(item)))
104+
logger.info("%s: %s", item, self.get_item(item))
102105

103106
def dls_present(self):
104107
return self.get_item("XMP:Irradiance") is not None \

micasense/panel.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,19 +25,22 @@
2525

2626
import math
2727
import re
28+
import logging
2829

2930
import cv2
3031
import matplotlib.pyplot as plt
3132
import numpy as np
3233
import pyzbar.pyzbar as pyzbar
3334
from skimage import measure
3435

36+
logger = logging.getLogger(__name__)
37+
3538

3639
class Panel(object):
3740

3841
def __init__(self, img, panel_corners=None, ignore_autocalibration=False):
3942
# if we have panel images with QR metadata, panel detection is not called,
40-
# so this can be forced here
43+
# so this can be forced here
4144
if img is None:
4245
raise IOError("Must provide an image")
4346

@@ -124,7 +127,7 @@ def reflectance_from_panel_serial(self):
124127
return None
125128

126129
def get_panel_type(self):
127-
print(self.__panel_type)
130+
logger.info(self.__panel_type)
128131

129132
def qr_corners(self):
130133
if self.__panel_type == 'auto':
@@ -146,13 +149,13 @@ def panel_detected(self):
146149
return self.qr_bounds is not None
147150

148151
def panel_corners(self):
149-
""" get the corners of a panel region based on the qr code location
152+
""" get the corners of a panel region based on the qr code location
150153
Our algorithm to do this uses a 'reference' qr code location, and
151154
it's associate panel region. We find the affine transform
152155
between the reference qr and our qr, and apply that same transform to the
153156
reference panel region to find our panel region. Because of a limitation
154-
of the pyzbar library, the rotation of the absolute QR code isn't known,
155-
so we then try all 4 rotations and test against a cost function which is the
157+
of the pyzbar library, the rotation of the absolute QR code isn't known,
158+
so we then try all 4 rotations and test against a cost function which is the
156159
minimum of the standard deviation divided by the mean value for the panel region"""
157160
if self.__panel_bounds is not None:
158161
return self.__panel_bounds
@@ -164,7 +167,7 @@ def panel_corners(self):
164167
if self.panel_version < 3:
165168
# use the actual panel measures here - we use units of [mm]
166169
# the panel is 154.4 x 152.4 mm , vs. the 84 x 84 mm for the QR code
167-
# it is left 143.20 mm from the QR code
170+
# it is left 143.20 mm from the QR code
168171
# use the inner 50% square of the panel
169172
s = 76.2
170173
p = 42
@@ -177,7 +180,7 @@ def panel_corners(self):
177180
elif self.panel_version >= 6:
178181
# use the actual panel measures here - we use units of [mm]
179182
# the panel is 100 x 100 mm , vs. the 91 x 91 mm for the QR code
180-
# it is down 125.94 mm from the QR code
183+
# it is down 125.94 mm from the QR code
181184
# use the inner 50% square of the panel
182185
p = 41
183186
s = 50
@@ -271,7 +274,7 @@ def radiance(self):
271274
def reflectance_mean(self):
272275
reflectance_image = self.image.reflectance()
273276
if reflectance_image is None:
274-
print(
277+
logger.info(
275278
"First calculate the reflectance image by providing a\n band specific irradiance to the calling "
276279
"image.reflectance(irradiance)")
277280
mean, _, _, _ = self.region_stats(reflectance_image,

0 commit comments

Comments
 (0)