Image matlab中基于bitshift的RGB直方图

Image matlab中基于bitshift的RGB直方图,image,matlab,image-processing,histogram,bit-shift,Image,Matlab,Image Processing,Histogram,Bit Shift,我试图在Matlab中创建一个mozaic图像。该数据库主要由RGB图像和一些灰度图像组成 我需要计算RGB图像的直方图,就像Wikipedia文章中关于的例子一样,并考虑使用Matlab中的bitshift操作符来组合R、G和B通道 nbins = 4; nbits = 8; index = bitshift(bitshift(image(:,:,1), log2(nbins)-nbits), 2*log2(nbins)) + ... + bitshift(bitsh

我试图在Matlab中创建一个mozaic图像。该数据库主要由RGB图像和一些灰度图像组成

我需要计算RGB图像的直方图,就像Wikipedia文章中关于的例子一样,并考虑使用Matlab中的bitshift操作符来组合R、G和B通道

nbins = 4;
nbits = 8;

index = bitshift(bitshift(image(:,:,1), log2(nbins)-nbits), 2*log2(nbins)) + ...
            + bitshift(bitshift(image(:,:,2), log2(nbins)-nbits), log2(nbins)) + ...
            + bitshift(image(:,:,3), log2(nbins)-nbits) + 1;
索引现在是一个与图像大小相同的矩阵,其索引对应于像素值的bin

如何将该矩阵中所有唯一值的出现次数相加,以获得RGB图像的直方图

有没有比bitshift更好的方法来计算RGB图像的直方图?

计算索引
bitshift
运算符似乎可以执行此操作。我个人要做的是创建一个查找关系,将RGB值与bin值关联起来。首先,您必须计算出每个维度中需要多少个箱子。例如,假设我们希望每个频道有8个垃圾箱。这意味着我们总共有512个箱子。假设每个通道有8位,您将生成一个关系,创建如下索引:

% // Figure out where to split our bins
accessRed = floor(256 / NUM_RED_BINS);
accessGreen = floor(256 / NUM_GREEN_BINS);
accessBlue = floor(256 / NUM_BLUE_BINS);

%// Figures out where to index the histogram
redChan = floor(red / accessRed);
greenChan = floor(green / accessGreen);
blueChan = floor(blue / accessBlue);

%// Find single index
out = 1 + redChan + (NUM_RED_BINS)*greenChan + (NUM_RED_BINS*NUM_GREEN_BINS)*blueChan;
这假设我们已将频道分为
红色
绿色
蓝色
。我们还将索引偏移1,因为MATLAB索引数组从1开始。这对我来说更有意义,但是
bitshift
操作符看起来效率更高

关于你的问题 现在,假设索引存储在
index
中,您可以使用
accumarray
功能来帮助您实现这一点
accumarray
接收阵列中的一组位置,以及每个位置的“权重”
accumarray
将找到相应的位置和权重,并将它们聚合在一起。在您的情况下,可以使用
sum
accumarray
不仅仅限于
sum
。您可以使用任何提供1对1关系的操作。例如,假设我们有以下变量:

index =

 1
 2
 3
 4
 5
 1
 1
 2
 2
 3
 3

weights = 

 1
 1
 1
 2
 2
 2
 3
 3
 3
 4
 4
accumarray
将要做的是针对
权重的每个值
,查看
索引
中的相应值,并将该值累加到相应的插槽中

因此,通过这样做,您将获得(确保确保
索引
权重
向量):

如果您看一看,所有值为1的索引,
权重
中共享相同索引1的任何值都将被汇总到
out
的第一个插槽中。我们有三个值:1、2和3。类似地,对于指数2,我们有1,3和3的值,这给了我们7

现在,为了将其应用到应用程序中,给定您的代码,您的索引看起来像是从1开始的。要计算图像的直方图,我们只需将所有权重设置为1,然后使用
accumarray
累积条目。因此:

%// Make sure these are column vectors
index = index(:);
weights = ones(numel(index), 1);

%// Calculate histogram
h = accumarray(index, weights);
%// You can also do:
%// h = accumarray(index, 1); - This is a special case if every value
%//                             in weights is the same number
accumarray
的行为默认调用
sum
。这应该会给你你所需要的。此外,如果有任何缺失值的索引(例如,假设索引矩阵中缺失2的索引),
accumarray
将在聚合时方便地在此位置放置一个零。有道理吧


祝你好运

指数从1开始,因为我在计算指数时加1;)Accumarray是我想要的功能。谢谢你给出了一个很好的解释性答案!:)酷。我编辑了我的帖子来反映这一点。不客气。祝你好运
%// Make sure these are column vectors
index = index(:);
weights = ones(numel(index), 1);

%// Calculate histogram
h = accumarray(index, weights);
%// You can also do:
%// h = accumarray(index, 1); - This is a special case if every value
%//                             in weights is the same number