子块矩阵的直方图

Histogram of subblock matrix

给定一些矩阵,我想将其分成大小为 2-by-2 的块,并显示每个块的直方图。以下是我为解决该问题而编写的代码,但我生成的直方图之和与整个矩阵的直方图并不相同。实际上,块的直方图总和是我预期的两倍。我做错了什么?

im =[1 1 1 2 0 6 4 3; 1 1 0 4 2 9 1 2; 1 0 1 7 4 3 0 9; 2 3 4 7 8 1 1 4; 9 6 4 1 5 3 1 4; 1 3 5 7 9 0 2 5; 1 1 1 1 0 0 0 0; 1 1 2 2 3 3 4 4];
display(imhist(im));
[r c]=size(im);
bs = 2; % Block Size (8x8)
nob=[r c ]./ bs; % Total number of Blocks
% Dividing the image into 8x8 Blocks
kk=0;
for k=1:nob/2
    for i=1:(r/bs)
        for j=1:(c/bs)
            Block(:,:,kk+j)=im((bs*(i-1)+1:bs*(i-1)+bs),(bs*(j-1)+1:bs*(j-1)+bs));
            count(:,:,kk+j)=sum(sum(sum(hist(Block(:,:,kk+j)))));
            p=sum(count(:,:,kk+j));
        end
        kk=kk+(r/bs);
    end
end

它们不相同的原因是因为您对 im 使用 imhist 而对块使用 hist。 Hist 根据你的数据范围将数据分成 10 个不同的 bin,imhist 根据图像类型将数据分开。由于您的数组是双精度数,因此 imhist bins 从 0 到 1.0 这就是为什么您的 imhist 只有 0 和 1 的值。hist 根据您的数据范围生成 bins,因此它实际上会根据您传入的值略有变化. 所以你不能简单地将垃圾桶加在一起。即使它们是相同大小的向量 10x1 ,它们中的值也可能非常不同。在一组数据中,bin(1) 的范围可以是 1-5,但在另一组数据中,bin(1) 的范围可以是 1-500。

为了解决所有这些问题,我使用了 imhist,并将您的数据转换为 uint8。最后,我将两个直方图相减并得到零,这表明它们确实相同

im =uint8([1 1 1 2 0 6 4 3 ;
           1 1 0 4 2 9 1 2 ;
           1 0 1 7 4 3 0 9 ;
           2 3 4 7 8 1 1 4 ; 
           9 6 4 1 5 3 1 4 ; 
           1 3 5 7 9 0 2 5 ; 
           1 1 1 1 0 0 0 0 ; 
           1 1 2 2 3 3 4 4 ]); 
orig_imhist = imhist(im);
%% next thing
[r c]=size(im);
bs=2; % Block Size (8x8)
nob=[r c ]./ bs; % Total number of Blocks

%creates arrays ahead of time
block = uint8(zeros(bs,bs,nob(1)*nob(2)));
%we use 256, because a uint8 has 256 values, or 256 'bins' for the
%histogram
block_imhist = zeros(256,nob(1)*nob(2));
sum_block_hist = zeros(256,1);

% Dividing the image into 2x2 Blocks
for i = 0:nob(1)-1
   for j = 0:nob(2)-1

      curr_block = i*nob(1)+(j+1);
      %creates the 2x2 block
      block(:,:,curr_block) = im(bs*i+1:bs*i+ bs,bs*j+1:bs*j+ bs);

      %creates a histogram for the block
      block_imhist(:,curr_block) = imhist(block(:,:,curr_block));

      %adds the current histogram to the running sum
      sum_block_hist = sum_block_hist + block_imhist(:,curr_block);
   end
end
%shows that the two are the same
sum(sum(orig_imhist-sum_block_hist))

如果我的解决方案解决了您的问题,请将其标记为答案