%% Parameters groupList = ["/images/MOT_3D_Camera/in_situ_absorption", "/images/ODT_1_Axis_Camera/in_situ_absorption", "/images/ODT_2_Axis_Camera/in_situ_absorption", "/images/Horizontal_Axis_Camera/in_situ_absorption", "/images/Vertical_Axis_Camera/in_situ_absorption"]; folderPath = "C:/Users/Karthik/Documents/GitRepositories/Calculations/IRF/0044/"; cam = 5; angle = 90 + 51.5; center = [1700, 2300]; span = [255, 255]; fraction = [0.1, 0.1]; NA = 0.6; pixel_size = 4.6e-6; lambda = 421e-9; d = lambda/2/pi/NA; k_cutoff = NA/lambda/1e6; %% Compute OD image, rotate and extract ROI for analysis % Get a list of all files in the folder with the desired file name pattern. filePattern = fullfile(folderPath, '*.h5'); files = dir(filePattern); refimages = zeros(span(1) + 1, span(2) + 1, length(files)); absimages = zeros(span(1) + 1, span(2) + 1, length(files)); for k = 1 : length(files) baseFileName = files(k).name; fullFileName = fullfile(files(k).folder, baseFileName); fprintf(1, 'Now reading %s\n', fullFileName); atm_img = im2double(imrotate(h5read(fullFileName, append(groupList(cam), "/atoms")), angle)); bkg_img = im2double(imrotate(h5read(fullFileName, append(groupList(cam), "/background")), angle)); dark_img = im2double(imrotate(h5read(fullFileName, append(groupList(cam), "/dark")), angle)); refimages(:,:,k) = subtract_offset(crop_image(bkg_img, center, span), fraction); absimages(:,:,k) = subtract_offset(crop_image(calculate_OD(atm_img, bkg_img, dark_img), center, span), fraction); end %% Fringe removal optrefimages = removefringesInImage(absimages, refimages); absimages_fringe_removed = absimages(:, :, :) - optrefimages(:, :, :); nimgs = size(absimages_fringe_removed,3); od_imgs = cell(1, nimgs); for i = 1:nimgs od_imgs{i} = absimages_fringe_removed(:, :, i); end %% Compute the Density Noise Spectrum mean_subtracted_od_imgs = cell(1, length(od_imgs)); mean_od_img = mean(cat(3, od_imgs{:}), 3, 'double'); density_fft = cell(1, length(od_imgs)); density_noise_spectrum = cell(1, length(od_imgs)); [Nx, Ny] = size(mean_od_img); dx = pixel_size; dy = pixel_size; xvals = (1:Nx)*dx*1e6; yvals = (1:Ny)*dy*1e6; Nyq_k = 1/dx; % Nyquist dk = 1/(Nx*dx); % Wavenumber increment kx = -Nyq_k/2:dk:Nyq_k/2-dk; % wavenumber kx = kx * dx; % wavenumber (in units of 1/dx) Nyq_k = 1/dy; % Nyquist dk = 1/(Ny*dy); % Wavenumber increment ky = -Nyq_k/2:dk:Nyq_k/2-dk; % wavenumber ky = ky * dy; % wavenumber (in units of 1/dy) % Create Circular Mask n = 2^8; % size of mask mask = zeros(n); I = 1:n; x = I-n/2; % mask x-coordinates y = n/2-I; % mask y-coordinates [X,Y] = meshgrid(x,y); % create 2-D mask grid R = 32; % aperture radius A = (X.^2 + Y.^2 <= R^2); % circular aperture of radius R mask(A) = 1; % set mask elements inside aperture to 1 % Calculate Power Spectrum and plot figure('Position', [100, 100, 1200, 800]); clf for k = 1 : length(od_imgs) mean_subtracted_od_imgs{k} = od_imgs{k} - mean_od_img; masked_img = mean_subtracted_od_imgs{k} .* mask; density_fft{k} = (1/numel(masked_img)) * abs(fftshift(fft2(masked_img))); density_noise_spectrum{k} = density_fft{k}.^2; % Subplot 1 % subplot(2, 3, 1); subplot('Position', [0.05, 0.55, 0.28, 0.4]) imagesc(xvals, yvals, od_imgs{k}) xlabel('µm', 'FontSize', 16) ylabel('µm', 'FontSize', 16) axis equal tight; colorbar colormap (flip(jet)); % set(gca,'CLim',[0 100]); set(gca,'YDir','normal') title('Single-shot image', 'FontSize', 16); % Subplot 2 % subplot(2, 3, 2); subplot('Position', [0.36, 0.55, 0.28, 0.4]) imagesc(xvals, yvals, mean_od_img) xlabel('µm', 'FontSize', 16) ylabel('µm', 'FontSize', 16) axis equal tight; colorbar colormap (flip(jet)); % set(gca,'CLim',[0 100]); set(gca,'YDir','normal') title('Averaged density image', 'FontSize', 16); % Subplot 3 % subplot(2, 3, 3); subplot('Position', [0.67, 0.55, 0.28, 0.4]); imagesc(xvals, yvals, mean_subtracted_od_imgs{k}) xlabel('µm', 'FontSize', 16) ylabel('µm', 'FontSize', 16) axis equal tight; colorbar colormap (flip(jet)); % set(gca,'CLim',[0 100]); set(gca,'YDir','normal') title('Image noise = Single-shot - Average', 'FontSize', 16); % Subplot 4 % subplot(2, 3, 4); subplot('Position', [0.05, 0.05, 0.28, 0.4]); imagesc(xvals, yvals, mean_subtracted_od_imgs{k} .* mask) xlabel('µm', 'FontSize', 16) ylabel('µm', 'FontSize', 16) axis equal tight; colorbar colormap (flip(jet)); % set(gca,'CLim',[0 100]); set(gca,'YDir','normal') title('Masked Noise', 'FontSize', 16); % Subplot 5 % subplot(2, 3, 5); subplot('Position', [0.36, 0.05, 0.28, 0.4]); imagesc(kx, ky, abs(log2(density_fft{k}))) xlabel('1/dx', 'FontSize', 16) ylabel('1/dy', 'FontSize', 16) axis equal tight; colorbar colormap (flip(jet)); % set(gca,'CLim',[0 100]); set(gca,'YDir','normal') title('DFT', 'FontSize', 16); % Subplot 6 % subplot(2, 3, 6); subplot('Position', [0.67, 0.05, 0.28, 0.4]); imagesc(kx, ky, abs(log2(density_noise_spectrum{k}))) xlabel('1/dx', 'FontSize', 16) ylabel('1/dy', 'FontSize', 16) axis equal tight; colorbar colormap (flip(jet)); % set(gca,'CLim',[0 100]); set(gca,'YDir','normal') title('Density Noise Spectrum = |DFT|^2', 'FontSize', 16); drawnow; end %% Compute the average 2D spectrum and do radial averaging to get the 1D spectrum % Compute the average power spectrum. averagePowerSpectrum = mean(cat(3, density_noise_spectrum{:}), 3, 'double'); % Plot the average power spectrum. figure('Position', [100, 100, 1200, 500]); clf subplot('Position', [0.05, 0.1, 0.4, 0.8]) % Adjusted position imagesc(abs(10*log10(averagePowerSpectrum))) axis equal tight; colorbar colormap(flip(jet)); % set(gca,'CLim',[0 1e-7]); title('Average Density Noise Spectrum', 'FontSize', 16); grid on; centers = ginput; radius = 6; % Plot where clicked. hVC = viscircles(centers, radius, 'Color', 'r', 'LineWidth', 2); xc = centers(:,1); % xc = [78.2600, 108.3400, 128.8200, 150.5800, 181.3000]; yc = centers(:,2); % yc = [131.3800, 155.7000, 128.8200, 101.3000, 126.2600]; [yDim, xDim] = size(averagePowerSpectrum); [xx,yy] = meshgrid(1:yDim,1:xDim); mask = false(xDim,yDim); for ii = 1:length(centers) mask = mask | hypot(xx - xc(ii), yy - yc(ii)) <= radius; end mask = not(mask); x1 = 1; y1 = 1; x2 = 256; y2 = 256; % Ask user if the circle is acceptable. message = sprintf('Is this acceptable?'); button = questdlg(message, message, 'Accept', 'Reject and Quit', 'Accept'); if contains(button, 'Accept','IgnoreCase',true) image = mask.*averagePowerSpectrum; image(image==0) = NaN; imagesc(kx, ky, mask.*abs(10*log10(averagePowerSpectrum))) hold on line([kx(x1),kx(x2)], [ky(y1),ky(y2)], 'Color','white', 'LineStyle','--', 'LineWidth', 4); % imagesc(kx, ky, 10*log10(averagePowerSpectrum)) % imagesc(kx, ky, log2(averagePowerSpectrum)) % imagesc(kx, ky, averagePowerSpectrum) xlabel('1/dx', 'FontSize', 16) ylabel('1/dy', 'FontSize', 16) axis equal tight; colorbar colormap(flip(jet)); % set(gca,'CLim',[0 1e-7]); title('Average Density Noise Spectrum', 'FontSize', 16); grid on; elseif contains(button, 'Quit','IgnoreCase',true) delete(hVC); % Delete the circle from the overlay. image = averagePowerSpectrum; imagesc(kx, ky, abs(10*log10(averagePowerSpectrum))) % imagesc(kx, ky, 10*log10(averagePowerSpectrum)) % imagesc(kx, ky, log2(averagePowerSpectrum)) % imagesc(kx, ky, averagePowerSpectrum) xlabel('1/dx', 'FontSize', 16) ylabel('1/dy', 'FontSize', 16) axis equal tight; colorbar colormap(flip(jet)); % set(gca,'CLim',[0 1e-7]); title('Average Density Noise Spectrum', 'FontSize', 16); grid on; end subplot('Position', [0.55, 0.1, 0.4, 0.8]) % Adjusted position % [r, Zr] = radial_profile(averagePowerSpectrum, 1); % Zr = (Zr - min(Zr))./(max(Zr) - min(Zr)); % plot(r, Zr, 'o-', 'MarkerSize', 4, 'MarkerFaceColor', 'none'); % set(gca, 'XScale', 'log'); % Setting x-axis to log scale [xi, yi, profile] = improfile(image, [x1,x2], [y1,y2]); profile = (profile - min(profile))./(max(profile) - min(profile)); ks = sqrt(kx.^2 + ky.^2); profile = profile(length(profile)/2:end); ks = ks(length(ks)/2:end); n = 0.15; [val,slice_idx]=min(abs(ks-n)); ks = ks(1:slice_idx); profile = profile(1:slice_idx); plot(ks, profile, 'b*-'); % plot(profile, 'b*-'); grid on; % xlim([min(ks) max(ks)]) title('Radial average of Density Noise Spectrum', 'FontSize', 16); grid on; %% Helper Functions function ret = get_offset_from_corner(img, x_fraction, y_fraction) % image must be a 2D numerical array [dim1, dim2] = size(img); s1 = img(1:round(dim1 * y_fraction), 1:round(dim2 * x_fraction)); s2 = img(1:round(dim1 * y_fraction), round(dim2 - dim2 * x_fraction):dim2); s3 = img(round(dim1 - dim1 * y_fraction):dim1, 1:round(dim2 * x_fraction)); s4 = img(round(dim1 - dim1 * y_fraction):dim1, round(dim2 - dim2 * x_fraction):dim2); ret = mean([mean(s1(:)), mean(s2(:)), mean(s3(:)), mean(s4(:))]); end function ret = subtract_offset(img, fraction) % Remove the background from the image. % :param dataArray: The image % :type dataArray: xarray DataArray % :param x_fraction: The fraction of the pixels used in x axis % :type x_fraction: float % :param y_fraction: The fraction of the pixels used in y axis % :type y_fraction: float % :return: The image after removing background % :rtype: xarray DataArray x_fraction = fraction(1); y_fraction = fraction(2); offset = get_offset_from_corner(img, x_fraction, y_fraction); ret = img - offset; end function ret = crop_image(img, center, span) % Crop the image according to the region of interest (ROI). % :param dataSet: The images % :type dataSet: xarray DataArray or DataSet % :param center: The center of region of interest (ROI) % :type center: tuple % :param span: The span of region of interest (ROI) % :type span: tuple % :return: The cropped images % :rtype: xarray DataArray or DataSet x_start = floor(center(1) - span(1) / 2); x_end = floor(center(1) + span(1) / 2); y_start = floor(center(2) - span(2) / 2); y_end = floor(center(2) + span(2) / 2); ret = img(y_start:y_end, x_start:x_end); end function ret = calculate_OD(imageAtom, imageBackground, imageDark) % Calculate the OD image for absorption imaging. % :param imageAtom: The image with atoms % :type imageAtom: numpy array % :param imageBackground: The image without atoms % :type imageBackground: numpy array % :param imageDark: The image without light % :type imageDark: numpy array % :return: The OD images % :rtype: numpy array numerator = imageBackground - imageDark; denominator = imageAtom - imageDark; numerator(numerator == 0) = 1; denominator(denominator == 0) = 1; ret = -log(double(abs(denominator ./ numerator))); if numel(ret) == 1 ret = ret(1); end end function [R, Zr] = radial_profile(data,radial_step) x = (1:size(data,2))-size(data,2)/2; y = (1:size(data,1))-size(data,1)/2; % coordinate grid: [X,Y] = meshgrid(x,y); % creating circular layers Z_integer = round(abs(X+1i*Y)/radial_step)+1; % very fast MatLab calculations: R = accumarray(Z_integer(:),abs(X(:)+1i*Y(:)),[],@mean); Zr = accumarray(Z_integer(:),data(:),[],@mean); end function [M] = ImagingResponseFunction(B) x = -100:100; y = x; [X,Y] = meshgrid(x,y); R = sqrt(X.^2+Y.^2); PHI = atan2(X,Y)+pi; %fit parameters tau = B(1); alpha = B(2); S0 = B(3); phi = B(4); beta = B(5); delta = B(6); A = B(7); C = B(8); a = B(9); U = heaviside(1-R/a).*exp(-R.^2/a^2/tau^2); THETA = S0*(R/a).^4 + alpha*(R/a).^2.*cos(2*PHI-2*phi) + beta*(R/a).^2; p = U.*exp(1i.*THETA); M = A*abs((ifft2(real(exp(1i*delta).*fftshift(fft2(p)))))).^2 + C; end function [RadialResponseFunc] = RadialImagingResponseFunction(C, k, kmax) A = heaviside(1-k/kmax).*exp(-C(1)*k.^4); W = C(2) + C(3)*k.^2 + C(4)*k.^4; RadialResponseFunc = 0; for n = -30:30 RadialResponseFunc = RadialResponseFunc + besselj(n,C(5)*k.^2).^2 + besselj(n,C(5)*k.^2).*besselj(-n,C(5)*k.^2).*cos(2*W); end RadialResponseFunc = C(6)*1/2*A.*RadialResponseFunc; end function [optrefimages] = removefringesInImage(absimages, refimages, bgmask) % removefringesInImage - Fringe removal and noise reduction from absorption images. % Creates an optimal reference image for each absorption image in a set as % a linear combination of reference images, with coefficients chosen to % minimize the least-squares residuals between each absorption image and % the optimal reference image. The coefficients are obtained by solving a % linear set of equations using matrix inverse by LU decomposition. % % Application of the algorithm is described in C. F. Ockeloen et al, Improved % detection of small atom numbers through image processing, arXiv:1007.2136 (2010). % % Syntax: % [optrefimages] = removefringesInImage(absimages,refimages,bgmask); % % Required inputs: % absimages - Absorption image data, % typically 16 bit grayscale images % refimages - Raw reference image data % absimages and refimages are both cell arrays containing % 2D array data. The number of refimages can differ from the % number of absimages. % % Optional inputs: % bgmask - Array specifying background region used, % 1=background, 0=data. Defaults to all ones. % Outputs: % optrefimages - Cell array of optimal reference images, % equal in size to absimages. % % Dependencies: none % % Authors: Shannon Whitlock, Caspar Ockeloen % Reference: C. F. Ockeloen, A. F. Tauschinsky, R. J. C. Spreeuw, and % S. Whitlock, Improved detection of small atom numbers through % image processing, arXiv:1007.2136 % Email: % May 2009; Last revision: 11 August 2010 % Process inputs % Set variables, and flatten absorption and reference images nimgs = size(absimages,3); nimgsR = size(refimages,3); xdim = size(absimages(:,:,1),2); ydim = size(absimages(:,:,1),1); R = single(reshape(refimages,xdim*ydim,nimgsR)); A = single(reshape(absimages,xdim*ydim,nimgs)); optrefimages=zeros(size(absimages)); % preallocate if not(exist('bgmask','var')); bgmask=ones(ydim,xdim); end k = find(bgmask(:)==1); % Index k specifying background region % Ensure there are no duplicate reference images % R=unique(R','rows')'; % comment this line if you run out of memory % Decompose B = R*R' using singular value or LU decomposition [L,U,p] = lu(R(k,:)'*R(k,:),'vector'); % LU decomposition for j=1:nimgs b=R(k,:)'*A(k,j); % Obtain coefficients c which minimise least-square residuals lower.LT = true; upper.UT = true; c = linsolve(U,linsolve(L,b(p,:),lower),upper); % Compute optimised reference image optrefimages(:,:,j)=reshape(R*c,[ydim xdim]); end end