Change values of multiple pixels in a RGB image

与世无争的帅哥 提交于 2019-12-12 18:27:08

问题


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?


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/35434119/change-values-of-multiple-pixels-in-a-rgb-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!