matlab - matlab中循环中矩阵子集的平均值

标签 matlab image-processing matrix mean subset

我使用一张我认为是矩阵的图像。

我想将 800 x 800 矩阵 (A) 转换为 400 x 400 矩阵 (B),其中 A 矩阵的 4 个单元格的平均值 = B 矩阵的 1 个单元格(我知道这不是正确的代码行):

B[1,1] =mean2(A[1,1 + 1,2 + 2,1 + 2,2]) 

整个矩阵依此类推...

B [1,2]=mean2(A[1,3 + 1,4 + 2,3 + 2,4 ])

我想:

1) 将 A 矩阵 reshape 为 2 x 320 000 矩阵,这样我就得到了需要彼此相邻平均的四个单元格,并且之后处理行号更容易。

Im4bis=reshape(permute(reshape(Im4,size(Im4,2),2,[]),[2,3,1]),2,[]);

2) 使用我需要平均(子集化)的 4 个单元格创建一个单元格数组并计算其平均值。这就是它不起作用的地方

I{1,160000}=ones,
for k=drange(1:2:319999)
    for n=1:160000
        I{n}=mean2(Im4bis(1:2,k:k+1));
    end
end

我创建了一个 400 x 400 个单元格的空矩阵(实际上是一个 1 x 160000 的向量),我想用平均值填充它,但我得到了一个 1 x 319 999 个单元格的矩阵,其中 2 个单元格中有一个是空的。

寻找光明

我的输入图像:

enter image description here

最佳答案

方法1

使用mat2cellcellfun

AC = mat2cell(A, repmat(2,size(A,1)/2,1), repmat(2,size(A,2)/2,1));

out = cellfun(@(x) mean(x(:)), AC);

方法2

使用 im2col

out = reshape(mean(im2col(A,[2 2],'distinct')),size(A)./2);

方法3

使用简单 for 循环

out(size(A,1)/2,size(A,2)/2) = 0;
k = 1;
for i = 1:2:size(A,1)
    l = 1;
    for j = 1:2:size(A,2)
        out(k,l) = mean(mean(A(i:i+1,j:j+1)));
        l = l+1;
    end
    k = k+1;
end

对输入图像进行测试:

A = rgb2gray(imread('inputImage.png'));

%// Here, You could use any of the method from any answers 
%// or you could use the best method from the bench-marking tests done by Divakar
out = reshape(mean(im2col(A,[2 2],'distinct')),size(A)./2);  

imshow(uint8(out));  

imwrite(uint8(out),'outputImage.bmp');

输出图像:

enter image description here

通过读取已写入的图像进行最终检查

B = imread('outputImage.bmp');

>> whos B

Name        Size              Bytes  Class    Attributes

B         400x400            160000  uint8              

关于matlab - matlab中循环中矩阵子集的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30263583/

相关文章:

java - 为什么在重写图像后我得不到相同的值?

matlab - 如何将 && 操作数求解为逻辑标量

visual-c++ - 如何从文件夹中访问多个图像

image-processing - 1000张图像的Python成像库叠加

R 真的很慢矩阵/data.frame 索引选择

c++ - 如何生成循环矩阵?

matlab - 我如何在 MATLAB 中随机选择矩阵的每一列中的一个元素?

matlab - For 循环求平均值?

algorithm - 获取 MATLAB 向量的子集

java - OpenCV for android 与 openCV for windows 的不同结果