CaptIglu
CaptIglu

Reputation: 93

Matlab: Create RGB matrix depending on values in 2 other matrices

sorry for the stupid question. I want to define an RGB image in matlab depending on the values in two matrices. e.g.:

  A       B         comparision RGB
|1 0|   |1 0|  -->  |green    red  |
|1 0|   |0 1|  -->  |purple   cyan |

The following code does the job but is very slow (I know):

comparision = uint8(zeros([H,W, 3])); 
for i=1:H
  for j=1:W
    if (A(i,j)==1 && B(i,j)==1) %tp
        comparision (i,j,:) = [113 140 0];
    end
    if (A(i,j)==0 && B(i,j)==0) %tn
        comparision (i,j,:) = [200 40 41];
    end
    if (A(i,j)==0 && B(i,j)==1) %fp (false alarm)
        comparision (i,j,:) = [10 130 120];
    end
    if (A(i,j)==1 && B(i,j)==0) %fn 
        comparision (i,j,:) = [120 20 120];
    end
  end
end

I'm pretty sure it can be done a lot faster using matlab matrix functionality. Unfortunately I'm always a bit confused about the matlab notation and was not successful googling :-/.

I tried something like this:

comparision(LabelImage1 == 1 & LabelImage2 == 1) = [255 0 0]

But it didn't work out.

Can anybody help me doing it faster? Thanks in advance

Upvotes: 2

Views: 272

Answers (1)

beaker
beaker

Reputation: 16791

You can convert the values A, B to indices and then use ind2rgb to map those indices to colors:

indImg = uint8(A.*2 + B);   % generate indices [0..3]
cMap = [1, 0, 0;   % red
        0, 1, 1;   % cyan
        1, 0, 1;   % magenta
        0, 1, 0];  % green
comparison = ind2rgb(indImg, cMap);   % convert indices to cMap RGB values

An indexed image is one in which each pixel value is an (integer) index into a color map rather than an RGB or grayscale value. You can display this kind of image directly using imshow:

imshow(indImg, cMap)

An indexed image of type uint8 or uint16 is the one situation I know of where MATLAB uses 0-based indexing, which is why the indices above are [0..3] and why @Divakar's alternate solution in the comments had to use indImg+1.

The function ind2rgb simply takes each of these indices and replaces them with the 3D RGB value, each of which would be something like permute(cMap(index), [1 3 2]).


For more speed, here's an amusing option:

comparison = cat(3, ~B, B, xor(A,B));

(you might have to cast that to a double, I'm not sure...)

Here is a simple comparison on ideone using this approach, my original code, and Divakar's suggestion. I couldn't get the image size above 2000x2000 due to memory limitations of the online interpreter, but this approach seems to be at least twice as fast as the others.

Upvotes: 5

Related Questions