Matlab:根据2个其他矩阵中的值创建RGB矩阵

时间:2016-09-17 15:06:08

标签: image matlab matrix rgb

抱歉这个愚蠢的问题。我想根据两个矩阵中的值在matlab中定义RGB图像。 e.g:

  A       B         comparision RGB
|1 0|   |1 0|  -->  |green    red  |
|1 0|   |0 1|  -->  |purple   cyan |

以下代码可以胜任,但非常慢(我知道):

comparision = uint8(zeros([H,W, 3])); 
for i=1:H
  for j=1:W
    if (A(i,j)==1 && B(i,j)==1) %tp
        comparision (i,j,:) = [113 140 0];
    end
    if (A(i,j)==0 && B(i,j)==0) %tn
        comparision (i,j,:) = [200 40 41];
    end
    if (A(i,j)==0 && B(i,j)==1) %fp (false alarm)
        comparision (i,j,:) = [10 130 120];
    end
    if (A(i,j)==1 && B(i,j)==0) %fn 
        comparision (i,j,:) = [120 20 120];
    end
  end
end

我非常确定使用matlab矩阵功能可以更快地完成它。不幸的是,我总是对matlab表示法有点困惑,并没有成功的谷歌搜索: - /。

我试过这样的事情:

comparision(LabelImage1 == 1 & LabelImage2 == 1) = [255 0 0]

但它没有成功。

任何人都可以帮助我更快吗?提前致谢

1 个答案:

答案 0 :(得分:5)

您可以将值A, B转换为索引,然后使用ind2rgb将这些索引映射到颜色:

indImg = uint8(A.*2 + B);   % generate indices [0..3]
cMap = [1, 0, 0;   % red
        0, 1, 1;   % cyan
        1, 0, 1;   % magenta
        0, 1, 0];  % green
comparison = ind2rgb(indImg, cMap);   % convert indices to cMap RGB values

indexed image是每个像素值是color map的(整数)索引而不是RGB或灰度值的索引。您可以使用imshow直接显示此类图像:

imshow(indImg, cMap)

uint8uint16类型的索引图像是我所知道的MATLAB使用基于0的索引的情况,这就是为什么上面的索引是[0..3]以及为什么@Divakar的评论中的备用解决方案必须使用indImg+1

函数ind2rgb只需获取每个索引,并用3D RGB值替换它们,每个值都类似于permute(cMap(index), [1 3 2])

为了提高速度,这里有一个有趣的选择:

comparison = cat(3, ~B, B, xor(A,B));

(您可能需要将其转换为double,我不确定...)

Here是使用这种方法,我的原始代码和Divakar的建议对ideone进行的简单比较。由于在线翻译的内存限制,我无法将图像大小设置在2000x2000以上,但这种方法似乎至少是其他方法的两倍。

相关问题