-
Notifications
You must be signed in to change notification settings - Fork 1
/
sas_tools.py
183 lines (152 loc) · 6.24 KB
/
sas_tools.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
import numpy as np
import scipy.stats
import ritsar.signal as sig
from PIL import Image
#--------------------------------------------------------------------------------------
# Adapted from the autoFocus2 function originally written by Douglas Macdonald
# as part of the RITSAR Python package located at https://github.com/dm6718/RITSAR and
# https://github.com/dm6718/RITSAR/blob/master/ritsar/imgTools.py.
#
# We modified the phase gradient estimate to use the ML estimate from:
# Jakowatz, Charles V., and Daniel E. Wahl. "Eigenvector method for maximum-likelihood
# estimation of phase errors in synthetic-aperture-radar imagery."
# JOSA A 10.12 (1993): 2539-2546.
#
# Flag for shadow PGA from:
# Prater, et al. J Prater, D Bryner, and S Synnes. "SHADOW BASED PHASE GRADIENT
# AUTOFOCUS FOR SYNTHETIC APERTURE SONAR." 5th annual Institute of Acoustics
# SAS/SAR Conference. Lerici, Italy. 2023.
#
# Assumes SLC azimuth is vertical dimension and range increases left to right
# along the horizontal dimension.
#
# "np" is the numpy package.
# "sig" is the signal package from RITSAR.
#--------------------------------------------------------------------------------------
def pga(img, win = 'auto', win_params = [100, 0.5], shadow_pga = False):
#Derive parameters
npulses = int(img.shape[0])
nsamples = int(img.shape[1])
#Initialize loop variables
img_af = 1.0*img
max_iter = 30
af_ph = 0
rms = []
#Compute phase error and apply correction
for iii in range(max_iter):
#Find brightest azimuth sample in each range bin
if shadow_pga:
index = np.argsort(np.abs(img_af), axis=0)[0]
else:
index = np.argsort(np.abs(img_af), axis=0)[-1]
#Circularly shift image so max values line up
f = np.zeros(img.shape)+0j
for i in range(nsamples):
f[:,i] = np.roll(img_af[:,i], int(npulses/2-index[i]))
if win == 'auto':
#Compute window width
s = np.sum(f*np.conj(f), axis = -1)
s = 10*np.log10(s/s.max())
# For first iteration, use all azimuth data
if iii == 0:
width = npulses
# For second iteration, use half azimuth data
elif iii == 1:
width = npulses // 2
#For all other iterations, use twice the 10 dB threshold
else:
width = np.sum(s>-10)
window = np.arange(npulses/2-width/2,npulses/2+width/2)
else:
#Compute window width using win_params if win not set to 'auto'
width = int(win_params[0]*win_params[1]**iii)
window = np.arange(npulses/2-width/2,npulses/2+width/2)
if width<5:
break
window = window.astype('int')
#Window image
g = np.zeros(img.shape)+0j
g[window] = f[window]
#Fourier Transform
G = sig.ift(g, ax=0)
# ML method
phi_dot = np.angle(np.sum(np.conj(G[:-1, :]) * G[1:, :], axis=1))
phi = np.concatenate([[0], np.cumsum(phi_dot)])
phi = np.unwrap(phi)
#Remove linear trend
t = np.arange(0,nsamples)
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(t,phi)
line = slope*t + intercept
phi = phi - line
if shadow_pga:
phi = -phi
rms.append(np.sqrt(np.mean(phi**2)))
if win == 'auto':
if rms[iii]<0.01:
break
#Apply correction
phi2 = np.tile(np.array([phi]).T,(1,nsamples))
IMG_af = sig.ift(img_af, ax=0)
IMG_af = IMG_af*np.exp(-1j*phi2)
img_af = sig.ft(IMG_af, ax=0)
#Store phase
af_ph += phi
print('number of iterations: {}'.format(iii+1))
return(img_af, np.flip(af_ph), rms)
#-----------------------------------------------------------------------------------------------------------------------------------------------------
# C Schlick Rational Tone Mapping Operator
# targetBrightness is 0,1.
def schlick(L, targetBrightness = 0.3, medianFlag = True):
L = np.squeeze(L)
if np.iscomplex(L).sum() > 0:
L = np.abs(L)
L = normalize(L.astype('float32'))
# determine b
if medianFlag:
m = np.median(L[np.where(L>0)])
else:
m = np.sqrt(np.sum(L**2) / (2*np.prod(L.shape)))
#
if np.isnan(m):
return np.zeros_like(L)
b = (targetBrightness - targetBrightness * m) / (m - targetBrightness * m)
b = np.clip(b, 1, 99999999)
# apply b
L = (b*L) / ((b-1)*L + 1 + 1e-9)
return L
#-----------------------------------------------------------------------------------------------------------------------------------------------------
def imwrite(mat, filename, normalize_data=True):
if mat.ndim == 3:
mat = mat[:,:,0:3]
if normalize_data:
mat = (normalize(mat)*255).astype('uint8')
else: # grayscale
if normalize_data:
mat = (normalize(mat)*255).astype('uint8')
else:
mat = (mat*255).astype('uint8')
#
img = Image.fromarray(mat)
img.save(filename)
return
#-----------------------------------------------------------------------------------------------------------------------------------------------------
# Normalizes array to [0,1]
def normalize(arr):
arr -= arr.min()
arr /= (arr.max() + 1e-9)
return arr
#-----------------------------------------------------------------------------------------------------------------------------------------------------
def get_fig_as_numpy(fig):
import io
buf = io.BytesIO()
fig.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
buf.seek(0)
# Open the image with PIL and convert to NumPy array
image = Image.open(buf)
image_array = np.array(image)
# Close the BytesIO object
buf.close()
# Resize the image to 256x256 using PIL
resized_image = Image.fromarray(image_array).resize((512, 512), Image.ANTIALIAS)
resized_image_array = np.array(resized_image)
return resized_image_array