Repository navigation
Expand file tree
/
Copy pathevaluateContrastShrinkage.m
More file actions
executable file
·216 lines (157 loc) · 8.73 KB
/
Copy pathevaluateContrastShrinkage.m
File metadata and controls
executable file
·216 lines (157 loc) · 8.73 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
%% This script tests how much contrast shrinking to perform on the special 100 images to minimize the effect of negative pixel intensities
%
% If this code is used in a publication, please cite the manuscript:
% "H Huang, KN Kay, NM Gregg, G Ojeda Valencia, M In, C Kapeller, Y Shu, GA Worrell, KJ Miller, and D Hermes.
% Single pulse electrical stimulation in white matter modulates iEEG visual responses in human early visual cortex. (Under Review)"
%
% A preprint is available currently at doi: https://doi.org/10.1101/2025.05.05.652264.
%
% The dataset corresponding to this code and manuscript is in BIDS format (version 1.10.0) on OpenNeuro (ds006485),
% and it will be made publicly available upon manuscript acceptance.
%
% Copyright (C) 2025 Harvey Huang
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <https://www.gnu.org/licenses/>.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
addpath('path/to/knkutils/imageprocessing');
addpath('path/to/knkutils/math');
% the 2 images to mix
baseFolder = 'stims/special100'; % where the base images are found
imgList = glob(fullfile(baseFolder, sprintf('*.png')));
listSz = length(imgList);
%% Phase scramble pairs of images and calculate pixels lost by shrinkage
rng('default');
coh = 25;
npairs = 50; % how many pairs to test at each shrinkage
shrinkage = 0:0.05:0.8; % percent of shrinkage at each iteration
pixelsLost = zeros(2*npairs, length(shrinkage));
% all possible image pairs
[X, Y] = meshgrid(1:listSz, 1:listSz);
idxes = logical(triu(ones(listSz), 1)); % indices above diagonal
pairsAll = [Y(idxes), X(idxes)]; % all possible pairs of NSD images
for aa = 1:length(shrinkage)
fprintf('%0.02f', shrinkage(aa));
% select 100 random non-self non-duplicate pairs of NSDspecial images
p = randperm(length(pairsAll));
pairs = pairsAll(p(1:npairs), :); % first 100 randomly permuted pairs
for kk = 1:npairs
fprintf('.');
imgPaths = [imgList(pairs(kk, 1)), imgList(pairs(kk, 2))]; % the 2 images to average together
imgs = cell(2, 1);
imgsGrayLin = cell(2, 1);
% get mean phase from both images
for ii = 1:2
imgs{ii} = imread(imgPaths{ii});
imgs{ii} = imresize(imgs{ii}, 1080/size(imgs{ii}, 1));
imgsGrayLin{ii} = rgb2gray(imgs{ii});
imgsGrayLin{ii} = rgb2lin(imgsGrayLin{ii}, 'ColorSpace', 'adobe-rgb-1998', 'OutputType', 'double');
imgsGrayLin{ii} = imadjustKeepMean(imgsGrayLin{ii}, shrinkage(aa));
end
magMean = sqrt(abs(fft2(imgsGrayLin{1})) .* abs(fft2(imgsGrayLin{2})));
imgsScramb = cell(2, 1);
for ii = 1:2
imgsScramb{ii} = phaseScrambleGrayNotRgb(imgsGrayLin{ii}, coh, false, magMean);
%pixelsLost(kk*2-2+ii, aa) = sum(imgsScramb{ii} < 0, 'all') / numel(imgsScramb{ii});
pixelsLost(kk*2-2+ii, aa) = sum(imgsScramb{ii} < 0 | imgsScramb{ii} > 1, 'all') / numel(imgsScramb{ii});
end
end
fprintf('\n');
end
%% Boxplot across shrinkages for current phase coherence, save output
mkdir(fullfile('output', 'contrastShrinkage'));
figure;
boxplot(pixelsLost, 'Positions', shrinkage, 'Colors', 'b', 'PlotStyle', 'compact');
yline(0, 'Color', [0.5, 0.5, 0.5]);
xlim([min(shrinkage)-0.03, max(shrinkage)+0.03]);
set(gca, 'xtick', shrinkage, 'xticklabels', shrinkage, 'box', 'off');
xlabel('Contrast shrinkage')
ylabel('Fraction of Pixels Lost');
title(sprintf('Phase Coherence %d%%', coh));
saveas(gcf, fullfile('output', 'contrastShrinkage', sprintf('pixelsLostCoh%d', coh)), 'png');
%% Examples of images scrambled with different shrinkage
rng('default');
sh = 0.3; % shrinkage
mkdir(fullfile('output', 'contrastShrinkage', sprintf('examples_sh=%0.2f', sh)));
cohs = [0, 25, 50, 100];
% select 5 random image pairs
p = randperm(length(pairsAll));
pairs = pairsAll(p(1:5), :);
for kk = 1:size(pairs, 1)
imgPaths = [imgList(pairs(kk, 1)), imgList(pairs(kk, 2))]; % the 2 images to average together
imgs = cell(2, 1);
imgsGrayLin = cell(2, 1);
% get mean phase from both images
for ii = 1:2
imgs{ii} = imread(imgPaths{ii});
imgs{ii} = imresize(imgs{ii}, 1080/size(imgs{ii}, 1));
imgName = regexp(imgPaths{ii}, 'shared\d{4}', 'match');
imwrite(imgs{ii}, fullfile('output', 'contrastShrinkage', sprintf('examples_sh=%0.2f', sh), sprintf('%s_orig.png', imgName{1})));
imgsGrayLin{ii} = rgb2gray(imgs{ii});
imgsGrayLin{ii} = rgb2lin(imgsGrayLin{ii}, 'ColorSpace', 'adobe-rgb-1998', 'OutputType', 'double');
imgsGrayLin{ii} = imadjustKeepMean(imgsGrayLin{ii}, sh);
end
magMean = sqrt(abs(fft2(imgsGrayLin{1})) .* abs(fft2(imgsGrayLin{2})));
for cc = 1:length(cohs)
for ii = 1:2
imgScramb = phaseScrambleGrayNotRgb(imgsGrayLin{ii}, cohs(cc), false, magMean);
pixLost = sum(imgScramb < 0 | imgScramb > 1, 'all') / numel(imgScramb);
imgOut = lin2rgb(imgScramb, 'ColorSpace', 'adobe-rgb-1998', 'OutputType', 'uint8');
imgName = regexp(imgPaths{ii}, 'shared\d{4}', 'match');
imwrite(imgOut, fullfile('output', 'contrastShrinkage', sprintf('examples_sh=%0.2f', sh), sprintf('%s_coh=%d_pixLost=%0.2f.png', imgName{1}, cohs(cc), pixLost)));
end
end
end
%% Functions
function imout = imadjustKeepMean(im, shrinkage)
assert(shrinkage >= 0 && shrinkage < 1, 'Shrinkage must be on the range [0, 1)');
assert(ismatrix(im), 'img should be 2D (grayscale) between 0 and 1');
inmean = mean(im, 'all');
outlims = [inmean*shrinkage, 1 - (1-inmean)*shrinkage]; % shrink proportionally toward mean, preserving mean
imout = imadjust(im, [0, 1], outlims);
%imout = imout - mean(imout, 'all') + mean(im, 'all'); % keep the same mean as input
end
% Version of phaseScrambleGray that doesn't convert to rgb at the end so its pixel distribution can be examined
function [imgScramb, phaseChange] = phaseScrambleGrayNotRgb(imgLin, coh, perm, inputMag)
% request linearized grayscale input
if nargin < 3 || isempty(perm), perm = true; end % don't use permuted so that both images are scrambled with the same uniform distribution
%assert(isa(img, 'uint8'), 'Expects image in uint8');
assert(coh >= 0 & coh <= 100, 'pct must be given as percent of contrast within [0, 100]');
%imgGray = rgb2gray(img); % convert to grayscale
%imgLin = rgb2lin(imgGray, 'ColorSpace', 'adobe-rgb-1998', 'OutputType', 'double'); % undo gamma to yield linear rgb (so that pixel intensity scales roughly with intensity)
% FFT on linearized grayscale img
imgLinFft = fft2(imgLin);
if nargin < 4 || isempty(inputMag)
mag = abs(imgLinFft); % magnitude (from image or from input)
else
mag = inputMag;
end
ph = angle(imgLinFft); % phase
% Get random phase
if perm
ph2 = angle(generatepermutedphase(ph)); % phase permuted from input image
else
ph2 = angle(generaterandomphaseFromInput(ph)); % phase randomly reassigned from uniform distribution, but dc and nyquist coefficients kept the same
%ph2 = angle(generaterandomphase(length(ph)));
%ph2(1) = ph(1);
end
phdiff = circulardiff(ph2, ph, 2*pi); % angle needed to reach random phase
% Apply mixture between real and phase scrambled image, ifft
imgScramb = real(ifft2(mag .* exp(1i * (ph + (1 - coh/100)*phdiff))));
phFinal = angle(fft2(imgScramb)); % (redundantly) obtain final phase distribution
phaseChange = mean(abs(sort(phFinal(:)) - sort(ph(:)))); % sort initial and final phase distributions, calculate average difference between distributions
%phaseChange = mean(abs(circulardiff(sort(phFinal(:)), sort(ph(:)), 2*pi))); % using circulardiff? probably unnecessary cuz phases r sorted
%imgOut = lin2rgb(imgScramb, 'ColorSpace', 'adobe-rgb-1998', 'OutputType', 'uint8'); % gamma correct grayscale image, convert back to uint8
end