0

So lately I am trying to work with indexes instead of for loops since it looks AND feels way faster on matlab.

So I am trying to change the following;

for i =1:size(l,1)
        for j=1:size(l,2)
                     if  l(i,j,1)>200 &&  l(i,j,2)<40 && l(i,j,3)<40
                          l(i,j,1)=144;
                          l(i,j,2)=0;
                          l(i,j,3)=0;

                     end
        end
end

into this:

p1(:,:,1)= (200 < l(:, :,1) & 40 > l(:, :,2) & 40 > l(:, :,3)) ;
p2(:,:,2)= (200 < l(:, :,1) & 40 > l(:, :,2) & 40 > l(:, :,3));
p3(:,:,3)= (200 < l(:, :,1) & 40 > l(:, :,2) & 40 > l(:, :,3));
pix(p1(:,:,1))=144;
pix(p2(:,:,2))=0;
pix(p3(:,:,3))=0;

It is almost working and I can see the pictures , but the colors appear different on both pics. I mean that imshow(pix) doesn't look exactly the same as imshow(l). I really cant spot the problem.

4

2 回答 2

0

这应该可以正常工作:

% This is how the data look like
q = randi(256, [1000, 1000, 3]);

% This is the desired outcome:
tic
qq = q;
for i = 1:size(q, 1)
        for j = 1:size(q, 2)
                     if  ((q(i, j, 1) > 200) && (q(i, j, 2) < 40) && (q(i, j, 3) < 40))
                          qq(i, j, 1) = 144;
                          qq(i, j, 2) = 0;
                          qq(i, j, 3) = 0;
                     end
        end
end
toc

% This is a faster solution    
tic
p1(:, :, 1) = (q(:, :, 1) > 200) & (q(:, :, 2) < 40) & (q(:, :, 3) < 40);
p2(:, :, 2) = p1(:, :, 1);
p3(:, :, 3) = p1(:, :, 1);
pix = q;
pix(p1(:)) = 144;
pix(p2(:)) = 0;
pix(p3(:)) = 0;
toc

% Check that the solution returns the desired outcome:    
all(pix(:) == qq(:))
sum(pix(:) ~= qq(:))
于 2013-10-29T23:46:01.667 回答
0

Here is a quick fix, using vectors to reference matrix elements refers to more elements than you intend. It still has one for loop though, but it should be quicker than your original method.

[ti,tj]=find(pix(:,:,1)>200 &  pix(:,:,2)<40 & pix(:,:,3)<40);
for k=1:length(ti)
    pix(ti(k),tj(k),:)=[144 0 0];
end
于 2013-10-29T23:28:37.030 回答