2016-02-16 47 views
2

我必须更改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]; 

此代码行返回错误。

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

+0

'image(rows_to_change,columns_to_change,:)'索引你想要的所有像素吗?这样你也像索引像素(r1,c2,:),这是打算? – Daniel

+0

我会''图像(r1,c1,:)= [255,0,0]'; 'image(r2,c2,:)= [255,0,0]';直到'image(rn,cn,:)= [255,0,0]'。 – Alessandro

回答

3

您可以使用sub2ind这一点,但它更容易每通道的工作:

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

转换你的行和列索引(即下标索引)线性指标(每2D频道):

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

设置每个通道的颜色:

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

Concatenat Ë通道中,形成彩色图像:

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

没有单独的渠道没有办法? – Alessandro

+0

@Alessandro它会是一团糟,但可能使用'permute'。然而,你有一个有限的(非常小的)和固定数量的通道,所以把它们分开是个不错的选择。如果您需要多次执行此操作,请将其封装在一个函数中。 – Dan

+0

好的,谢谢!有用。 – Alessandro

1

如果你真的不想分开的渠道,你能给我们这样的代码,但它肯定是更复杂的做这种方式:

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

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

+0

我会尝试这个选项。实际上,分离三个频道似乎更加复杂。 – Alessandro