Matlab 从三维数组中的矩阵匹配值
我正在尝试匹配图像中的RGB值Matlab 从三维数组中的矩阵匹配值,matlab,image-processing,matrix,multidimensional-array,vectorization,Matlab,Image Processing,Matrix,Multidimensional Array,Vectorization,我正在尝试匹配图像中的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;
% 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]
在此图像中,只有一个RGB值与RGB集相匹配,即[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
我已经编写了这段代码,但对于较大的图像来说速度非常慢
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
速度更快的解决方案是什么?您可以在颜色上循环,这比在每个像素上循环快得多
% Set up your colours into the 3rd dimension, so they match along the same axis
RGB3D = reshape(RGBset,[],1,3);
% Loop over them
for ii = 1:size(RGB3D, 1)
% See if all 3 members of the colour match any pixel
matched = all(ismember(img, RGB3D(ii,:,:)),3)
if any(matched)
disp(matched)
disp(['matched color: ' num2str(ii)]);
% do something else with the matched pixels
end
end
可以使用和替换循环:
这将创建一个3列矩阵
img2
,其中每行对应于img
中的一个像素。这样,ismember(…,'rows')
就可以以矢量化的方式应用。然后根据需要对获得的结果进行重塑。我们可以将每个RGB三元组减少为一个标量,我们将对RGBset
和img
执行此操作。这将分别将它们减少为2D
和1D
矩阵。我们称之为降维。随着数据的减少,我们实现了内存效率,有望提高性能
因此,包含这些基础的解决方案看起来是这样的-
% 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), []);
矢量化解决方案的基准测试
基准测试代码-
% 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
基准输出-
--------------------- Reshape + Permute ------------------
Elapsed time is 3.101870 seconds.
--------------------- Dim reduction ------------------
Elapsed time is 0.031589 seconds.
谢谢你的回答。它是否给出所需的
匹配的矩阵?很抱歉,我无法理解每个matched
矩阵是您图像的大小,对于与RGBset
矩阵的ii
行中的颜色匹配的像素,true
。路易斯的回答很可能是一个很快的好主意,而且速度也很快!谢谢你的回答。你能详细说明一下降维的工作原理吗?@Likeunknown在文章的开头添加了一些评论。看看那些!
--------------------- Reshape + Permute ------------------
Elapsed time is 3.101870 seconds.
--------------------- Dim reduction ------------------
Elapsed time is 0.031589 seconds.