How to optimize my code??
5 views (last 30 days)
Show older comments
Hi. I have 100 images which is stored in "in{v}". I have 7 templates to compare and detect specific x and y positions in the images. I get my desired result. But, this program runs for about 30 minutes. Could someone help me to execute the code more rapidly??
clear all;
clc;
for v=1:100
input=sprintf('image%u.jpeg',v);
in{v}=rgb2gray(imread(input));
[r c]=size(in{v});
for u=1:7
input=sprintf('template%u.jpeg',u);
s{u}=rgb2gray(imread(input));
for i=1:c-33
for j=1:r-54
a=imcrop(in{v},[i j 53 32]);
b=corr2(s{u},a);
if((b>0.97) && (b<1.03))
d=1;
break;
else
d=0;
end
end
if (d==1)
break;
end
end
if (d==1)
x(u,v)=i;
y(u,v)=j;
end
end
end
0 Comments
Answers (2)
Ken Atwell
on 5 Jan 2012
Your profile tells us that all the time is being spent in two MATLAB functions. You could replace the imcrop call with simple MATLAB indexing, since that is all that it is really doing here. Try:
a=in{v(j:j+32, i:i+53)};
Better still, if you have access to the Parallel Computing Toolbox, your outermost for loop, with a little work, could be parallelized into a parfor loop.
1 Comment
KAE
on 15 Nov 2018
I have also found that imcrop is very slow in R2018b due to all the interactive bells & whistles. If you just want to select a specified subregion, you should index directly as Ken recommends.
Sean de Wolski
on 5 Jan 2012
I would recommend using the profile as a first step to see what is taking the longest.
doc profile
More:
It appears you already know the end sizes of x,y,u,in so preallocate them at the beginning of your script (as those cute orange bars on the side of the editor are hinting at):
in = cell(100,1);
s = cell(7,1);
x = zeros(7,100);
y = zeros(7,100);
Also clear all clears functions from memory and can slow things down a little bit. Use clear or clearvars instead.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!