a b/HelperFunctions/matlab/cropPad/cropPadNii.m
1
function cropPadNii(niiIn,niiOut,compressFlag,normalizeFlag,padNum)
2
%% crop the zero padding around nifti file
3
% Author: Da Ma (da_ma@sfu.ca)
4
% compressFlag: whether to compress the output nifti file (Default: False)
5
% normalizeFlag: whether/how to normalize the input volume
6
%    0 (default): donot normalize
7
%    1 : normalize to [0,1]
8
% [Yet to be implemented]:
9
% padNum: Number of voxels to pad around the cropped images
10
%%
11
12
% By default, don't compress .nii file to .nii.gz
13
if ~exist('compressFlag','var'); compressFlag=false;end
14
% By default, compress to [0,1]
15
if ~exist('normalizeFlag','var'); normalizeFlag=0;end
16
17
%% Read input nifti
18
disp('loading nifti file ...')
19
% read nifti volume
20
vol = niftiread(niiIn);
21
% % read nifti head
22
disp('read nifti header ...')
23
niiHead = niftiinfo(niiIn);
24
%% crop zero pad
25
disp('cropping nifti volume ...')
26
vol = cropPad(vol);
27
% [Yet to be implemented]:
28
% padNum: Number of voxels to pad around the cropped images%% normalze
29
if normalizeFlag == 1
30
    vol = mat2gray(vol);
31
    vol = single(vol);
32
end
33
34
%% update header dimension
35
niiHead.ImageSize = size(vol);
36
niiHead.raw.dim(2:4) = size(vol);
37
38
%% save nifti
39
disp('saving nifti file ...')
40
% determine if need to save as a '.nii.gz' compression file
41
[niiPath,niiName,niiExt] = fileparts(niiOut);
42
[~,~,internalExt] = fileparts(niiName);
43
if internalExt == ".nii" ||niiExt == ".gz"
44
    compressFlag = 1; % = true
45
end
46
savePath = fullfile(niiPath,niiName);
47
%% save nii
48
niftiwrite(vol,savePath,niiHead,'Compressed',compressFlag);
49