% perspRect - this function let the user choose a perspectively distorted % rectangular region and rectified the image back to a % rectangle. % % Usage: imRect = perspRect(im,sze,option) % % Arguments: im - image to be rectified % sze - size of the output image, [width,height] in pixel % option - 1: rectify the whole image % 2: rectify the selected region in the image % 3: rectify the selected region and crop it (default) % % Returns: imRect - the rectified image % % Author: % Tzu Yen Wong % wongt AT csse DOT uwa DOT edu DOT au % Department of Computer Science & Software Engineering % The University of Western Australia % % Date: March 2006 function imRect = perspRect(im,sze,option) eval('option;','option=3;') eval('sze;','sze=[300 300];') % get the distorted rectangular area show(im) title('digitize 4 corner points') [x,y]=getline('close'); pts1 = [x(1:4),y(1:4)]'; hold on, plot([x(1:4);x(1)],[y(1:4);y(1)],'-ro') title('digitization of points succeeded!') drawnow % get the output rectangle width = sze(1); height = sze(2); pts2 = [1 width width 1; 1 1 height height]; % calculate the perspective transformation T = homography2d([pts1; ones(1,4); pts2; ones(1,4)]); rg1 = getRegion(pts1,1); warning off if option==1, [imw,newT] = imtrans(im,T); elseif option>=2, [imw,newT] = imtrans(im,T,rg1); else warning('invalid option, default used') end warning on pts1w = trans(inv(newT)*T,pts1); % crop out the rectangular area if option==3, xmin = min(pts1w(1,:)); ymin = min(pts1w(2,:)); ww = max(pts1w(1,:)) - xmin + 1; hh = max(pts1w(2,:)) - ymin + 1; imw = imcrop(imw,[xmin ymin ww hh]); end show(imw) imRect = imw; if option < 3, hold on, polyplot(pts1w,'ro-'); end function region = getRegion(pts,rounded) minrow = min(pts(2,:)); maxrow = max(pts(2,:)); mincol = min(pts(1,:)); maxcol = max(pts(1,:)); region = [minrow maxrow mincol maxcol]; if rounded, region = [floor(minrow) ceil(maxrow) floor(mincol) ceil(maxcol)]; end return