How to optimize my code??

7 次查看(过去 30 天)
Jinnu Panilet
Jinnu Panilet 2012-1-5
评论: KAE 2018-11-15
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

回答(2 个)

Ken Atwell
Ken Atwell 2012-1-5
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 个评论
KAE
KAE 2018-11-15
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
Sean de Wolski 2012-1-5
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.
  1 个评论
Jinnu Panilet
Jinnu Panilet 2012-1-5
Thank you for your reply. I tried doc profile and I found that corr2 function takes 59.1% of the total time and imcrop function takes 40.4% of the total time. Are there any ways to fix this problem??

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Scripts 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by