2

I need to write a code that flips the image across y-axis. This code is working but it turns the image to grayscale. I want it to stay in RGB. Lastly, I am not able to use any functions. (imrotate etc.)

subplot(1,2,1);
imshow(A);
title('original')
 
[r c ~]= size(A)
 
for i=1:r
   for j=1:c
       Aa(i,j)=A(i,c-j+1);
    end
end
 
subplot(1,2,2);
imshow(Aa);
title('flipped across vertical axis')
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120

2 Answers2

3

You can use the function flip to flip any array along one axis:

Aa = flip(A,2);

This will work for both a gray-scale and an RGB image.

This is equivalent to the following indexing expression for a 3D array (such as an RGB image):

Aa = A(:,end:-1:1,:);

Tip: If you are going to write a loop, always make the inner loop the one that loops over the first index. This makes a huge speed difference if the array doesn’t fit in the cache (such as any normal-sized image). In the code in the OP, the two loops should be reversed for best cache usage.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
2

if you said it works for one dimension, why not use the same for all 3 dimensions of RGB?

subplot(1,2,1); imshow(A); title('original')

[r c ~]= size(A)

for dim=1:3
    for i=1:r
        for j=1:c
            Aa(i,j,dim)=A(i,c-j+1,dim);
        end
    end
end

subplot(1,2,2); imshow(Aa); title('flipped across vertical axis')
Yossi Levi
  • 1,258
  • 1
  • 4
  • 7