Alessandro
Alessandro

Reputation: 794

Change values of multiple pixels in a RGB image

I have to change pixel values in a RGB image. I have two arrays indicating positions, so:

rows_to_change = [r1, r2, r3, ..., rn];
columns_to_change = [c1, c2, c3, ..., cn];

I would operate this modification without loops. So intuitively, in order to set the red color in those location, I write:

image(rows_to_change, columns_to_change, :) = [255, 0, 0];

This code line returns an error.

How can I operate this change without using a double for loop?

Upvotes: 2

Views: 1695

Answers (2)

Daniel
Daniel

Reputation: 36710

If you really don't want to separate the channels you can us this code, but it's definitely more complicated to do it this way:

%your pixel value
rgb=[255, 0, 0]
%create a 2d mask which is true where you want to change the pixel
mask=false(size(image,1),size(image,2))
mask(sub2ind(size(image),rows_to_change,columns_to_change))=1
%extend it to 3d
mask=repmat(mask,[1,1,size(image,3)])
%assign the values based on the mask.
image(mask)=repmat(rgb(:).',numel(rows_to_change),1)

The primary reason I originally came up with this idea where Images with a variable number of channels.

Upvotes: 1

Dan
Dan

Reputation: 45752

You can use sub2ind for this, but it's easier to work per channel:

red = image(:,:,1);
green = image(:,:,2);    
blue = image(:,:,3);

Convert your row and column indices (i.e. subscript indices) to linear indices (per 2D channel):

idx = sub2ind(size(red),rows_to_change,columns_to_change)

Set the colours per channel:

red(idx) = 255;
green(idx) = 0;
blue(idx) = 0;

Concatenate the channels to form a colour image:

new_image = cat(3,red,green,blue)

Upvotes: 3

Related Questions