子块矩阵的直方图

时间:2015-02-04 22:01:29

标签: matlab histogram

给定一些矩阵,我想将其划分为大小为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

1 个答案:

答案 0 :(得分:1)

它们不相同的原因是因为你使用imhist for im和hist作为块。 Hist根据您的数据范围将数据分成10个不同的区域,根据图像类型分类数据。由于您的阵列是双打的,因此imhist箱从0到1.0这就是为什么你的imhist只有0和1的值。hist根据你的数据范围产生箱子,所以它实际上会根据你传递的值略有变化所以你不能简单地将垃圾箱加在一起。即使它们是相同大小的矢量10x1,它们中的值也可能非常不同。在一个集合bin(1)中可以是1-5范围,但在另一组数据bin(1)中可以是1-500。

要修复我使用过的所有这些问题,并将您的数据转换为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))

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

相关问题