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