2011-10-04 44 views
2

我已经实现了一个功能来做到这一点,但我不喜欢循环的必要性。但我没有看到任何避免循环的方法。好奇的是,如果有更好的方法来做到这一点。如何高效地绘制matlab图像中的像素列表?

function [ colored_img ] = colorImg (img, ix, c) 
% function [ colored_img ] = colorImg (img, ix, c) 
% 
% INPUTS 
% img - a 3D array representing the image to color. 
% ix - the indexes of the pixels to set to a new color. 
% c - a vector representing the color to paint the pixels ix. 
% 
% OUTPUTS 
% colored_img - the colored image. 


colored_img = img; 
for jx = 1 : numel(c); 
    a = colored_img(:,:,jx); 
    a(ix) = c(jx); 
    colored_img(:,:,jx) = a; 
end 




end 
+0

究竟是什么第三维? (R,G,B)? –

回答

0

您可以复制颜色的索引。

imageSize = numel(img(:,:,1)); 
rgbIdx = bsxfun(@plus,ix(:),(0:2)*imageSize); 

%# replicate the color so that there are as many 
%# entries as pixels to recolor 
%# (skip this if you use a colormap 
%# of length nPixelsToRecolor) 
nPixelsToRecolor = length(ix); %# assign this so that comment makes sense 
repColor = repmat(c,nPixelsToRecolor,1); %# assuming color is 1-by-3 

colored_img = img; 
colored_img(rgbIdx(:)) = repColor(:); 
+0

嗯,从他的代码看来,第三维具有相同大小的颜色矢量,而不仅仅是R,G,B ?! –

+0

@Laurent':我假设OP希望代码能够同时处理灰度和RGB图像;从而在颜色矢量上循环。 – Jonas

+0

哇,真好。任何想法为什么这样一个概念上简单的问题,很难实现?这些都是一些非常密集的matlab行... – John