-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDemonsSuperResolution.py
More file actions
294 lines (242 loc) · 11.5 KB
/
Copy pathDemonsSuperResolution.py
File metadata and controls
294 lines (242 loc) · 11.5 KB
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
import numpy as np
from skimage.transform import resize
import subprocess
import scipy.io as sio
from scipy.sparse import csr_matrix, coo_array
import json
import imresize
from scipy.signal import medfilt2d
# if isempty(model.SR)
# % Initialize super-resolved image by the temporal median of the
# % motion-compensated low-resolution frames.
# %SR = imageToVector( imresize(medfilttemp(LRImages, model.motionParams), ...
# % coarseToFineScaleFactors(1)) );
# SR = imageToVector( imresize(medfilttemp(LRImages, model.motionParams), ...
# coarseToFineScaleFactors(1)) );
# else
# % Use the user-defined initial guess.
# SR = imageToVector( imresize(model.SR, coarseToFineScaleFactors(1)) );
# end
# % Initialize the confidence weights of the observation model.
# for frameIdx = 1:size(LRImages, 3)
# % Use uniform weights as initial guess.
# model.confidence{frameIdx} = ones(numel(LRImages(:,:,frameIdx)), 1);
# end
# % Iterations for cross validation based hyperparameter selection.
# maxCVIter = optimParams.maxCVIter;
# % Decide if the regularization weight should be automatically adjusted
# % per iteration.
# if isempty(model.imagePrior.weight)
# % No user-defined parameter available. Adjust the weight at each
# % iteration.
# useFixedRegularizationWeight = false;
# else
# % Use the user-defined regularization weight.
# useFixedRegularizationWeight = true;
# end
SR = []
confidenceweight = {}
optimParams = {}
model = {}
coarseToFineScaleFactors = range(min(1,model['magFactor']), model.magFactor)
Y= []
residualError = []
W = []
def imageToVector(img):
return img.flatten('F')[:,np.newaxis]
def get_residual(SR, LR, W, photometric_params=None):
# GETRESIDUAL Get residual error for low-resolution and super-resolved
# data.
# GETRESIDUAL computes the residual error caused by a super-resolved
# image with the associated low-resolution frames and the model
# parameters (system matrix and photometric parameters).
if photometric_params is None:
r = LR - np.dot(W, SR)
else:
num_frames = photometric_params['mult'].shape[2]
num_lr_pixel = len(LR) // num_frames
if np.ndim(photometric_params['mult']) == 2: # Check if 'mult' is a vector
bm = np.zeros_like(LR)
ba = np.zeros_like(LR)
for k in range(num_frames):
start_idx = (k * num_lr_pixel)
end_idx = ((k + 1) * num_lr_pixel)
bm[start_idx:end_idx] = np.tile(photometric_params['mult'][:,:,k], (num_lr_pixel, 1)).flatten()
ba[start_idx:end_idx] = np.tile(photometric_params['add'][:,:,k], (num_lr_pixel, 1)).flatten()
else:
bm = np.zeros_like(LR)
ba = np.zeros_like(LR)
for k in range(num_frames):
start_idx = (k * num_lr_pixel)
end_idx = ((k + 1) * num_lr_pixel)
bm[start_idx:end_idx] = photometric_params['mult'][:,:,k].flatten()
ba[start_idx:end_idx] = photometric_params['add'][:,:,k].flatten()
r = LR - bm * np.dot(W, SR) - ba
return r
def estimate_observation_confidence_weights(r, weights=None, scale_parameter=None):
# Estimate observation confidence weights
weights_vec = []
r_vec = []
r_max = 0.02 # Threshold for median residual to detect outliers
# r_max = 0.1 # Alternative threshold (commented out in MATLAB)
for k in range(len(r)):
r_vec.extend(r[k])
if np.abs(np.median(r[k])) < r_max:
weights_bias_k = 1
else:
weights_bias_k = 0
weights_vec.extend([w * weights_bias_k for w in weights[k]])
if scale_parameter is None:
if any(w > 0 for w in weights_vec):
# Use adaptive scale parameter estimation
scale_parameter = get_adaptive_scale_parameter(np.array(r_vec)[np.array(weights_vec) > 0],
np.array(weights_vec)[np.array(weights_vec) > 0])
else:
scale_parameter = 1
for k in range(len(r)):
# Estimate local confidence weights for current frame
c = 2
weights_local = 1 / np.abs(r[k])
weights_local[np.abs(r[k]) < c * scale_parameter] = 1 / (c * scale_parameter)
weights_local = c * scale_parameter * weights_local
# Assemble confidence weights from bias weights and local weights
if any(weights_bias_k > 0 for weights_bias_k in weights_vec):
weights[k] = [weights_bias_k * weights_local_i for weights_bias_k, weights_local_i in zip(weights_vec, weights_local)]
else:
weights[k] = [1 * weights_local_i for weights_local_i in weights_local]
return weights, scale_parameter
def get_adaptive_scale_parameter(r, weights):
# Nested function to compute adaptive scale parameter
weighted_median_diff = np.abs(r - weighted_median(r, weights))
scale_parameter = 1.4826 * weighted_median(weighted_median_diff[weights > 0], weights[weights > 0])
return scale_parameter
def weighted_median(values, weights):
# Function to compute weighted median
sorted_indices = np.argsort(values)
sorted_values = values[sorted_indices]
sorted_weights = weights[sorted_indices]
cumulative_weights = np.cumsum(sorted_weights)
total_weight = np.sum(sorted_weights)
median_index = np.searchsorted(cumulative_weights, total_weight / 2.0)
return sorted_values[median_index]
def get_btv_transformed_image(X, P, alpha0):
# Pad image at the border to perform shift operations
Xpad = np.pad(X, ((P, P), (P, P)), mode='symmetric')
# Consider shifts in the interval [-P, +P]
btv_transformed_image = []
rows, cols = X.shape
for l in range(-P, P + 1):
for m in range(-P, P + 1):
if l != 0 or m != 0:
# Shift by l and m pixels
Xshift = Xpad[(P + l):(P + l + rows), (P + m):(P + m + cols)]
# Apply BTV transformation
transformed_patch = alpha0**(np.abs(l) + np.abs(m)) * (Xshift - X)
# Apply median filtering
filtered_patch = medfilt2d(transformed_patch, kernel_size=3)
# Convert the filtered patch to a vector and append to btv_transformed_image
btv_transformed_image.append(filtered_patch.flatten())
btv_transformed_image = np.array(btv_transformed_image)
return btv_transformed_image
def estimate_wbtv_prior_weights(z, p=0.5, weights=None, scale_parameter=None):
# Estimate weights for WBTVPrior
if weights is None:
weights = np.ones_like(z)
if scale_parameter is None:
scale_parameter = get_adaptive_scale_parameter(z, weights)
# Estimation of weights based on pre-selected scale parameter
c = 2
scale_parameter *= c
weights = (p * scale_parameter**(1 - p)) / (np.abs(z)**(1 - p))
weights[np.abs(z) <= scale_parameter] = 1
return weights, scale_parameter
def get_adaptive_scale_parameter(z, weights):
# Nested function to compute adaptive scale parameter
median_z = weighted_median(z, weights)
weighted_median_diff = np.abs(z - median_z)
scale_parameter = weighted_median(weighted_median_diff, weights)
return scale_parameter
def weighted_median(values, weights):
# Function to compute weighted median
sorted_indices = np.argsort(values)
sorted_values = values[sorted_indices]
sorted_weights = weights[sorted_indices]
cumulative_weights = np.cumsum(sorted_weights)
total_weight = np.sum(sorted_weights)
median_index = np.searchsorted(cumulative_weights, total_weight / 2.0)
return sorted_values[median_index]
if len(SR) == 0:
tensor = np.stack(matrices_list,axis=-1)
print(tensor.shape)
sr_med = np.zeros((tensor.shape[0],tensor.shape[1]))
for y in range(tensor.shape[0]):
for x in range(tensor.shape[1]):
a = np.array(tensor[y,x,:])
for value in a:
if value>0:
np.delete(a,np.where(a==0))
sr_med[y,x] = np.median(a)
print(sr_med)
#Setting Scale
np.array(sr_med)
scale = 1
img_rsz = resize(sr_med,(sr_med.shape[0],sr_med.shape[1]),anti_aliasing= True )
print(img_rsz)
SR = sr_med
SR = imageToVector(SR)
for frameIdx in range(0,tensor.shape[2]):
confidenceweight[frameIdx] = np.ones(len(tensor.shape[:,:,frameIdx],1))
maxCVIter = optimParams['maxCVIter']
if model['imagePrior'] and model['imagePrior'].get('weight', None) is not None:
useFixedRegularizationWeight = True
else:
useFixedRegularizationWeight = False
for iter in range(0,optimParams['maxMMiter']):
if iter <= len(coarseToFineScaleFactors):
model['magFactor'] = coarseToFineScaleFactors[iter]
for frameIdx in range(0,tensor.shape[2]):
params = {'size': tensor.shape[:,:,frameIdx], 'magFactor': model['magFactor'], 'psfWidth' : model['psfWidth'], 'motionParams': model['motionParams'] }
json_object = json.dumps(params, indent=8)
with open("params.json", "w") as outfile:
outfile.write(json_object)
matBin = "/home/labcisne/R2022a/bin/matlab"
# Necessario definir variavel folder se o .py nao estiver na mesma pasta do composeSM.m, CC folder = ""
folder = "/home/labcisne/DocThais/DocThais/Projeto/Testes/SRPython"
# folder = ""
script = "testeComposeSystemMarix.m"
cmd = []
cmd.append(matBin)
cmd.append("-sd")
cmd.append(folder)
cmd.append("-batch")
cmd.append(f"run('{script}');")
subprocess.run(cmd)
W[frameIdx] = sio.loadmat('Wmx.mat')
elif iter>1:
SR= imresize.imresize(np.reshape(SR,(tensor.shape[0]*coarseToFineScaleFactors[iter-1],tensor.shape[1]*coarseToFineScaleFactors[iter-1]),'C'),
(tensor.shape[0]*coarseToFineScaleFactors[iter],tensor.shape[1]*coarseToFineScaleFactors[iter]))
SR = imageToVector(SR)
for frameIdx in range(0,tensor.shape[2]):
Y[frameIdx] = imageToVector(tensor[:,:,frameIdx])
residualError[frameIdx] = get_residual(SR, Y[frameIdx],W[frameIdx], model['photometric_params'])
model['confidence'], sigmanoise = estimate_observation_confidence_weights(residualError, model['confidence'])
################################
################################
################################
#model.imagePrior.parameters{3}, model.imagePrior.parameters{4}
btvTransformedImage = get_btv_transformed_image(np.reshape(SR,(model['magFactor']*tensor[:,:,0].shape[0],model['magFactor']*tensor[:,:,0].shape[0],'C')))
try:
btvWeights
except NameError:
btvWeights = np.ones(btvTransformedImage.shape[0],btvTransformedImage.shape[1])
if (btvWeights.shape[0]*btvWeights.shape[1]) != (btvTransformedImage.shape[0]*btvTransformedImage.shape[1]):
btvWeights = imresize.imresize(btvWeights,(btvTransformedImage.shape[0]*btvTransformedImage.shape[1]))
btvWeights, sigmaBTV = estimate_wbtv_prior_weights(btvTransformedImage,optimParams['sparsityParameter'],btvWeights)
if maxCVIter > 1 and useFixedRegularizationWeight == False:
model.imagePrior.weight, SR_best = selectregularizationweight()
maxCVIter = max(round(0.5 * maxCVIter), 1)
else:
# No automatic hyperparameter selection required
SR_best = SR
SR_old = SR
SR, numFumEvals =