我在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);
虽然这有效但看起来很混乱。我确信这是一个更优雅的解决方案,但我没有看到它。
答案 0 :(得分:0)
到目前为止,我能找到的最简单的方法是:
% 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。
答案 1 :(得分:0)
以上代码有错误。这是正确的。试试吧。
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