# How can I change the red pixel values that are greater than green and blue bands?

2 views (last 30 days)
Duygu Ocal on 15 Mar 2015
Commented: Duygu Ocal on 15 Mar 2015
I have an RGB image, sized (128,128,3). I need to write a for loop and change the pixel values whose red band is larger than their green or blue channels, with white pixels. But I am new to programming and couldn't figure out how to write the for loop. i just have a basic structure;
image2 =ones(128)*255 % a matrix with all white pixel values(255)
for image(128,128,3);
if image(:,:,1) > image(:,:,2:3);
then image(:,:,1) = image2(:,:,1);
end
end
can you help me please?

Guillaume on 15 Mar 2015
Going through the introduction tutorial in matlab's documentation would have told you the syntax of for loops as well as the syntax for if branching.
There's so many things wrong with your code that I'm not going to explain it. Read the doc. If you were going to use a loop, this would work:
for row = 1:size(image, 1) %iterate over the rows
for col = 1:size(image, 2) %iterate over the columns
if all(image(row, col, 1) > image(row, col, 2:3))
image(row, col, :) = 1;
end
end
end
However, using a loop to do this is extremely inneficient. The following will do exactly the same in less line of codes and less time:
isgreater = image(:, :, 1) > image(:, :, 2) & image(:, :, 1) > image(:, :, 3);
image(repmat(isgreater, 1, 1, 3)) = 1; %replicate isgreater across all three colour channels
##### 1 CommentShowHide None
Duygu Ocal on 15 Mar 2015
Thank you for replying. i guess that because my image is small both given codes worked fine and fast but as you've stated, for loop couldn't have worked on a hyperspectral data for example. Thank you again...

### Community Treasure Hunt

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

Start Hunting!