Speeding up matrix comparison within a loop (logical indexing???)

1 次查看(过去 30 天)
At the moment as part of a larger programme I have the following code, however it takes a 10s of minutes to run. I've seen people on these forums reference something called "logical indexing" that removes the need for the loop however googling logical indexing I couldn't figure out quite what it is or how it works.
for i=2:12
sizeOfIm=size(squeeze(imlab50(i,:,:,:)));
outputIm=zeros(sizeOfIm(1),sizeOfIm(2),sizeOfIm(3));
outputIm(:,:,:)=squeeze(imlab50(i,:,:,:));
outputIm=uint8(outputIm);
for loopy = 1 : sizeOfIm(1)
for loopx = 1:sizeOfIm(2)
if (squeeze((backGrndColour(i,:)).'-mindif(:))>squeeze(imlab50(i,loopy,loopx,:)))
if (squeeze(backGrndColour(i,:)).'-maxdif(:) <squeeze(imlab50(i,loopy,loopx,:)))
outputIm(loopy,loopx,:)=0;
end
end
end
end
In short how do I do the following comparison for every value in the matrices, without having three serperate nested loops that vary i, loopy, and loopx?
if (squeeze((backGrndColour(i,:)).'-mindif(:))>squeeze(imlab50(i,loopy,loopx,:)))

回答(2 个)

Sara
Sara 2015-1-27
Without having any data to test it, I'd say you could do:
for i=2:12
x = squeeze(imlab50(i,:,:,:));
outputIm=uint8(x);
[j,k] = find(squeeze((backGrndColour(i,:)).'-mindif(:)) > x);
outputIm(j,k,:) = 0;
end
In the find, check if it should be x or outputIm.
  1 个评论
Andriy Boubriak
Andriy Boubriak 2015-1-27
I got the followng error
"Error using > Number of array dimensions must match for binary array op.
Error in locator (line 32) [j,k] = find(squeeze((backGrndColour(i,:)).'-mindif(:)) > x);"

请先登录,再进行评论。


Image Analyst
Image Analyst 2015-1-27
What is imlab50? Is it a uint8 video?
And this code:
outputIm=zeros(sizeOfIm(1),sizeOfIm(2),sizeOfIm(3));
outputIm(:,:,:)=squeeze(imlab50(i,:,:,:));
outputIm=uint8(outputIm);
can most likely be replaced with this to save some time possibly.
outputIm = uint8(squeeze(imlab50(i,:,:,:)));
Another thing - you made a very common error, getting x and y wrong. You're calling the first index x and the second one y - that's wrong. The first index is the row index and thus should be y not x, and the second index is the column and thus should be called x, not y.
  3 个评论
Image Analyst
Image Analyst 2015-1-28
If imlab50 is a CIELAB color space image, why does it have 4 dimensions? Is it CMYK or something???

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by