Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
745 views
in Technique[技术] by (71.8m points)

matlab - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...