Search code examples
matlabloopsimage-processingcolorsmatrix-indexing

How to concatenate 3 RGB channels without using the cat(3,R,G,B) function


I have a RGB image which I am trying to complement without using the built-in function imcomplement(A).

R=A(:,:,1);% A is the input image
G=A(:,:,2);
B=A(:,:,3);
[r,c]=size(B);
for i=1:1:r
    for j=1:1:c
        R(i,j)=255-R(i,j); 
        G(i,j)=255-G(i,j);
        B(i,j)=255-B(i,j);
    end
end
new=cat(3,R,G,B);

This solution gives the expected output.

How can I do the same thing without using the cat function? This is my current unsuccessful attempt:

[r,c]=size(B);
new=zeros(size(A,1),size(A,2),'uint8');
for i=1:1:r
    for j=1:1:c
        for k=1:1:1
            new(i,j,k)=(255-G(i,j));
        end
    end
end

Solution

  • As mentioned by @Pascal, the most straightforward solution is

    new = intmax('uint8') - A;
    

    If you insist on using loops (which I highly advise against in this case), these should work:

    [r,c,s] = size(A);
    new = zeros(r,c,s,'uint8'); % alternatively: zeros(r,c,s,'like',A);
    for iR = 1:r % the middle :1: is implied
      for iC = 1:c
        for iS = 1:s % s stands for "slice"
          new(iR, iC, iS) = intmax('uint8') - A(iR, iC, iS);
        end
      end
    end
    
    for iR = 1:r
      for iC = 1:c
        new(iR, iC, 1) = intmax('uint8') - R(iR, iC);
        new(iR, iC, 2) = intmax('uint8') - G(iR, iC);
        new(iR, iC, 3) = intmax('uint8') - B(iR, iC);
      end
    end
    

    As you can see, all of the above solutions do not use the cat function which you wanted to avoid.