r_undistort.m 2.56 KB
function r_undistort(expNumber,camNumber,iFirst,nSkip,iEnd)
% R_UNDISTORT - Undistort a batch of images and copy them in a
% separate directory called undistort. Images are saved in RGB jpg.
%
% Syntax:  r_undistort(expNumber,camNumber,iFirst,nSkip,iEnd)
%
% Inputs:
%    expNumber - The experiment identifier
%    camNumber - The camera number
%    iFirst    - The number of the first image to be treated
%    nSkip     - The number of images skipped
%    iEnd      - The last image to be treated. Set to zero to treat all
%                images.
%
% Example:
%    r_undistort(201307231525,2,1,1,0)
%
% Other m-files required: calib toolbox
%   (http://www.vision.caltech.edu/bouguetj/calib_doc/)
% Subfunctions: none
% MAT-files required: Calib_Results (produced by the calib procedure)
%
% See also: CALIB, CALIB_GUI, RECT, R_ROTATE

% Author: Dany Dumont
% UQAR/ISMER
% email: dany_dumont@uqar.ca
% Website: http://www.ismer.ca/dumont-dany
% September 2013
% ______________________________________________________________________

nbF = 40;
nbFStr = num2str(nbF);

rootdir = ['/MP_oceanographie/MP/images/multicam_',nbFStr,'f'];
expdir  = [rootdir,'/',num2str(expNumber),'_multicam'];
camdir  = [expdir,'/cam',num2str(camNumber)];
origdir = [camdir,'/original'];
unddir  = [camdir,'/undistorted'];
caldir  = [rootdir,'/calib/cam',num2str(camNumber)];
calfile = [caldir,'/Calib_Results'];

load(calfile)

if ~exist('fc','var')||~exist('cc','var')||~exist('kc','var')||~exist('alpha_c','var'),
    fprintf(1,'No intrinsic camera parameters available.\n');
    return
end

% KK = [fc(1) alpha_c*fc(1) cc(1);0 fc(2) cc(2) ; 0 0 1];

% Compute the new KK matrix to fit as much data in the image in order to
% accomodate large distortions
r2_extreme = (nx^2/(4*fc(1)^2) + ny^2/(4*fc(2)^2)); %#ok<NASGU>
dist_amount = 1;        %(1+kc(1)*r2_extreme + kc(2)*r2_extreme^2);
fc_new = dist_amount * fc;

KK_new = [fc_new(1) alpha_c*fc_new(1) cc(1);0 fc_new(2) cc(2) ; 0 0 1];

cd(origdir)

imfiles = dir('im*.jpg');
nFiles  = size(imfiles,1);

if ~exist(unddir,'dir')
    mkdir(unddir)
end

if iEnd == 0
    iEnd = nFiles;
end

for n = iFirst:nSkip:iEnd
    
    imfilename = imfiles(n).name;
    imNumber   = imfilename(3:7);
    
    disp([' ',imNumber]);
    
    I = imread(imfilename);
    I = double(I);
    
    I_rect(:,:,1) = rect(I(:,:,1),eye(3),fc,cc,kc,alpha_c,KK_new);
    I_rect(:,:,2) = rect(I(:,:,2),eye(3),fc,cc,kc,alpha_c,KK_new);
    I_rect(:,:,3) = rect(I(:,:,3),eye(3),fc,cc,kc,alpha_c,KK_new);
    I_rect = uint8(I_rect);

    imwrite(I_rect,[unddir,'/im',imNumber,'_undistorted.jpg'],'jpg');
    
end