File: ef230-2023-08/www/examples/image_cropper.m Download
%! Interactive image cropping
%! Prompts user for a file name of a file that contains one or more
%! images that are to be rotated and cropped. The user then clicks on the
%! corners of the images and Matlab extracts, rotates, crops, and
%! saves the sub-image(s).
% University of Tennessee : EF 230 Fall, 2009 : Will Schleter

function image_cropper
clear all; close all; clc;
global g

getsampleimage();

while process_image
end

close all;
return

%-------------------------
function done=process_image
% read and show a main image until user cancels
global g
done=false;
[FileName,PathName] = uigetfile('scan*.jpg','Select the input file');
if FileName==0, return; end
figure(1)
g.img=imread([PathName FileName]);
imshow(g.img);
while process_sub_image
end
done=true;
close(1);
return


%-------------------------
function done=process_sub_image()
% prompt for info about a sub image until user cancels
global g
done=false;
figure(1);
hold on;
prompts={'top left','bottom left','bottom right','top right'};
x1=[];
y1=[];
for i=1:4
    title(['Click on the ' prompts{i} ' corner of the sub-image. Right click to cancel.']);
    [x,y,b] = ginput(1);
    if b~=1
        return
    end
    x1(i)=x;
    y1(i)=y;
    text(x,y,num2str(i));
end
done=true;
figure(2)
imc=imcrop(g.img,[min(x1),min(y1),max(x1)-min(x1),max(y1)-min(y1)]);
dx=x1(3)-x1(2);
dy=y1(3)-y1(2);
ang = 180/pi*atan2(dy,dx);
imr=imrotate(imc,ang);
imshow(imr)
title('Click on top left corner');
[x,y,but]=ginput(1);
if but~=1, close(2); return; end;
dx=norm([diff(x1(2:3)) diff(y1(2:3))])
dy=norm([diff(x1(1:2)) diff(y1(1:2))])
imrc=imcrop(imr,[x,y,round(dx),round(dy)]);
imshow(imrc);
defname=getnextname('pic',4,'.jpg');
name=inputdlg('Enter file name','Cropper',1,{defname});
if length(name)==0, close 2; return; end
imwrite(imrc,name{1});
close(2);
done=true;
return


%-------------------------
function r=getnextname(prefix,numsize,extension)
% search current directory for files of the form prefix*extension
% and returns the next available file name where * is replaced by
% a number that is ns characters long and next in sequence
% example if called with 'file',4,'.jpg' and file0003.jpg exists
% in the current directory, this routine would return file0004.jpg
ss = strcat(prefix,'*',extension)
files=dir(ss)
imax=1;
j1=length(prefix)+1;
j2=length(prefix)+numsize;
for i=1:length(files)
    n=str2num(files(i).name(j1:j2));
    if ~isempty(n), imax=max(imax,n); end;
end
r=sprintf('%s%0*u%s',prefix,numsize,imax+1,extension);
return

%-------------------------
function getsampleimage()
% get a sample image
url='http://ef.engr.utk.edu/ef230-2009-08/modules/misc/data/';
file='scancropsample.jpg';
if exist(file,'file')
  return
end
h=msgbox('Loading file from web site, please wait...');
urlwrite([url file],file);
close(h);
return