如何用矢量化计算图像块的方差

时间:2015-05-30 17:54:11

标签: image matlab matrix vectorization

我有一个560 * 560 * 3的图像文件,我想将图像分成许多小的8 * 8补丁,然后计算每个补丁的方差。什么是用Matlab或Octave计算每个图像块的方差的矢量化方法?

3 个答案:

答案 0 :(得分:2)

您可以使用nfilter功能:

  fun = @var;
  B = nlfilter(A, [8 8], fun);

顺便说一句,如果你想要3x3图像补丁,可以使用stdfilt function。剩下的就是在图像上应用一个正方形:

  s = stdfilt(im);
  s = s.*s;

答案 1 :(得分:1)

使用mat2cellcellfun。我假设图像存储在矩阵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);

答案 2 :(得分:1)

一种矢量化方法 -

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