Image 更改RGB图像中多个像素的值

Image 更改RGB图像中多个像素的值,image,matlab,matrix,rgb,Image,Matlab,Matrix,Rgb,我必须改变RGB图像中的像素值。 我有两个数组指示位置,因此: rows_to_change = [r1, r2, r3, ..., rn]; columns_to_change = [c1, c2, c3, ..., cn]; 我会在没有回路的情况下进行修改。直观地说,为了在这些位置设置红色,我写道: image(rows_to_change, columns_to_change, :) = [255, 0, 0]; 此代码行返回一个错误 如何在不使用双for循环的情况下操作此更改?您可以

我必须改变RGB图像中的像素值。 我有两个数组指示位置,因此:

rows_to_change = [r1, r2, r3, ..., rn];
columns_to_change = [c1, c2, c3, ..., cn];
我会在没有回路的情况下进行修改。直观地说,为了在这些位置设置红色,我写道:

image(rows_to_change, columns_to_change, :) = [255, 0, 0];
此代码行返回一个错误


如何在不使用双for循环的情况下操作此更改?

您可以使用
sub2ind
进行此操作,但每个通道更容易操作:

red = image(:,:,1);
green = image(:,:,2);    
blue = image(:,:,3);
red(idx) = 255;
green(idx) = 0;
blue(idx) = 0;
将行和列索引(即下标索引)转换为线性索引(每个2D通道):

设置每个通道的颜色:

red = image(:,:,1);
green = image(:,:,2);    
blue = image(:,:,3);
red(idx) = 255;
green(idx) = 0;
blue(idx) = 0;
连接通道以形成彩色图像:

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

如果您真的不想分离通道,可以使用以下代码,但这样做肯定更复杂:

%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)

我最初提出这个想法的主要原因是,具有可变通道数的图像。

是否
图像(行到列的变化,列到列的变化,:)
索引所有需要的像素?这样你也可以索引像素,比如(r1,c2,:),这是有意的吗?我希望
图像(r1,c1,:)=[255,0,0]
<代码>图像(r2,c2,:)=[255,0,0];直到
image(rn,cn,:)=[255,0,0]
。没有单独的频道是不行的?@Alessandro这会很混乱,但可能使用
permute
。但是,您有一个有限(并且非常小)和固定数量的通道,因此将它们分离是一个很好的选择。如果您需要多次执行此操作,只需将其封装在函数中。我将尝试此选项。实际上,分离三个通道似乎更为复杂。