【问题标题】:Change specific locations in RGB image to a particular color based on index locations in MATLAB根据 MA​​TLAB 中的索引位置将 RGB 图像中的特定位置更改为特定颜色
【发布时间】:2012-11-21 07:19:58
【问题描述】:

我在 MATLAB 中有一个 2336x3504 RGB uint8 文件。我还有一个由索引符号中感兴趣的像素组成的向量(基于 2336x3504 二进制图像)。我希望将 RGB 图像中与感兴趣的像素对应的所有点设置为特定颜色。

我的第一个想法是做以下事情:

% Separate RGB image into three 3 uint8 arrays.

RGB1 = RGBImage(:,:,1);

RGB2 = RGBImage(:,:,2);

RGB3 = RGBImage(:,:,3);

% Change each layer based on the color I want (say for red, or [255 0 0])

RGB1(interestPixels) = 255;

RGB2(interestPixels) = 0;

RGB3(interestPixels) = 0;

% Then put it all back together

NewRGBImage = cat(3,RGB1,RGB2,RGB3);

虽然这可行,但它看起来很乱。我确信有一个更优雅的解决方案,但我没有看到它。

【问题讨论】:

    标签: matlab rgb


    【解决方案1】:

    到目前为止我能找到的最简单的方法是:

    % test init
    mat = randi(3,[2 4 3]);        % a 3-channel 2x4 image
    interest_pix = [1 1;2 2; 1 3]; % some pixel coordinates
    
    channel_selector = ones(1,size(interest_pix,1));
    inds_chn1 = sub2ind(size(mat),interest_pix(:,1), interest_pix(:,2),1*channel_selector);
    inds_chn2 = sub2ind(size(mat),interest_pix(:,1), interest_pix(:,2),2*channel_selector);
    inds_chn3 = sub2ind(size(mat),interest_pix(:,1), interest_pix(:,2),3*channel_selector);
    
    mat(inds_chn1)=255;    % you could also use NaN or Inf to make the changes more apparent
    mat(inds_chn2)=0;
    mat(inds_chn3)=0;
    

    这种方法的优点是它不会为通道创建新矩阵。

    阅读材料:matrix indexing.

    【讨论】:

      【解决方案2】:

      以上代码有错误。这是正确的。试试吧。

      function testmat=testmat()
      mat = rand(3,3,3)% a 3-channel 2x4 image
      [v w c]=size(mat)
      interest_pix = [1 1;2 2; 1 3]; % some pixel coordinates
      
      channel_selector = ones(1,size(interest_pix,1));
      c1=1*channel_selector;
      d1(:,1)=c1(1,:);
      
      c2=2*channel_selector;
      d2(:,1)=c2(1,:)
      
      c3=3*channel_selector;
      d3(:,1)=c3(1,:);
      
      inds_chn1 = sub2ind(size(mat),interest_pix(:,1), interest_pix(:,2),1*d1);
      inds_chn2 = sub2ind(size(mat),interest_pix(:,1), interest_pix(:,2),1*d2);
      inds_chn3 = sub2ind(size(mat),interest_pix(:,1), interest_pix(:,2),1*d3);
      
      mat(inds_chn1)=255;    % you could also use NaN or Inf to make the changes more apparent
      mat(inds_chn2)=0;
      mat(inds_chn3)=0;
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-28
        • 1970-01-01
        • 2011-01-02
        相关资源
        最近更新 更多