-
Notifications
You must be signed in to change notification settings - Fork 0
/
BioMulti_L_NL_Model_Complex_Ongoing.py
executable file
·2284 lines (2053 loc) · 89.5 KB
/
BioMulti_L_NL_Model_Complex_Ongoing.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
#!usr/bin/env python3
# -*- coding: utf-8 -*-
'''
======================================================================
DigitialBrain Version 2.0
Copyright(c) 2020 Qiang Li
All Rights Reserved.
qiang.li@uv.es
Distributed under the (new) BSD License.
######################################################################
----------------------------------------------------------------------
Permission to use, copy, or modify this software and its documentation
for educational and research purposes only and without fee is here
granted, provided that this copyright notice and the original authors'
names appear on all copies and supporting documentation. This program
shall not be used, rewritten, or adapted as the basis of a commercial
software or hardware product without first obtaining permission of the
authors. The authors make no representations about the suitability of
this software for any purpose. It is provided "as is" without express
or implied warranty.
I would like to thank all of the open suorce contributors in the Python
open community, because open source make this script works.
The *.ipynb version also can get when you test code.
'''
# Dependent toolbox
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# pip3
#sudo pip3 install MotionClouds
#sudo pip3 install NeuroTools
#sudo pip3 install statsmodels==0.10.0rc2 --pre
#sudo pip3 install pyrtools
#sudo pip3 install PyWavelets
#sudo pip3 install colour-science
#sudo pip3 install colorama
# @caution: you need first run (InstallDependent.sh) for install necessary
# dependent toolbox
# Bash InstallDependent.sh
# Input the mudules and exter-packages
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import sys
sys.path.insert(0,'/home/qiang/QiangLi/Python_Utils_Functional/Retina-LGN-V1-ongoing/PyTorchSteerablePyramid')
#@caution: if you download via pip, you need to update some funciton:
#1). hand change scipy.msic to scipy.special otherwise you can not import out factorial function.
#2). add from imageio import imread in the utils script.
from steerable.SCFpyr_NumPy import SCFpyr_NumPy
import steerable.utils as utils
from google.colab.patches import cv2_imshow
from skimage.color import rgb2lab, lab2rgb, rgb2gray, xyz2lab, rgb2xyz, rgb2yuv, yuv2rgb, gray2rgb, xyz2rgb, rgb2hsv
import glob
from imageio import imread
import math
from skimage.transform import resize, rescale
import scipy
import scipy.misc
from PIL import Image
import matplotlib.pyplot as plt
import os
from mpl_toolkits.axes_grid1 import ImageGrid
import cv2
import numpy as np
from numpy.linalg import inv
import time
from matplotlib import transforms
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib import colors
from mpl_toolkits.mplot3d import Axes3D
from skimage.util import dtype
import torch
import torch.nn.functional as F
import PIL.Image as pim
import warnings
from skimage import data, img_as_float
from skimage import exposure
from scipy import linalg
import MotionClouds as mc
import pyrtools as pt
import pywt
import colour
from pywt._doc_utils import wavedec2_keys, draw_2d_wp_basis
from mpl_toolkits import axes_grid1
from tqdm import tqdm_notebook as tqdm
from tqdm import trange
from colorama import Fore
#%tensorflow_version 1x
import tensorflow as tf
warnings.filterwarnings('ignore')
#%matplotlib inline
plt.style.use('ggplot')
plt.matplotlib.rcParams['font.size'] = 6
#%load_ext autoreload
#%autoreload 2
#Sometimes, it will erros. Why? Go to check right postion use !ls
sys.path.insert(0, '/home/qiang/QiangLi/Python_Utils_Functional/Retina-LGN-V1-ongoing/SLIP/SLIP')
from SLIP import Image
#LogGabor can be install in the first time but when you second time install it,
#It will cause error. Here for how to fix it.
#!pip3 install --upgrade pip setuptools wheel
#!sudo apt-get install libpq-dev
sys.path.insert(0, '/home/qiang/QiangLi/Python_Utils_Functional/Retina-LGN-V1-ongoing/LogGabor/LogGabor')
from LogGabor import LogGabor
parameterfile = '/home/qiang/QiangLi/Python_Utils_Functional/Retina-LGN-V1-ongoing/LogGabor/default_param.py'
lg = LogGabor(parameterfile)
print('It works on 23 April2020')
#DWT wavelet filters
sys.path.insert(0, '/home/qiang/QiangLi/Python_Utils_Functional/Retina-LGN-V1-ongoing/')
from nt_toolbox.general import *
from nt_toolbox.signal import *
from nt_toolbox.compute_wavelet_filter import *
print('It works on 27 April2020')
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
'''
############################################################################
# Visual Computing
# Fourier Brain
############################################################################
# Human visual inspired multi-layer LNL model. In this model, the main
# component are:
#
# Nature Image --> VonKries Adaptation --> ATD (Color processing phase)
# Wavelets Transform --> Contrast sensivity function (CSF) --> Divisive
# Normalization(DN) --> Noise(Gaussian or Poisson)
#
# Evalute of model with TID2008 database.
#
# Redundancy redunction measure with Total Correlation(RBIG or Cortex module)
#
# This model derivated two version script: Matlab, Python. In the future, I
# want to implemented all of these code on C++ or Java. If our goal is
# simulate of primate brain, we need to implement all everything to High
# performance Computer(HPC) with big framework architecture(C/C++/Java).
'''
############################################################################
# Function
############################################################################
def prepare_colorarray(arr):
"""Check the shape of the array and convert it to
floating point representation.
"""
arr = np.asanyarray(arr)
if arr.ndim != 3 or arr.shape[2] != 3:
msg = "the input array must be have a shape == (.,.,3))"
raise ValueError(msg)
return dtype.img_as_float(arr)
#---------------------------------------------------------------
# Matrices that define conversion between different color spaces
# I will update more convert matrix at here.
#---------------------------------------------------------------
#rgb_to_xyz = np.array([[0.412453, 0.357580, 0.180423],
# [0.212671, 0.715160, 0.072169],
# [0.019334, 0.119193, 0.950227]])
#xyz_to_rgb = linalg.inv(rgb_to_xyz)
xyz_to_atd = np.array([[0.297, 0.72, -0.107],
[-0.449, 0.29, -0.077],
[0.086, -0.59, 0.501]])
atd_to_xyz = linalg.inv(xyz_to_atd)
atd_to_xyz_updated=np.array([[0.979, 1.189, 1.232],
[-1.535, 0.764, 1.163],
[0.445, 0.135, 2.079]])
srgb_to_iou=np.array([[0.2814, 0.6938, 0.0638],
[-0.0971, 0.1458, -0.0250],
[-0.0930, -0.2529, 0.4665]])
iou_to_srgb = linalg.inv(srgb_to_iou)
rgb_to_yuv=np.array([[0.299, 0.587, 0.114],
[-0.147, -0.288, 0.436],
[0.615, -0.515, -0.100]])
rgb_to_yiq=np.array([[0.299, 0.587, 0.114],
[0.596, -0.274, -0.322],
[0.211, -0.523, 0.312]])
#---------------------------------------------------------------
# Conversion between different color spaces
#---------------------------------------------------------------
def convert(matrix, arr):
"""Do the color space conversion.
Parameters
----------
matrix : array_like
The 3x3 matrix to use.
arr : array_like
The input array.
Returns
-------
out : ndarray, dtype=float
The converted array.
"""
arr = prepare_colorarray(arr)
arr = np.swapaxes(arr, 0, 2)
oldshape = arr.shape
arr = np.reshape(arr, (3, -1))
out = np.dot(matrix, arr)
out.shape = oldshape
out = np.swapaxes(out, 2, 0)
return np.ascontiguousarray(out)
def xyz2atd(xyz):
return convert(xyz_to_atd, xyz)
def atd2xyz(atd):
return convert(atd_to_xyz, atd)
def atd2xyz_updated(atd):
return convert(atd_to_xyz_updated, atd)
def linsrgb_to_srgb (linsrgb):
gamma = 1.055 * linsrgb**(1./2.4) - 0.055
scale = linsrgb * 12.92
return np.where (linsrgb > 0.0031308, gamma, scale)
def srgb2iou(srgb):
return convert(srgb_to_iou, srgb)
def iou2srgb(iou):
return convert(iou_to_srgb,iou)
def rgb2yuv_matrix(rgb):
return convert(rgb_to_yuv,rgb)
def rgb2yiq(rgb):
return convert(rgb_to_yiq, rgb)
#---------------------------------------------------------------
# Check max and min value in each channel
#---------------------------------------------------------------
def plot_MinMax(X, labels=["R", "G", "B"]):
print("-------------------------------")
for i, lab in enumerate(labels):
mi=np.min(X[:,:,i])*255
ma=np.max(X[:,:,i])*255
print("{} : MIN={:8.4f}, MAX={:8.4f}".format(lab,mi,ma))
#test=np.array(images[2])
#plot_MinMax(test, labels=["R","G","B"])
#---------------------------------------------------------------
# Visualization the ATD opponent channel with presudo color
#---------------------------------------------------------------
def visual_channel_iou(image_iou, dim):
"""
Opponent channel processing theory
PresudoColor visualization
The input array must be ATD color space
"""
z=np.zeros(image_iou.shape)
if dim != 0:
print(np.mean(image_iou[:,:,0]))
print(np.max(image_iou[:,:,0]))
print(np.min(image_iou[:,:,0]))
z[:,:,0]= np.min(image_iou[:,:,0])
z[:,:,dim] = image_iou[:,:,dim]
z = iou2srgb(z)
z = (255*np.clip(z,0,1)).astype('uint8')
return(z)
#---------------------------------------------------------------
# Implemented Weber's and Fechner's law
#---------------------------------------------------------------
def waber(lumin, lambdaValue):
"""
Weber's law nspired by Physhilogy experiment.
"""
# lambdaValue normally select 0.6
w = lumin**lambdaValue
#w = (255*np.clip(w,0,1)).astype('uint8')
return(w)
#---------------------------------------------------------------
# Implemented Entropy
#---------------------------------------------------------------
def entropy(img):
"""
Calculate the entropy of image
"""
hist, _ = np.histogram(img)
hist = hist[hist > 0]
return -np.log2(hist / hist.sum()).sum()
def show_entropy(band_name, img):
"""
Plot the entropy of image
"""
bits = entropy(img)
per_pixel = bits / img.size
print(f"{band_name:3s} entropy = {bits:7.2f} bits, {per_pixel:7.6f} per pixel")
def image_entropy(img):
"""
Calculate the entropy of an image-update funciton
"""
histogram, _ = np.histogram(img)
histogram_length = sum(histogram)
samples_probability = [float(h) / histogram_length for h in histogram]
return -sum([p * math.log(p, 2) for p in samples_probability if p != 0])
def print_entropy(band_name, img):
"""
plot the entropy of image with each band name
"""
bits = image_entropy(img)
#per_pixel = bits / img.size
print(f"{band_name:3s} entropy = {bits:7.2f} bits")
#---------------------------------------------------------------
# Implemented mutual_information
#---------------------------------------------------------------
def mutual_information(hgram):
"""
Mutual information for joint histogram
"""
# Convert bins counts to probability values
pxy = hgram / float(np.sum(hgram))
px = np.sum(pxy, axis=1) # marginal for x over y
py = np.sum(pxy, axis=0) # marginal for y over x
px_py = px[:, None] * py[None, :] # Broadcast to multiply marginals
# Now we can do the calculation using the pxy, px_py 2D arrays
nzs = pxy > 0 # Only non-zero pxy values contribute to the sum
return np.sum(pxy[nzs] * np.log(pxy[nzs] / px_py[nzs]))
#---------------------------------------------------------------
# Implemented resized_img function
#---------------------------------------------------------------
def resized_img(img):
'''
Resized function for image size with (256, 256)
'''
image_resized = resize(img, (256, 256, 3), anti_aliasing=True)
return image_resized
#---------------------------------------------------------------
# Implemented visualization image histogram with 3D function
#---------------------------------------------------------------
def histogram3dplot(h, e, fig=None):
'''
Visualization 3D histogram of image.
'''
M, N, O = h.shape
idxR = np.arange(M)
idxG = np.arange(N)
idxB = np.arange(O)
R, G, B = np.meshgrid(idxR, idxG, idxB)
a = np.diff(e[0])[0]
b = a/2
R = a * R + b
a = np.diff(e[1])[0]
b = a/2
G = a * G + b
a = np.diff(e[2])[0]
b = a/2
B = a * B + b
colors = np.vstack((R.flatten(), G.flatten(), B.flatten())).T/255
h = h / np.sum(h)
if fig is not None:
f = plt.figure(fig)
else:
f = plt.gcf()
ax = f.add_subplot(111, projection='3d')
mxbins = np.array([M,N,O]).max()
ax.scatter(R.flatten(), G.flatten(), B.flatten(), s=h.flatten()*(256/mxbins)**3/2, c=colors)
#ax.set_xlabel('Red')
#ax.set_ylabel('Green')
#ax.set_zlabel('Blue')
#---------------------------------------------------------------
# Calculate correlation coffecient value for image split channel
#---------------------------------------------------------------
def show_coeff(band_name, img_ch, img_chs):
'''
Plot the correlation coefficient between two color channel
'''
coeff=np.corrcoef(img_ch.ravel(), img_chs.ravel())[0, 1]
print(f"{band_name:3s} coeff = {coeff:.2f} coeff")
#---------------------------------------------------------------
# Visualization Lab colorspace with presudo-color
#---------------------------------------------------------------
def extract_single_dim_from_LAB_convert_to_RGB(image,dim):
'''
Visualization presudo color in the LAB color space.
'''
z = np.zeros(image.shape)
if dim != 0:
z[:,:,0]=30 ## I need brightness to plot the image along 1st or 2nd axis
z[:,:,dim] = image[:,:,dim]
z = lab2rgb(z)
return(z)
#---------------------------------------------------------------
# Calculate MSE between raw image and reference image
#---------------------------------------------------------------
def mse(reference, query):
'''
Calculate the mse between origin image and query image
'''
(ref, que) = (reference.astype('double'), query.astype('double'))
diff = ref - que
square = (diff ** 2)
mean = square.mean()
return mean
#---------------------------------------------------------------
# Calculate PSNR between raw image and reference image
#---------------------------------------------------------------
def psnr(reference, query, normal=255):
'''
Calculate the PSNR of original image and query image.
'''
normalization = float(normal)
msev = mse(reference, query)
if msev != 0:
value = 10.0 * np.log10(normalization * normalization / msev)
else:
value = float("inf")
return value
def show_psnr(band_name, reference, query):
'''
plot psnr of reference image and query image
'''
psnr_ = psnr(reference, query, normal=255)
print(f"{band_name:3s} psnr_ = {psnr_:.2f} psnr_")
#---------------------------------------------------------------
# Convert RGB image to gray
#---------------------------------------------------------------
def convert_gray(im_rgb):
'''
Convert image gray scale, image of shape (None,None,3)
'''
R=im_rgb[:,:,0]
G=im_rgb[:,:,1]
B=im_rgb[:,:,2]
L = R*299/1000 + G*587/1000+B*114/1000
return(L)
def convert_to_luminance(x):
'''
Convert color image into luminacne
'''
return np.dot(x[..., :3], [0.299, 0.587, 0.144]).astype('double')
#---------------------------------------------------------------
# Implemented CSF, you can adjust fourier space size and frequency
#---------------------------------------------------------------
def make_CSF(x, nfreq):
'''
Contrast Sensitivity Function implemented with Delay version.
The CSF measures the sensitivity of human visual system to the various frequencies of visual stimuli,
Here we apply an adjusted CSF model given by:
The mathmatic equation of CSF located in my CortexComputing notebook(Random section)
Input:
x - Define size of domain, float
nfreq - Fourier frequency, float
Output:
CSF - Fourier Space of CSF, 2darray
'''
#w=0.7
#up_bound=7.8909
#down_bound= 0.9809
#a=2.6
#b=0.0192
#c=0.114
#e=1.1
params=[0.7, 7.8909, 0.9809, 2.6, 0.0192, 0.114, 1.1]
N_x=nfreq
N_x_=np.linspace(0, N_x, x+1)-nfreq/2
N_x_up=N_x_[:-1]
[xplane,yplane]=np.meshgrid(N_x_up, N_x_up)
plane=(xplane+1j*yplane)
radfreq=np.abs(plane)
s=(1-params[0])/2*np.cos(4*np.angle(plane))+(1+params[0])/2
radfreq=radfreq/s
print(radfreq.shape)
csf = params[3]*(params[4]+params[5]*radfreq)*np.exp(-(params[5]*radfreq)**params[6])
f = radfreq < params[1]
csf[f] = params[2]
return csf
#---------------------------------------------------------------
# Implemented Gabor function with control contrast, luminacne
# velocity, orienttion and sigma of Gaussian function.
#---------------------------------------------------------------
def Gabor(size, L0, c, f, theta, sigma, center=None):
""" Make a Gabor functional with control parameters.
:Input:
-size: array, float
-L0: luminance, float
-c: contrast, float
-theta: orientation, float
-sigma: fwhm of gaussian, float
-center: center coordinate of spatial map, float
:output:
-Gabor
"""
x=np.arange(0, size, 1, float)
y = x[:,np.newaxis]
if center is None:
x=y=int(size//2)
else:
x=center[0]
y=center[1]
[x,y]=np.meshgrid(range(-x,x),range(-y,y))
L=L0*(1.0+c*np.sin(2*np.pi*f*(x*np.cos(theta)+y*np.sin(theta))) * np.exp(-(x**2+y**2)/2*sigma**2))
return L
#---------------------------------------------------------------
# Global contrast normalization
#---------------------------------------------------------------
def global_contrast_normalization(X, s, lmda, epsilon):
'''
Global contrast normalization
'''
for i in range(len(X)):
X_average = np.mean(X[i])
print('Mean: ', X_average)
x = X[i] - X_average
# `su` is here the mean, instead of the sum
contrast = np.sqrt(lmda + np.mean(x**2))
x = s * x / max(contrast, epsilon)
#global_contrast_normalization(images, 1, 10, 0.000000001)
#---------------------------------------------------------------
# Implemented gaussian filter
#---------------------------------------------------------------
def gaussian_filter(kernel_shape):
'''
Gaussian filter
'''
x = np.zeros(kernel_shape, dtype='float32')
def gauss(x, y, sigma=2.0):
Z = 2 * np.pi * sigma ** 2
return 1. / Z * np.exp(-(x ** 2 + y ** 2) / (2. * sigma ** 2))
mid = np.floor(kernel_shape[-1] / 2.)
for kernel_idx in range(0, kernel_shape[1]):
for i in range(0, kernel_shape[2]):
for j in range(0, kernel_shape[3]):
x[0, kernel_idx, i, j] = gauss(i - mid, j - mid)
return x / np.sum(x)
#---------------------------------------------------------------
# Local mean and local divisive
# local contrast normalization for increase feature
# which inspired by Divisive Normalization
#---------------------------------------------------------------
def DivisiveNormalization(image,radius=9):
"""
image: torch.Tensor , .shape => (1,channels,height,width)
radius: Gaussian filter size (int), odd
"""
if radius%2 == 0:
radius += 1
def get_gaussian_filter(kernel_shape):
x = np.zeros(kernel_shape, dtype='float64')
def gauss(x, y, sigma=2.0):
Z = 2 * np.pi * sigma ** 2
return 1. / Z * np.exp(-(x ** 2 + y ** 2) / (2. * sigma ** 2))
mid = np.floor(kernel_shape[-1] / 2.)
for kernel_idx in range(0, kernel_shape[1]):
for i in range(0, kernel_shape[2]):
for j in range(0, kernel_shape[3]):
x[0, kernel_idx, i, j] = gauss(i - mid, j - mid)
return x / np.sum(x)
n,c,h,w = image.shape[0],image.shape[1],image.shape[2],image.shape[3]
gaussian_filter = torch.Tensor(get_gaussian_filter((1,c,radius,radius)))
filtered_out = F.conv2d(image,gaussian_filter,padding=radius-1)
mid = int(np.floor(gaussian_filter.shape[2] / 2.))
### Subtractive Normalization
centered_image = image - filtered_out[:,:,mid:-mid,mid:-mid]
## Variance Calc
sum_sqr_image = F.conv2d(centered_image.pow(2),gaussian_filter,padding=radius-1)
s_deviation = sum_sqr_image[:,:,mid:-mid,mid:-mid].sqrt()
per_img_mean = s_deviation.mean()
## Divisive Normalization
divisor = np.maximum(per_img_mean.numpy(),s_deviation.numpy())
divisor = np.maximum(divisor, 1e-4)
new_image = centered_image / torch.Tensor(divisor)
return new_image
#---------------------------------------------------------------
# Plot image and hist
#---------------------------------------------------------------
def plot_img_and_hist(image, axes, bins=256):
"""
The script modifies from skimage.
Plot an image along with its histogram and cumulative histogram.
"""
image = img_as_float(image)
ax_img, ax_hist = axes
ax_cdf = ax_hist.twinx()
# Display image
ax_img.imshow(image, cmap=plt.cm.gray)
ax_img.set_axis_off()
# Display histogram
ax_hist.hist(image.ravel(), bins=bins, histtype='step', color='black')
ax_hist.ticklabel_format(axis='y', style='scientific', scilimits=(0, 0))
ax_hist.set_xlabel('Pixel intensity')
ax_hist.set_xlim(0, 1)
ax_hist.set_yticks([])
# Display cumulative distribution
img_cdf, bins = exposure.cumulative_distribution(image, bins)
ax_cdf.plot(bins, img_cdf, 'r')
ax_cdf.set_yticks([])
return ax_img, ax_hist, ax_cdf
#---------------------------------------------------------------
# Adjust Gamma
#---------------------------------------------------------------
def adjust_gamma(image, gamma=0.8):
# The nonlinearlity convert between human visual and display screen
invGamma = 1.0 / gamma
table = np.array([((i / 255.0) ** invGamma) * 255 for i in np.arange(0, 256)]).astype("uint8")
return cv2.LUT(image, table)
#---------------------------------------------------------------
# Visualization wavelet transform coefficient with verious scale
#---------------------------------------------------------------
def plot_wavelet_ql(fW, Jmin=0):
"""
plot_wavelet - plot wavelets coefficients.
U = plot_wavelet(fW, Jmin):
"""
def rescaleWav(A):
v = abs(A).max()
B = A.copy()
if v > 0:
B = .5 + .5 * A / v
return B
n = fW[0,0].shape[1]
Jmax = int(np.log2(n)) - 1
U = fW[0,0].copy()
for j in np.arange(Jmax, Jmin - 1, -1):
U[:2 ** j:, 2 ** j:2 **
(j + 1):] = rescaleWav(U[:2 ** j:, 2 ** j:2 ** (j + 1):])
U[2 ** j:2 ** (j + 1):, :2 **
j:] = rescaleWav(U[2 ** j:2 ** (j + 1):, :2 ** j:])
U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):] = (
rescaleWav(U[2 ** j:2 ** (j + 1):, 2 ** j:2 ** (j + 1):]))
U[:2 ** j:, :2 ** j:] = nt.rescale(U[:2 ** j:, :2 ** j:])
imageplot(U)
for j in np.arange(Jmax, Jmin - 1, -1):
plt.plot([0, 2 ** (j + 1)], [2 ** j, 2 ** j], 'r')
plt.plot([2 ** j, 2 ** j], [0, 2 ** (j + 1)], 'r')
plt.plot([0, n], [0, 0], 'r')
plt.plot([0, n], [n, n], 'r')
plt.plot([0, 0], [0, n], 'r')
plt.plot([n, n], [0, n], 'r')
return U
#---------------------------------------------------------------
# Wavelet transform coefficient with Daubechies filter
# Visualization coefficients
#---------------------------------------------------------------
def wavelet_transform(I, Jmin=1, h = compute_wavelet_filter("Daubechies",6)) :
"""
2D-Wavelet decomposition, using Mallat's algorithm.
By default, the convolution filters are those proposed by
Ingrid Daubechies in her landmark 1988-1992 papers.
"""
wI = perform_wavortho_transf(I, Jmin, + 1, h)
return wI
def iwavelet_transform(wI, Jmin=1, h = compute_wavelet_filter("Daubechies",6)) :
"""
Invert the Wavelet decomposition by rolling up the operations above.
"""
I = perform_wavortho_transf(wI, Jmin, - 1, h)
return I
def display(im):
"""
Displays an image using the methods of the 'matplotlib' library.
"""
plt.figure(figsize=(8,8))
plt.imshow( im, cmap="gray", vmin=0, vmax=1)
plt.axis("off")
#---------------------------------------------------------------
# Wavelet threshold coefficient with Daubechies filter
# Visualization coefficients
#---------------------------------------------------------------
def Wavelet_threshold(wI, threshold) :
"""
Re-implement a thresholding routine and create a copy of the Wavelet transform
Remove all the small coefficients then Invert the new transform
"""
wI_thresh = wI.copy()
wI_thresh[ abs(wI) < threshold ] = 0
I_thresh = iwavelet_transform(wI_thresh)
return I_thresh
def thresh_hard(u,t):
'Hard threshold for Ortho-wavelets'
return u*(np.abs(u)>t)
def thresh_soft(u,t):
'Soft threshold for Ortho-wavelets'
return np.maximum(1-t/np.abs(u), 0)*u
#---------------------------------------------------------------
# Visualization sp3_filter coefficients
#--------------------------------------------------------------
def make_grid_coeff_ql(coeff, normalize=True):
'''
Visualization function for building a large image that contains the
low-pass, high-pass and all intermediate levels in the steerable pyramid.
For the complex intermediate bands, the real part is visualized.
Args:
coeff (list): complex pyramid stored as list containing all levels
normalize (bool, optional): Defaults to True. Whether to normalize each band
Returns:
np.ndarray: large image that contains grid of all bands and orientations
'''
M, N = coeff[0,1].shape
Norients = pyr.num_scales
#out = np.zeros((M * 2 - coeff[3, 3].shape[0], Norients * N))
out=np.zeros((258,514))
currentx, currenty = 0, 0
for i in range(1, pyr.num_scales):
for j in range(4):
tmp = coeff[i,j].real
m, n = tmp.shape
if normalize:
tmp = 255 * tmp/tmp.max()
tmp[m-1,:] = 255
tmp[:,n-1] = 255
out[currentx:currentx+m,currenty:currenty+n] = tmp
currenty += n
currentx += coeff[i, 0].shape[0]
currenty = 0
a, b = coeff[3,3].shape
out[currentx: currentx+a, currenty: currenty+b] = 255 * coeff[3,3]/coeff[3,3].max()
out[0,:] = 255
out[:,0] = 255
return out.astype(np.uint8)
#---------------------------------------------------------------
# Visualization entropy 2D map
#--------------------------------------------------------------
def entropy_2d(signal):
'''
function returns entropy of a signal
signal must be a 1-D numpy array
'''
lensig=signal.size
symset=list(set(signal))
numsym=len(symset)
propab=[np.size(signal[signal==i])/(1.0*lensig) for i in symset]
ent=np.sum([p*np.log2(1.0/p) for p in propab])
return ent
#---------------------------------------------------------------
# Add colorbar with right size
#--------------------------------------------------------------
def add_colorbar(im, aspect=20, pad_fraction=0.5, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca()
cax = divider.append_axes("right", size=width, pad=pad)
plt.sca(current_ax)
return im.axes.figure.colorbar(im, cax=cax, **kwargs)
#---------------------------------------------------------------
# View image and Fourier space in the same time and
# Plot the centerl response
#--------------------------------------------------------------
def viewimage(img):
'''
In the current figure window, show the image and its
central rows and columns (round((end+1)/2)), as well
as its amplitude spectrum and its central rows and columns.
Input: 2d array (img)
Output: 2d array (img and correspond its Fourier space)
'''
img2 = 20*np.log10(np.fft.fftshift(np.abs(np.fft.fft2(img))))
plt.figure(figsize=(10, 10))
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)
plt.subplot(2,3,1)
plt.imshow(img, cmap='gray'), plt.axis('off'), plt.title('image')
plt.subplot(2,3,2)
plt.plot(img[np.int64((img.shape[0]+1)/2) ,:], 'r.-' )
plt.axis('off')
plt.title('central row of image')
plt.subplot(2,3,3)
plt.plot(img[:, np.int64((img.shape[0]+1)/2)], 'r.-')
plt.axis('off')
plt.title('central column of image')
plt.subplot(2,3,4)
plt.imshow(img2, cmap='gray')
plt.axis('off')
plt.title('magnitude spectrum')
plt.subplot(2,3,5)
plt.plot(img2[:, np.int64((img2.shape[0]+1)/2)], 'b.-')
plt.axis('off')
plt.title('central row of magnitude spectrum')
plt.subplot(2,3,6)
plt.plot(img2[np.int64((img2.shape[0]+1)/2), :], 'b.-')
plt.axis('off')
plt.title('central column of magnitude spectrum')
plt.tight_layout()
plt.show()
#---------------------------------------------------------------
# Saturation is an element-wise exponential function.
#--------------------------------------------------------------
def saturation_f(x,g,xm,epsilon,sizeT):
'''
SATURATION_F is an element-wise exponential function (saturation).
It is good to (1) model the saturation in Wilson-Cowan recurrent networks,
and (2) as a crude (fixed) approximation to the luminance-brightness transform.
This saturation is normalized and modified to have these two good properties:
(a) Some specific input, xm (e.g. the median, the average) maps into itself: xm = f(xm).
f(x) = sign(x)*K*|x|^g , where the constant K=xm^(1-g)
(b) Plain exponential is modified close to the origin to avoid the singularity of
the derivative of saturating exponentials at zero.
This problem is solved by imposing a parabolic behavior below a certain
threshold (epsilon) and imposing the continuity of the parabola and its
first derivative at epsilon.
f(x) = sign(x)*K*|x|^g for |x| > epsilon
sign(x)*(a*|x|+b*|x|^2) for |x| <= epsilon
with:
a = (2-g)*K*epsilon^(g-1)
b = (g-1)*K*epsilon^(g-2)
The derivative is (of course) signal dependent:
df/dx = g*K*|x|^(g-1) for |x| > epsilon [bigger with xm and decreases with signal]
a + 2*b*|x| for |x| <= epsilon [bigger with xm and decreases with signal (note that b<0)]
In the end, the slope at the origin depends on the constant xm (bigger for bigger xm).
The program gives the function and the derivative. For the inverse see INV_SATURATION_F.M
For vector/matrix inputs x, the vector/matrix with anchor points, xm, has to be the same size as x.
USE: [f,dfdx] = saturation_f(x,gamma,xm,epsilon);
x = n*m matrix with the values
gamma = exponent (scalar)
xm = n*m matrix with the anchor values (in wavelet representations typically anchors will be different for different subbands)
epsilon = threshold (scalar). It can also be a matrix the same size as x (again different epsilons per subband, e.g. epsilon = 1e-3*x_average)
'''
K = tf.pow(xm, tf.scalar_mul(1 - g, tf.ones([sizeT,1])))
K = tf.where(tf.math.is_nan(K), tf.zeros_like(K), K)
a = (2 - g) * K*(epsilon**(g - 1))
a = tf.where(tf.math.is_nan(a), tf.zeros_like(a), a)
b = (g-1) * K*(epsilon**(g - 2))
b = tf.where(tf.math.is_nan(b), tf.zeros_like(b), b)
pG = tf.math.greater(x, tf.ones([sizeT,1]) * epsilon)
pG_zeros = tf.count_nonzero(pG)
pp1 = tf.math.less_equal(x, tf.ones([sizeT,1]) * epsilon)
pp2 = tf.math.greater_equal(x, tf.zeros([sizeT,1]))
pp1_zeros = tf.count_nonzero(pp1)
pp2_zeros = tf.count_nonzero(pp2)
nG = tf.math.less(x, -tf.ones([sizeT,1]) * epsilon)
np1 = tf.math.greater(x, -tf.ones([sizeT,1]) * epsilon)
np2 = tf.math.less_equal(x, tf.zeros([sizeT,1]))
nG_zeros = tf.count_nonzero(nG)
np1_zeros = tf.count_nonzero(np1)
np2_zeros = tf.count_nonzero(np2)
f = x
def f1(): return tf.where(pG, K*tf.pow(x, (g * tf.ones([sizeT,1]))), f)
def f2(): return f
f1 = tf.cond(tf.math.greater(pG_zeros, 0), f1, f2)
def f3(): return tf.where(nG, -K*tf.pow(tf.abs(x), (g * tf.ones([sizeT,1]))), f1)
def f4(): return f1
f2 = tf.cond(tf.math.greater(nG_zeros, 0), f3, f4)
def f5(): return tf.where(tf.math.logical_and(pp1,pp2), a * tf.abs(x) + b *tf.pow(x, 2 * tf.ones([sizeT,1])), f2)
def f6(): return f2
f3 = tf.cond(tf.math.greater(pp1_zeros + pp2_zeros, 1), f5, f6)
def f7(): return tf.where(tf.math.logical_and(np1,np2), -(a * tf.abs(x) + b * tf.pow(x, 2 * tf.ones([sizeT,1]))), f3)
def f8(): return f3
f4 = tf.cond(tf.math.greater(np1_zeros + np2_zeros, 1), f7, f8)
return f4
############################################################################
# Main section
############################################################################
if __name__ is '__main__':
############################################################################
#Setting parameters
############################################################################
wavelets_types=['SCFpyr_NumPy_SteerbalePyramid', 'LogGabor', 'sp3_filters', 'Daubechies', 'DWT']
wavelets_type=wavelets_types[3]
noise_types=['Gaussian', 'Possion']
noise_type=noise_types[1]
threshold=False
adaptation_gain_control=False
statis_wavlets=True
saturation =False
dim = (256, 256)
g_sa = 0.5
epsilon_sa = 0.1
k_sa = 1
deltat_sa = 1e-5
g_sa = np.array(g_sa).astype('float32')
epsilon_sa = np.array(epsilon_sa).astype('float32')
############################################################################
#Load image and preprocess
############################################################################
image=cv2.imread('drive/My Drive/PyTorchSteerablePyramid/assets/lena.jpg', cv2.IMREAD_UNCHANGED)
print('Original Dimensions : ',image.shape)
im= cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
print('Resized Dimensions : ',im.shape)
im=im/255
b,g,r = cv2.split(im)
rgb_img = cv2.merge([r,g,b])
plt.figure(figsize=(4,5))
plt.imshow(rgb_img)
plt.axis('off')
plt.title("Orignal")
plt.tight_layout()
plt.show()
print('########################')
print('Step 1')
print('Load img test passed!!!')
print('########################')
#---------------------------------------------------------------
# Gamma correction with monit and eye nonlinearlity
#---------------------------------------------------------------
im_gamma=exposure.adjust_gamma(im, gamma=0.6)
b,g,r = cv2.split(im_gamma)
img_gamma_rgb = cv2.merge([r,g,b])
plt.figure(figsize=(4,5))
plt.imshow(img_gamma_rgb)
plt.axis("off")
plt.tight_layout()
plt.title("GammaCorrection")
plt.show()
print('########################')
print('Step 2')
print('Gammma correction test passed!!!')
print('########################')
#---------------------------------------------------------------
# VonKries adaptation
#---------------------------------------------------------------
if adaptation_gain_control==True:
M = np.asarray([[.40024,0.7076,-.08081], [-.2263,1.16532,0.0457],[0,0,.91822]])
int_M = inv(M)