【问题标题】:Change values of multiple pixels in a RGB image更改 RGB 图像中多个像素的值
【发布时间】:2016-02-16 13:37:42
【问题描述】:

我必须更改 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 循环的情况下操作此更改?

【问题讨论】:

  • image(rows_to_change, columns_to_change, :) 是否索引您想要的所有像素?这样,您还可以索引 (r1,c2,:) 之类的像素,这是有意的吗?
  • 我愿意image(r1,c1,:)=[255, 0, 0]; image(r2,c2,:)=[255, 0, 0];直到image(rn,cn,:)=[255, 0, 0]

标签: image matlab matrix rgb


【解决方案1】:

您可以为此使用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;

连接通道形成彩色图像:

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

【讨论】:

  • 没有单独的渠道不行吗?
  • @Alessandro 会一团糟,但可能使用permute。但是,您拥有有限(并且非常小)且固定数量的通道,因此将它们分开是一个不错的选择。如果您需要多次执行此操作,只需将其包装在一个函数中即可。
【解决方案2】:

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

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

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

【讨论】:

  • 我会试试这个选项。实际上,分离三个通道似乎更复杂。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
  • 1970-01-01
相关资源
最近更新 更多