简体   繁体   English

在Matlab中操作没有for循环的矩阵

[英]Manipulate matrix without for loops in Matlab

I'm working in Matlab. 我在Matlab工作。 I have a colored image in a matrix called im1. 我在一个名为im1的矩阵中有一个彩色图像。 I need to make all black pixels as white without altering other pixels. 我需要将所有黑色像素都设为白色而不改变其他像素。 How can I do this without for loop? 如果没有for循环,我怎么能这样做? This code takes a good 10s to execute on a large image. 此代码需要很长的10秒才能在大图像上执行。

for i=1:h
for j=1:w
    if im1(i,j,:)==0
        im1(i,j,:)=255;
    end
end
end

I can think of two approaches using logical indexing. 我可以想到使用逻辑索引的两种方法。

Approach 1 - 方法1 -

im1(repmat(all(im1==0,3),[1 1 size(im1,3)]))=255

Approach 2 - 方法2 -

im1(bsxfun(@and,all(im1==0,3),im1==0))=255

It would be interesting to see which one is more efficient. 看看哪一个更有效率会很有趣。

try this 尝试这个

[height, width, dim_3] = size(im1);
[row col] = find(im1(:,:,1) == 0 & im1(:,:,2) == 0 & im1(:,:,3) == 0);
im1(sub2ind([height, width, dim_3],repmat(row,dim_3,1),repmat(col,dim_3,1),repmat((1:dim_3)',numel(row),1))) = 255;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM