Image 如何利用矢量化计算图像面片的方差
我有一个560*560*3的图像文件,我想把图像分成许多8*8的小块,然后计算每个小块的方差。使用Matlab或倍频程计算每个图像块的方差的矢量化方法是什么?使用Image 如何利用矢量化计算图像面片的方差,image,matlab,matrix,vectorization,Image,Matlab,Matrix,Vectorization,我有一个560*560*3的图像文件,我想把图像分成许多8*8的小块,然后计算每个小块的方差。使用Matlab或倍频程计算每个图像块的方差的矢量化方法是什么?使用mat2cell和cellfun。我假设图像存储在矩阵M中。你需要的是单元格平均值和单元格平均值的方差。这是图像压缩方案吗 PatchSize = 8; %These have the 8x8 patches (although you can change this using PatchSize) RedPortion = mat
mat2cell
和cellfun
。我假设图像存储在矩阵M
中。你需要的是单元格平均值和单元格平均值的方差。这是图像压缩方案吗
PatchSize = 8;
%These have the 8x8 patches (although you can change this using PatchSize)
RedPortion = mat2cell(M(:,:,1), PatchSize*ones(size(M,1)/PatchSize, 1), PatchSize*ones(size(M,2)/PatchSize, 1));
GreenPortion = mat2cell(M(:,:,2), PatchSize*ones(size(M,1)/PatchSize, 1), PatchSize*ones(size(M,2)/PatchSize, 1));
BluePortion = mat2cell(M(:,:,3), PatchSize*ones(size(M,1)/PatchSize, 1), PatchSize*ones(size(M,2)/PatchSize, 1));
% The mean(x(:)) takes the mean of the 8x8 cell
RedMean = cellfun(@(x) mean(x(:)), RedPortion, 'uni', 0);
GreenMean = cellfun(@(x) mean(x(:)), GreenPortion, 'uni', 0);
BlueMean = cellfun(@(x) mean(x(:)), BluePortion, 'uni', 0);
% The x - mean(x(:)) takes the variance from the mean of the 8x8 cell
RedVariance = cellfun(@(x) x - mean(x(:)), RedPortion, 'uni', 0);
GreenVariance = cellfun(@(x) x - mean(x(:)), GreenPortion, 'uni', 0);
BlueVariance = cellfun(@(x) x - mean(x(:)), BluePortion, 'uni', 0);
您可以使用
nfilter
功能:
fun = @var;
B = nlfilter(A, [8 8], fun);
顺便说一下,如果您想要3x3图像修补程序,可以使用stdfilt
。剩下的就是在图像上应用一个正方形:
s = stdfilt(im);
s = s.*s;
一种矢量化方法-
PSZ = 8; %// Patch size
[m,n,r] = size(A); %// Get size of image
%// Arrange each patch into columns of a 2D array
ptc = reshape(permute(reshape(A,PSZ,m/PSZ,PSZ,[]),[1 3 2 4]),PSZ^2,[])
%// Perform variance calculations for each column and reshape into a 3D array
out = reshape(sum(bsxfun(@minus,ptc,mean(ptc,1)).^2)/(PSZ^2-1),m/PSZ,n/PSZ,r)
样本运行-
投入:
>> A
A(:,:,1) =
1 4 5 0.19304 0.39711 0.010979
6 2 1 0.34164 0.37472 0.57326
9 0 3 0.9329 0.13111 0.78973
0.45032 0.37385 0.59497 0.39067 0.43504 0.23537
0.58247 0.58158 0.96216 0.27322 0.091513 0.44802
0.68664 0.11612 0.18578 0.15195 0.61463 0.56936
....
>> PSZ %//(patch-size)
PSZ =
3
运行代码后:
>> out
out(:,:,1) =
8.2778 0.091761
0.066907 0.032665
....
验证第一个修补程序的结果:
1 4 5
6 2 1
9 0 3
>> var([1 4 5 6 2 1 9 0 3]) %// With MATLAB's var function on the first patch
ans =
8.2778
从,输出,我们有
out(1,1,1)
是8.2778
补丁不是8x8,而是8x3,对吗?考虑到三种颜色成分,您如何定义差异?cellfun
基本上是在引擎盖下使用一个循环。对于循环(如果有的话),我不确定这比快多少。