-
Notifications
You must be signed in to change notification settings - Fork 0
/
libmpMuelMat.py
1929 lines (1594 loc) · 73.7 KB
/
libmpMuelMat.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
import os # system library
import numpy as np # for any numeric processing
import ctypes # for interfacing with C-like data-types (pointers) used in the shared library
import time # for computational performance
import matplotlib # for plotting variables & results
import matplotlib.pyplot as plt
import scipy.io # for matlab datasets
from datetime import datetime
__version__ = "1.0"
def credits():
'''
# Function to display the credits of libmpMuelMat library.
'''
print('-----------------------------------------------------------------------------')
print(' libmpMuelMat: Open Library for Polarimetric Mueller Matrix Image Processing')
print(' ')
print(' version: 1.0 ')
print(' requirements: Python 3.5+ -- https://www.python.org/downloads/ ')
print(' GCC 9.4 or later -- https://gcc.gnu.org/ ')
print(' openMP for parallel computing -- https://www.openmp.org/ ')
print(' ')
print(' readme and instructions: ./ReadMe.txt -- please follow installation steps')
print(' testing openMP: libmpMuelMat.test_OpenMP()')
print(' ')
print(' project: HORAO - Inselspital, Bern, CH -- 2022')
print(' developer: Dr. Stefano Moriconi ([email protected])')
print('-----------------------------------------------------------------------------')
def list_Dependencies():
'''# Function to List all current dependencies of the libmpMuelMat library
#
# Please update any incorrect dependency prior to using the library. '''
print(' ')
print(' libmpMuelMat ', __version__, '-- list of dependencies:')
print(' ')
try:
print(' * numpy (', np.__version__, ')')
except:
print(' * numpy ( NOT FOUND )')
try:
print(' * ctypes (', ctypes.__version__, ')')
except:
print(' * ctypes ( NOT FOUND )')
try:
print(' * matplotlib (', matplotlib.__version__, ')')
except:
print(' * matplotlib ( NOT FOUND )')
try:
print(' * scipy (', scipy.__version__, ')')
except:
print(' * scipy ( NOT FOUND )')
print(' ')
print(' C-libs shared library path:')
if _chkFilePath(_get_CLib_path()):
print(_get_CLib_path(), '-- FOUND')
else:
print(_get_CLib_path(), '-- NOT FOUND')
print(' ')
print(' Matlab (.mat) testing data path:')
if _chkFilePath(_get_testDataMAT_path()):
print(_get_testDataMAT_path(), ' -- FOUND')
else:
print(_get_testDataMAT_path(), ' -- NOT FOUND')
print(' ')
print(' ')
print(' -- Please update any incorrect dependency prior to using the library.')
print(' ')
def _get_CLib_path():
'''
# Function to retrieve the global (or local) path to the Compiled C Shared Library
'''
Clibs_pth = "./C-libs/libmpMuelMat.so" # << Change the Global (or Local) path here if necessary!
# Clibs_pth = "./C-libs/libmpMuelMat.dll" # << Uncomment and Change here for Windows OS
return Clibs_pth
def _loadClib():
'''
# Function to retrieve the callable handle to the Compiled C Shared Library
'''
try:
Clib = ctypes.cdll.LoadLibrary(_get_CLib_path())
except:
Clib = None
print(
" <!> libmpMuelMat: Cannot Load Shared Library! -- Please check dependencies with: libmpMuelMat.list_Dependencies()")
return Clib
def _get_testDataMAT_path():
'''
# Function to retrieve the global (or local) path to test Data (MATLAB data format '.mat')
'''
testDataMAT_pth = './TestData/MAT/libmpMuelMat_TestData.mat' # << Change here the path to the testing/validation data
return testDataMAT_pth
def _get_test_calib_path(): # TO BE REMOVED
'''
# Private Function to retrieve the testing calibration folder path
'''
test_calib_path = './TestData/Raw/Calibration/' # << Change here the path to the test calibration folder
return test_calib_path
def _get_test_scan_path():
'''
# Private Function to retrieve the testing Raw Intensities folder path
'''
test_scan_path = './TestData/Raw/Scan/' # << Change here the path to the test scan folder
return test_scan_path
def _chkFilePath(filePath):
'''
# Private Function to check existence of a file in the computer
'''
return os.path.exists(filePath) & os.path.isfile(filePath)
def _chkFolderPath(folderPath):
'''
# Private Function to check the existence of a folder in the computer
'''
return os.path.exists(folderPath) & os.path.isdir(folderPath)
def default_CamType(CamID=None):
'''# Define the Default Camera Type used in the Polarimetric Acquisitions
# Default: 'Stingray IPM2'
#
# Call: CamType = default_CamType([CamID])
#
# *Inputs*
# [CamID]: optional scalar integer identifying the Camera device as listed below
#
# *Outputs*
# CamType: string with the camera device identifier
#
# Possible Options for different input CamID:
#
# CamID CamType
# 0 -> 'Stingray IPM2' (default)
# 1 -> 'Prosilica'
# 2 -> 'JAI'
# 3 -> 'JAI Packing 2x2'
# 4 -> 'JAI Binning'
# 5 -> 'Stingray'
# 6 -> 'Stingray IPM1'
#
# -1 -> 'TEST' -- used for (Unit)Testing
'''
CamType = None
if (CamID == None):
CamID = 0
if (CamID == -1):
CamType = 'TEST'
if (CamID == 0):
CamType = 'Stingray IPM2'
if (CamID == 1):
CamType = 'Prosilica'
if (CamID == 2):
CamType = 'JAI'
if (CamID == 3):
CamType = 'JAI Packing 2x2'
if (CamID == 4):
CamType = 'JAI Binning'
if (CamID == 5):
CamType = 'Stingray'
if (CamID == 6):
CamType = 'Stingray IPM1'
if (int(CamID) < -1 | int(CamID) > 6):
CamType = 'Stingray IPM2' # Default
return CamType
def get_Cam_Params(CamType):
'''# Function to retrieve the polarimetric Camera Parameters
# Several camera types are listed below
#
# Call: (ImgShape2D,GammaDynamic) = get_Cam_Params(CamType)
#
# *Inputs*
# CamType: string identifying the camera type (see: default_CamType()).
#
# * Outputs *
# ImgShape2D: list containing the camera pixel-wise size as [dim[0],dim[1]]
# GammaDynamic: scalar intensity as maximum value for detecting saturation/reflection'''
ImgShape2D = None
GammaDynamic = None
if (CamType == 'Prosilica'):
GammaDynamic = 16384
ImgShape2D = [600, 800]
if (CamType == 'JAI'):
GammaDynamic = 16384
ImgShape2D = [768, 1024]
if (CamType == 'JAI Packing 2x2'):
GammaDynamic = 16384
ImgShape2D = [384, 512]
if (CamType == 'JAI Binning'):
GammaDynamic = 16384
ImgShape2D = [384, 1024]
if (CamType == 'Stingray'):
GammaDynamic = 65530
ImgShape2D = [600, 800]
if (CamType == 'Stingray IPM1'):
GammaDynamic = 65530
ImgShape2D = [388, 516]
if (CamType == 'Stingray IPM2'):
GammaDynamic = 65530
ImgShape2D = [388, 516]
if (CamType == 'TEST'):
GammaDynamic = 65530
ImgShape2D = [128, 128]
return ImgShape2D, GammaDynamic
def get_testDataMAT():
'''# Function to retrieve variables from the MATLAB test Data
# The loaded variables are:
# A,W: polarisation states matrices obtained from calibration to compute the Mueller Matrix
# I: intensities (background noise is subtracted) to compute the Mueller Matrix
# IN: raw intensities
#
# NB: as the variables are natively from a MATLAB environment (fortran ordering),
# the data is re-ordered in a C-like fashion in line with subsequent processing.
#
# Variables are returned in the following order: A,I,W,IN'''
mat = scipy.io.loadmat(_get_testDataMAT_path())
A = mat.get('A')
I = mat.get('INTENSITE')
W = mat.get('W')
IN = mat.get('IN')
if np.isfortran(A):
A = A.ravel(order='C').reshape(A.shape)
if np.isfortran(I):
I = I.ravel(order='C').reshape(I.shape)
if np.isfortran(W):
W = W.ravel(order='C').reshape(W.shape)
if np.isfortran(IN):
IN = IN.ravel(order='C').reshape(IN.shape)
return A, I, W, IN
def _get_validDataMAT():
'''
# Provate Function to retrieve validation variables from the MATLAB test Data
# The loaded variables are considered as Reference in the validation and are the following:
#
# Call: validDataMAT = _get_validDataMAT()
#
# validDataMAT: dictionary containing the following keys:
#
# 'nM': (normalised) Mueller Matrix
# 'M11': normalising Mueller Matrix Component M(1,1)
#
# 'Mdetmsk': mask of the pixels with negative M determinant
# 'Mphymsk': mask of the pixels satisfying the physical criterion
# 'Isatmsk': mask of the pixels with saturated intensities (e.g. reflections)
# 'Msk': final mask of the valid pixels obtained as logical AND of the above ones
#
# 'Els': Real part of the Mueller Matrix EigenValues (unsorted)
# 'Elsmsk': mask of the negative EigenValues per lambda (sorted)
#
# 'MD': polarimetric matrix of diattenuation
# 'MR': polarimetric matrix of phase shift (retardance)
# 'Mdelta': polarimetric matrix of depolarisation
#
# 'totD': total diattenuation
# 'linD': linear diattenuation
# 'cirD': circular diattenuation
# 'oriD': orientation of linear diattenuation
#
# 'totR': total phase shift (retardance)
# 'linR': linear phase shift (retardance)
# 'cirR': circular phase shift (retardance)
# 'oriR': orientation of linear phase shift (retardance)
# 'oriRfull': full orientation of linear phase shift (retardance)
#
# 'totP': total depolarisation
#
# Variables are returned in the order above.
'''
mat = scipy.io.loadmat(_get_testDataMAT_path())
validDataMAT = {'nM': mat.get('MM'),
'M11': mat.get('M11'),
'Mdetmsk': mat.get('mask_det_neg'),
'Mphymsk': mat.get('mask_physical_criterion'),
'Isatmsk': mat.get('mask_saturation'),
'Msk': mat.get('mask_final'),
'Els': mat.get('Image_eigenvalues_coherency'),
'MD': mat.get('Image_MD'),
'MR': mat.get('Image_MR'),
'Mdelta': mat.get('Image_Mdelta'),
'totD': mat.get('Image_total_diattenuation'),
'linD': mat.get('Image_linear_diattenuation'),
'cirD': mat.get('Image_circular_diattenuation'),
'oriD': mat.get('Image_orientation_linear_diattenuation'),
'totR': mat.get('Image_total_retardance'),
'linR': mat.get('Image_linear_retardance'),
'cirR': mat.get('Image_circular_retardance'),
'oriR': mat.get('Image_orientation_linear_retardance'),
'oriRfull': mat.get('Image_orientation_linear_retardance_full'),
'totP': mat.get('Image_total_depolarization')}
return validDataMAT
def read_cod_data_X3D(input_cod_Filename, CamType=None, isRawFlag=0, VerboseFlag=0):
'''# Function to read (load) stacked 3D data from the camera acquisition or other exported dataset in '.cod' binary format.
# The data can be calibration data, intensity data (and background noise), or processed data with the libmpMuelMat library.
#
# Call: X3D = read_cod_data_X3D( input_cod_Filename, [CamType] , [isRawFlag] , [VerboseFlag] )
#
# *Inputs*
# input_cod_Filename: string with Global (or local) path to the '.cod' file to import.
#
# [CamType]: optional string with the Camera Device Name used during the acquisition (see: default_CamType())
#
# [isRawFlag]: scalar boolean (0,1) as flag for Raw data (e.g. raw intensities and calibration data) -- default: 0
# if 1 -> '.cod' interpreted *with Header* and *Fortran-like ordering*
# if 0 -> '.cod' interpreted *without Header* and native *C-like ordering*
#
# [VerboseFlag]: optional scalar boolean (0,1) as flag for displaying performance (computational time)
# (default: 0)
#
# * Outputs *
# X3D: 3D stack of Polarimetric Components of shape shp3 = [dim[0],dim[1],16].
# NB: the dimensions dim[0] and dim[1] are given by the camera parameters from CamType.
'''
if (CamType == None):
CamType = default_CamType() # << default
shp2 = get_Cam_Params(CamType)[0]
## Initial Time (Total Performance)
t = time.time()
header_size = 140 # header size of the '.cod' file
m = 16 # components of the polarimetric data in the '.cod' file
# Reading the Data (loading) NB: binary data is float, but the output array is *cast* to double
with open(input_cod_Filename, "rb") as f:
X3D = np.fromfile(f, dtype=np.single).astype(np.double)
f.close()
if isRawFlag:
# Calibration files WITH HEADER (to be discarded)
# Reshaping and transposing the shape of the imported array (from Fortran- -> C-like)
X3D = np.moveaxis(X3D[header_size:].reshape([shp2[1], shp2[0], m]), 0, 1)
else:
# Other Files from libmpMuelMat processing WITHOUT HEADER
# Reshaping the imported array (already C-like)
X3D = X3D.reshape([shp2[0], shp2[1], m])
## Final Time (Total Performance)
telaps = time.time() - t
if VerboseFlag:
print(' ')
print(' >> read_cod_data_X3D Performance: Elapsed time = {:.3f} s'.format(telaps))
return X3D
def write_cod_data_X3D(X3D, output_cod_Filename, VerboseFlag=1):
'''# Function to write (export) stacked 3D data from the camera acquisitions or further processing in '.cod' binary format.
# The data can be both calibration data (A,W), or processed intensities(I), or processed 3D data (MM), etc.
#
# Call: write_cod_data_X3D( X3D, output_cod_Filename, [VerboseFlag] )
#
# *Inputs*
# X3D: 3D stack of images, e.g. calibration states (A,W), processed intensities, polarimetric components ...
# X3D is expected to be of shape shp3 = [dim[0],dim[1],16].
#
# output_cod_Filename: string with Global (or local) path to export the data in binary format with '.cod' extension.
#
# [VerboseFlag]: optional scalar boolean (0,1) as flag for displaying performance (computational time)
# (default: 1)
#
# NB: The output data array will be written in C-like ordering.
'''
shp3 = X3D.shape
if (np.prod(np.shape(shp3)) != 3):
raise Exception(
'Input: "X3D" should have shape of a 3D image, e.g. (idx0, idx1, idx2). The shape value was found: {}'.format(
shp3))
if (shp3[-1] != 16):
raise Exception(
'Input: "X3D" should have shape 16 components in the last dimension. The number of elements in the last dimension is: {}'.format(
shp3[-1]))
with open(output_cod_Filename, "wb") as f:
X3D.astype(np.single).tofile(f)
f.close()
if VerboseFlag:
print(' ')
print(' >> Exported X3D .cod file as:', output_cod_Filename)
return None
def read_cod_data_X2D(input_cod_Filename, CamType=None, VerboseFlag=0):
'''# Function to read (load) 2D data from exported dataset in '.cod' binary format.
# The 2D data is a component of processed data using the libmpMuelMat library.
#
# Call: X2D = read_cod_data_X2D( input_cod_Filename, [CamType] , [VerboseFlag] )
#
# *Inputs*
# input_cod_Filename: string with Global (or local) path to the '.cod' file to import.
#
# [CamType]: optional string with the Camera Device Name used during the acquisition (see: default_CamType())
#
# [VerboseFlag]: optional scalar boolean (0,1) as flag for displaying performance (computational time)
# (default: 0)
#
# * Outputs *
# X2D: 2D Component (e.g. a polarimetric feature) processed with libmpMuelMat of shape shp2 = [dim[0],dim[1]].
# NB: the dimensions dim[0] and dim[1] are given by the camera parameters.
'''
if (CamType == None):
CamType = default_CamType() # << default
shp2 = get_Cam_Params(CamType)[0]
## Initial Time (Total Performance)
t = time.time()
# Reading the Data (loading) NB: binary data is float, but the output array is *cast* to double
with open(input_cod_Filename, "rb") as f:
X2D = np.fromfile(f, dtype=np.single).astype(np.double)
f.close()
# Reshaping the imported array (already C-like)
X2D = X2D.reshape(shp2)
## Final Time (Total Performance)
telaps = time.time() - t
if VerboseFlag:
print(' ')
print(' >> read_cod_data_X2D Performance: Elapsed time = {:.3f} s'.format(telaps))
return X2D
def write_cod_data_X2D(X2D, output_cod_Filename, VerboseFlag=1):
'''# Function to write (export) 2D data from the camera acquisitions or further processing in '.cod' binary format.
# The data is usually a 2D Component of a Polarimetric feature processed with libmpMuelMat library.
#
# Call: write_cod_data_X2D( X2D, output_cod_Filename, [VerboseFlag] )
#
# *Inputs*
# X2D: 2D Component (e.g. a polarimetric feature) processed with libmpMuelMat of shape shp2 = [dim[0],dim[1]].
#
# output_cod_Filename: string with Global (or local) path to export the data in binary format with '.cod' extension.
#
# [VerboseFlag]: optional scalar boolean (0,1) as flag for displaying performance (computational time)
# (default: 1)
#
# NB: The output data array will be written in C-like ordering.
'''
shp2 = X2D.shape
if (np.prod(np.shape(shp2)) != 2):
raise Exception(
'Input: "X2D" should have shape of a 2D image, e.g. (idx0, idx1). The shape value was found: {}'.format(
shp2))
with open(output_cod_Filename, "wb") as f:
X2D.astype(np.single).tofile(f)
f.close()
if VerboseFlag:
print(' ')
print(' >> Exported X2D .cod file as:', output_cod_Filename)
return None
def _gen_AIW_rnd(shp2=None):
'''# Function to generate random A, I, and W, as in Mueller Matrix computation M = AIW.
#
# Call: (A,I,W) = gen_AIW_rnd( shp2 )
#
# *Inputs*
# shp2: shape of the 2D A, I, and W images as (dim0, dim1)
# NB: is shp2 is not provided, a default shape is retrieved, based on default camera type.
#
# *Outputs*
# A: 3D arrays of shape [shp2[0],shp2[1],16] with random values.
#
# I: 3D arrays of shape [shp2[0],shp2[1],16] with random values.
#
# W: 3D arrays of shape [shp2[0],shp2[1],16] with random values.
#
# The output values follow a canonical normal distribution (mean=0,std=1).
#
#
# Note:
# In later stages, this function may embed a generative functionality based on Diffusion Networks
# to synthesise new samples of Intensities (as well as polarisation states A,W) from random noise.'''
if (shp2 == None):
shp2 = get_Cam_Params(default_CamType())[0]
# Checking Inputs
if np.prod(np.shape(shp2)) != 2:
raise Exception(
'Input: "shp2" should be the shape of a 2D image, e.g. (idx0, idx1). The value of "shp2" was: {}'.format(
shp2))
if ~ np.all(np.isfinite(shp2), axis=-1):
raise Exception('Input: "shp2" should contain all FINITE elements. The value of "shp2" was: {}'.format(shp2))
if ~ np.all(shp2 == np.array(shp2, np.int32)):
shp2 = np.array(shp2, np.int32)
print(" -- Warning: Input argument (shp2) has non-integer elements - Default: round to closest integers.")
if ~ np.all(np.greater(shp2, 0)):
raise Exception('Input: "shp2" has non-positive number of elements. The value of "shp2" is: {}'.format(shp2))
# Determining outputs
A = np.random.randn(shp2[0], shp2[1], 16)
I = np.random.randn(shp2[0], shp2[1], 16)
W = np.random.randn(shp2[0], shp2[1], 16)
return A, I, W
def gen_AW(shp2=None, wlen=550):
'''#Function to generate synthetic polarisation state/acquisition matrices A,W of arbitrary shape.
# The polarisation matrices A,W can be used to compute the Mueller Matrix decomposition,
# given an input set of intensities I.
#
# Call: (A,W) = gen_AW([shp2],[wlen])
#
# *Inputs*
# shp2: shape of the 2D A, I, and W images as (dim0, dim1)
# NB: is shp2 is not provided, a default shape is retrieved, based on default camera type.
#
# wlen: integer scalar for the polarimetric wavelength in nm [default: 550]
# supported wavelengths: [550, 650]
#
# *Outputs*
#
# A,W: 3D arrays of shape [shp2[0],shp2[1],16] with values from previous calibrations.
# NB: the values are statistical estimations, and should be used in synthetic set-up only,
# in order to simulate an artificial calibration of the system.
#
# NB: only 2 wavelength are currently supported: 550nm (default) and 650nm
# other input wavelengths will produce randomly distributed (Gaussian) matrices as output.
'''
if (shp2 == None):
shp2 = get_Cam_Params(default_CamType())[0]
else:
if np.prod(np.shape(shp2)) != 2:
raise Exception(
'Input: "shp2" should be the shape of a 2D image, e.g. (idx0, idx1). The value of "shp2" was: {}'.format(
shp2))
if ~ np.all(np.isfinite(shp2), axis=-1):
raise Exception(
'Input: "shp2" should contain all FINITE elements. The value of "shp2" was: {}'.format(shp2))
if ~ np.all(shp2 == np.array(shp2, np.int32)):
shp2 = np.array(shp2, np.int32)
print(" -- Warning: Input argument (shp2) has non-integer elements - Default: round to closest integers.")
if ~ np.all(np.greater(shp2, 0)):
raise Exception(
'Input: "shp2" has non-positive number of elements. The value of "shp2" is: {}'.format(shp2))
if (wlen == None):
wlen = 550
shp3 = [shp2[0], shp2[1], 1]
if wlen == 550: # 550nm case
Aavg = np.reshape([1.0, 1.0067, 1.0063, 1.0103,
-0.7548, 0.5901, 0.0144, -0.1166,
0.6439, -0.5866, 0.2537, -0.7111,
0.1301, 0.5103, -0.9442, -0.6459], [1, 1, 16])
Asd0 = np.reshape([0.0, 0.0023, 0.0008, 0.0037,
0.0029, 0.0034, 0.0038, 0.0066,
0.0118, 0.0104, 0.0112, 0.0072,
0.0039, 0.0075, 0.0030, 0.0040], [1, 1, 16])
Asd1 = np.reshape([0.0, 0.1616, 0.1144, 0.1749,
0.3796, 0.7578, 0.3512, 0.4703,
0.9391, 0.6024, 0.6473, 0.6591,
0.6314, 0.4556, 0.5217, 0.3556], [1, 1, 16]) * 1e-3
Wavg = np.reshape([1.0, 0.4459, -0.3686, 0.0157,
0.9764, -0.2924, 0.3592, 0.3089,
0.9910, -0.1115, -0.1771, -0.4991,
0.9927, 0.1199, 0.4264, -0.3359], [1, 1, 16])
Wsd0 = np.reshape([0.0, 0.0153, 0.0189, 0.0054,
0.0045, 0.0161, 0.0110, 0.0144,
0.0018, 0.0073, 0.0085, 0.0218,
0.0044, 0.0032, 0.0203, 0.0116], [1, 1, 16])
Wsd1 = np.reshape([0.0, 0.5660, 0.4860, 0.2746,
0.2612, 0.3685, 0.4690, 0.3205,
0.1963, 0.4282, 0.4011, 0.4667,
0.3608, 0.2955, 0.6957, 0.3378], [1, 1, 16]) * 1e-3
A = np.tile(Aavg, shp3) + \
np.tile(Asd0 * np.random.randn(1, 1, 16), shp3) + \
np.tile(Asd1, shp3) * np.random.randn(shp3[0], shp3[1], shp3[2])
W = np.tile(Wavg, shp3) + \
np.tile(Wsd0 * np.random.randn(1, 1, 16), shp3) + \
np.tile(Wsd1, shp3) * np.random.randn(shp3[0], shp3[1], shp3[2])
elif wlen == 650: # 650nm case
Aavg = np.reshape([1.0, 1.0043, 1.0109, 0.9891,
-0.8740, 0.4763, -0.1336, -0.1286,
0.4076, -0.5499, 0.0573, -0.9903,
-0.0872, 0.7152, -0.9581, -0.2042], [1, 1, 16])
Asd0 = np.reshape([0.0, 0.0019, 0.0013, 0.0046,
0.0014, 0.0124, 0.0054, 0.0151,
0.0120, 0.0066, 0.0118, 0.0089,
0.0021, 0.0069, 0.0025, 0.0082], [1, 1, 16])
Asd1 = np.reshape([0.0, 0.0003, 0.0001, 0.0003,
0.0004, 0.0012, 0.0009, 0.0005,
0.0017, 0.0013, 0.0012, 0.0016,
0.0009, 0.0010, 0.0025, 0.0016], [1, 1, 16])
Wavg = np.reshape([1.0, 0.3281, -0.1997, -0.0830,
1.0085, -0.1275, 0.2055, 0.2813,
1.0031, -0.0071, -0.1106, -0.3519,
1.0254, 0.0806, 0.3605, -0.0691], [1, 1, 16])
Wsd0 = np.reshape([0.1, 0.0198, 0.0123, 0.0076,
0.0042, 0.0142, 0.0085, 0.0200,
0.0018, 0.0064, 0.0097, 0.0236,
0.0047, 0.0053, 0.0218, 0.0021], [1, 1, 16])
Wsd1 = np.reshape([0.0, 0.0008, 0.0006, 0.0003,
0.0006, 0.0003, 0.0009, 0.0009,
0.0002, 0.0010, 0.0010, 0.0007,
0.0009, 0.0004, 0.0010, 0.0002], [1, 1, 16])
A = np.tile(Aavg, shp3) + \
np.tile(Asd0 * np.random.randn(1, 1, 16), shp3) + \
np.tile(Asd1, shp3) * np.random.randn(shp3[0], shp3[1], shp3[2])
W = np.tile(Wavg, shp3) + \
np.tile(Wsd0 * np.random.randn(1, 1, 16), shp3) + \
np.tile(Wsd1, shp3) * np.random.randn(shp3[0], shp3[1], shp3[2])
else:
print(' <!> gen_AW: parsed wavelength is not supported: returning random as in "gen_AIW_rnd"')
A = np.random.randn(shp2[0], shp2[1], 16)
W = np.random.randn(shp2[0], shp2[1], 16)
return A, W
def map_msk2_to_idx(msk2):
'''# Function to determine the C-like linear indices, given a logical mask of a 2D image.
#
# Call: idx = map_msk2_to_idx( msk2 )
#
# *Inputs*
# msk2: boolean mask of a 2D image of shape (dim0, dim1)
#
# *Outputs*
# idx: C-like linear indices corresponding to the 'True' voxels in msk2
# e.g. if msk3 has shape (3,3) and the only true value is in the middle,
# i.e. msk2[1,1] = True, the idx array will be a scalar equal to 4.
# NB: indexing starts from 0
'''
# Checking Inputs
if np.prod(np.shape(np.shape(msk2))) != 2:
raise Exception(
'Input: "msk2" should have the shape of a 2D image, e.g. (idx0, idx1). The shape was: {}'.format(
np.shape(msk2)))
if msk2.dtype != bool:
raise Exception('Input: "msk2" should be logical, i.e. boolean type. The data type was: {}'.format(msk2.dtype))
idx = np.array(np.ravel_multi_index(np.nonzero(msk2), msk2.shape), dtype=np.int32)
return idx
def _mng_Idxs(idx, shp2):
'''
# Function to manage indexing of pixels array to be processed in the Mueller Matrix computing.
# This function is meant to harmonise indices values compatibly with a C-compiled shared library.
#
# Call: (idx,idx_ptr,numel,numel_ptr) = _mng_Idxs( idx,shp2 )
#
# *Inputs*
# idx: scalar value identically equal to -1 (negative one) *OR*
# 1D array containing unique C-like indices of selected pixel array locations within the 2D image [dim[0],dim[1]].
#
# shp2: shape of the 2D image: expected [dim[0],dim[1]]
#
# *Outputs*
# idx: updated 1D array containing unique C-like indices of
# *ALL* or *SELECTED* pixel locations within the 2D image.
# idx_ptr: C-like pointer to the 1D updated array of indices (idx)
# numel: scalar number of elements in the updated 1D array of indices (idx)
# numel_ptr: C-like pointer to the scalar number of elements (numel)
'''
# Checking Inputs
if np.prod(np.shape(shp2)) != 2:
raise Exception(
'Input: "shp2" should be the shape of a 2D image, e.g. (idx0, idx1). The value of "shp2" was: {}'.format(
shp2))
if ~ np.all(np.isfinite(shp2), axis=-1):
raise Exception('Input: "shp2" should contain all FINITE elements. The value of "shp2" was: {}'.format(shp2))
if ~ np.all(shp2 == np.array(shp2, np.int32)):
shp2 = np.array(shp2, np.int32)
print(" -- Warning: Input argument (shp2) has non-integer elements - Default: round to closest integers.")
if ~ np.all(np.greater(shp2, 0)):
raise Exception('Input: "shp2" has non-positive number of elements. The value of "shp2" is: {}'.format(shp2))
# Remove possible repetitions
idx = np.unique(np.array(idx))
if (np.prod(np.shape(idx)) == 1) & np.all(idx == -1):
# CASE: process *ALL* voxels in the 3D image
numel = np.array(np.prod(shp2), dtype=np.int32) # IMPORTANT: data type must be int32
numel_ptr = numel.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
idx = np.array(np.arange(0, numel), dtype=np.int32) # IMPORTANT: data type must be int32
idx_ptr = idx.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
else:
# CASE: process *SELECTED* voxels in the 3D image
# Checking that the selected voxel indices are within the 3D image shape range
if not (np.all(np.greater_equal(idx, 0)) & np.all(np.less(idx, np.prod(shp2)))):
raise Exception('The parsed indices (idx) are *OUT* of the 3D image. The parsed idx is: {}'.format(idx))
idx = np.array(idx, dtype=np.int32) # IMPORTANT: data type must be int32
idx_ptr = idx.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
numel = np.array(np.prod(idx.shape), dtype=np.int32) # IMPORTANT: data type must be int32
numel_ptr = numel.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
return idx, idx_ptr, numel, numel_ptr
def ini_MM(shp2):
'''# Function to initialise the Mueller Matrix Components used in the compiled Shared Library
# This function set the data type to double (i.e. np.double).
#
# Call: (M,M_ptr) = ini_MM( shp2 )
#
# *Inputs*
# shp2: shape of the 2D Mueller Matrix image as (dim0, dim1)
#
# *Outputs*
# M: Mueller Matrix of shape (shp2[0],shp2[1],16) initialised as zeros
# M_ptr: C-like pointer to the Matrix '''
# Checking Inputs
if np.prod(np.shape(shp2)) != 2:
raise Exception(
'Input: "shp2" should be the shape of a 2D image, e.g. (idx0, idx1). The value of "shp2" was: {}'.format(
shp2))
if ~ np.all(np.isfinite(shp2), axis=-1):
raise Exception('Input: "shp2" should contain all FINITE elements. The value of "shp2" was: {}'.format(shp2))
if ~ np.all(shp2 == np.array(shp2, np.int32)):
shp2 = np.array(shp2, np.int32)
print(" -- Warning: Input argument (shp2) has non-integer elements - Default: round to closest integers.")
if ~ np.all(np.greater(shp2, 0)):
raise Exception('Input: "shp2" has non-positive number of elements. The value of "shp2" is: {}'.format(shp2))
# Initialising Outputs
M = np.zeros([shp2[0], shp2[1], 16], dtype=np.double)
M_ptr = _ptr_X(M)
return M, M_ptr
def ini_Comp(shp2):
'''# Function to initialise a 2D Component (can be used in C compiled code with pointer)
# This function set the data type to double (i.e. np.double).
#
# Call: (X2D,X2D_ptr) = ini_Comp( shp2 )
#
# *Inputs*
# shp2: shape of the 2D image Component as (dim0, dim1)
#
# *Outputs*
# X2D: 2D Image Component of shape (shp2[0],shp2[1]) initialised as zeros'''
X2D = np.zeros(shp2, dtype=np.double)
X2D_ptr = X2D.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
return X2D, X2D_ptr
def ini_msk2(shp2):
'''# Function to initialise the logical mask variable (can be used in the compiled Shared Library with the pointer)
# This function set the data type to boolean, and returns the associated pointer.
#
# Call: (msk2,msk2_ptr) = ini_msk2( shp2 )
#
# *Inputs*
# shp2: shape of the 2D image as (dim0, dim1)
#
# *Outputs*
# msk2: logical validity mask of 2D shape (shp2), initialised as 'True'
# msk2_ptr: pointer of the logical validity mask.'''
if np.prod(np.shape(shp2)) != 2:
raise Exception(
'Input: "shp2" should be the shape of a 2D image, e.g. (idx0, idx1). The value of "shp2" was: {}'.format(
shp2))
if ~ np.all(np.isfinite(shp2), axis=-1):
raise Exception('Input: "shp2" should contain all FINITE elements. The value of "shp2" was: {}'.format(shp2))
if ~ np.all(shp2 == np.array(shp2, np.int32)):
shp2 = np.array(shp2, np.int32)
print(" -- Warning: Input argument (shp2) has non-integer elements - Default: round to closest integers.")
if ~ np.all(np.greater(shp2, 0)):
raise Exception('Input: "shp2" has non-positive number of elements. The value of "shp2" is: {}'.format(shp2))
msk2 = np.ones(shp2, dtype=np.bool_)
msk2_ptr = msk2.ctypes.data_as(ctypes.POINTER(ctypes.c_bool))
return msk2, msk2_ptr
def ini_REls(shp2):
'''# Function to initialise the REAL EigenVALUES of the Mueller Matrix for the compiled Shared Library
# This function set the data type to double (i.e. np.double).
#
# Call: (REls,REls_ptr) = ini_REls( shp2 )
#
# *Inputs*
# shp2: shape of the 2D Mueller Matrix REAL EigenValue Component as (dim0, dim1)
#
# *Outputs*
# REls: REAL EigenVALUES of the Mueller Matrix of shape (shp2[0],shp2[1],4) initialised as zeros
# REls_ptr: C-like pointer to the variable'''
# Checking Inputs
if np.prod(np.shape(shp2)) != 2:
raise Exception(
'Input: "shp2" should be the shape of a 2D image, e.g. (idx0, idx1). The value of "shp2" was: {}'.format(
shp2))
if ~ np.all(np.isfinite(shp2), axis=-1):
raise Exception('Input: "shp2" should contain all FINITE elements. The value of "shp2" was: {}'.format(shp2))
if ~ np.all(shp2 == np.array(shp2, np.int32)):
shp2 = np.array(shp2, np.int32)
print(" -- Warning: Input argument (shp2) has non-integer elements - Default: round to closest integers.")
if ~ np.all(np.greater(shp2, 0)):
raise Exception('Input: "shp2" has non-positive number of elements. The value of "shp2" is: {}'.format(shp2))
# Initialising Outputs
REls = np.zeros([shp2[0], shp2[1], 4], dtype=np.double)
REls_ptr = _ptr_X(REls)
return REls, REls_ptr
def _ptr_X(X):
'''
# Private Function to determine the pointers to the Matrix Components variables used in the compiled Shared Library
#
# Call: X_ptr = _ptr_X( X )
#
# *Inputs*
# X: any numpy NDarray
#
# *Outputs*
# X_ptr: C-like pointer to the input X
'''
X_ptr = X.ctypes.data_as(ctypes.POINTER(ctypes.c_double))
return X_ptr
def compute_MM_AIW(A, I, W, idx=-1, VerboseFlag=0):
'''# Function to compute the Mueller Matrix from the equation M = AIW
#
# Call: (M,nM) = compute_MM_AIW_new( A , I , W , [idx] , [VerboseFlag] )
#
# *Inputs*
# A, I, W:
# stacked 3D arrays with 16 components in the last dimension.
# All A, I, amd W must have the same shape: shp3 = A.shape,
# corresponding to a 3D stack of 2D images in the form shp3 = [dim[0],dim[1],16].
#
# >> NB: all A,I,W should have a c-like ordering (not fortran-like ordering) for best performance!
#
# [idx]: optional 1-D array of C-like linear indices obtained from the function 'map_msk2_to_idx'
# if idx is a scalar equal to -1, *ALL* indices are considered (default),
# i.e. idx = np.array(np.arange(0,numel)), with numel = np.prod([dim[0],dim[1]])
#
# [VerboseFlag]: optional scalar boolean (0,1) as flag for displaying performance (computational time)
# (default: 0)
#
# * Outputs *
# M: 3D stack of Mueller Matrix Components of shape shp3.
# The matrix has the form [dim[0],dim[1],16].
#
# nM: 3D stack of normalised Mueller Matrix Components of shape shp3 = [dim[0],dim[1],16].
# Each Component is normalised by M(1,1) as default.
#
# *** This is a python wrapper for the shared library: libmpMuelMat.so ***
# *** The C-compiled shared library automatically enables and configures
# *** multi-core processing for maximal performance using OpenMP libraries.'''
# Loading Shared Library
mpMuelMatlibs = _loadClib()
## Initial Time (Total Performance)
t = time.time()
# Retrieving 3D image shape
shp3 = np.shape(A)
shp2 = [shp3[0], shp3[1]]
# Managing voxel indices and pointers
(idx, idx_ptr,
numel, numel_ptr) = _mng_Idxs(idx, shp2)
# Determining Input Pointers
A_ptr = _ptr_X(A.ravel(order='C'))
# Determining Input Pointers
I_ptr = _ptr_X(I.ravel(order='C'))
# Determining Input Pointers
W_ptr = _ptr_X(W.ravel(order='C'))
# Initialising M Output
(M, M_ptr) = ini_MM(shp2)
(nM, nM_ptr) = ini_MM(shp2)
# Calling the C-compiled function from the shared library
mpMuelMatlibs.mp_comp_MM_AIW(M_ptr, nM_ptr,
A_ptr, I_ptr, W_ptr,
idx_ptr, numel_ptr)
## Final Time (Total Performance)
telaps = time.time() - t
if VerboseFlag:
print(' ')
print(' >> compute_MM_AIW Performance: Elapsed time = {:.3f} s'.format(telaps))
return M, nM
def norm_MM(M):
'''# Function to normalise the Mueller Matrix coefficients by the first one (M11)
#
# Call: (nM,M11) = norm_MM( M )