匹配三维数组中矩阵的值

Lik*_*own 4 matlab image-processing matrix vectorization multidimensional-array

我试图匹配图像中的RGB值.

         % R  G   B
RGBset = [ 3  9  12;
           4  8  13;
          11 13  13;
           8  3   2]

img(:,:,1) = [1   2   3
              6   5   4
              7   9   8
             10  11  12];

img(:,:,2) = [3  4  8;
              6  7  8;
             11 10  9;
             12 13 14];

img(:,:,3)= [3  7  2;
             4  9 10;
             5 11 12;
             6 13 14]
Run Code Online (Sandbox Code Playgroud)

在此图像中,只有一个RGB值与RGBset匹配[11,13,13],因此预期输出为:

[0  0  0;
 0  0  0;
 0  0  0;
 0  1  0]; % reshape(img(4,2,:),1,3) = [11, 13 13] is available in RGBset
           % no other RGB value is present in the image
Run Code Online (Sandbox Code Playgroud)

我已经制作了这个代码,但是对于较大的图像来说它非常慢.

matched= zeros(img(:,:,1));
for r=1:size(img(:,:,1),1)
    for c=1:size(img(:,:,2),2)
     matched(r,c)=ismember(reshape(img(r,c,:),1,3),RGBset,'rows');
    end
end
Run Code Online (Sandbox Code Playgroud)

更快的解决方案是什么?

Div*_*kar 5

我们可以减少每个RGB三元为标每我们会做这两个RGBsetimg.这将分别减少它们2D1D矩阵.我们称之为维数减少.通过这些减少的数据,我们实现了内存效率,并且希望能够带来性能提升.

因此,覆盖这些基地的解决方案看起来像这样 -

% Scaling array for dim reduction
s = [256^2, 256, 1].';

% Reduce dims for RGBset and img
RGBset1D = RGBset*s;
img1D = reshape(img,[],3)*s;

% Finally use find membership and reshape to 2D
out = reshape(ismember(img1D, RGBset1D), size(img,1), []);
Run Code Online (Sandbox Code Playgroud)

矢量化解决方案的基准测试

基准代码 -

         % R  G   B
RGBset = [ 3  9  12;
           4  8  13;
          11 13  13;
           8  3   2]

% Setup inputs
img = randi(255, 2000, 2000, 3);
img(3,2,:) = RGBset(4,:);

% Luis's soln
disp('--------------------- Reshape + Permute ------------------')
tic
img2 = reshape(permute(img, [3 1 2]), 3, []).';
matched = ismember(img2, RGBset, 'rows');
matched = reshape(matched, size(img,1), []);
toc

% Proposed in this post
disp('--------------------- Dim reduction ------------------')
tic
s = [256^2, 256, 1].';
RGBset1D = RGBset*s;
img1D = reshape(img,[],3)*s;
out = reshape(ismember(img1D, RGBset1D), size(img,1), []);
toc
Run Code Online (Sandbox Code Playgroud)

基准输出 -

--------------------- Reshape + Permute ------------------
Elapsed time is 3.101870 seconds.
--------------------- Dim reduction ------------------
Elapsed time is 0.031589 seconds.
Run Code Online (Sandbox Code Playgroud)