Main Content

使用二元直方图进行颜色分析

此示例说明如何调整二元直方图的色阶,以显示与 bin 有关的更多详细信息。

加载图像 peppers.png,这张彩色照片显示了几种辣椒和其他一些蔬菜。8 位无符号整数数组 rgb 包含图像数据。

rgb = imread('peppers.png');
imshow(rgb)

Figure contains an axes object. The axes object contains an object of type image.

为每个像素的红、绿 RGB 值绘制二元直方图,以可视化形式呈现颜色分布。

r = rgb(:,:,1);
g = rgb(:,:,2);
b = rgb(:,:,3);
histogram2(r,g,'DisplayStyle','tile','ShowEmptyBins','on', ...
    'XBinLimits',[0 255],'YBinLimits',[0 255]);
axis equal
colorbar
xlabel('Red Values')
ylabel('Green Values')
title('Green vs. Red Pixel Components')

Figure contains an axes object. The axes object with title Green vs. Red Pixel Components, xlabel Red Values, ylabel Green Values contains an object of type histogram2. This object represents g vs. r.

此直方图明显趋向于色阶底部,原因是有些 bin 的计数很大。这导致大部分 bin 在颜色图中显示为第一种颜色,即蓝色。如果没有提供更多详细信息,很难得出关于哪种颜色更占主导性的结论。

要查看更多详细信息,请通过将坐标区的 CLim 属性设置为介于 0 和 500 之间的范围,重新调整直方图的色阶。其结果就是直方图中计数达到 500 或以上的 bin 在颜色图中显示为最后一种颜色,即黄色。由于大部分 bin 的计数在这个较小范围内,因此所显示的 bin 的颜色变化较大。

ax = gca;
ax.CLim = [0 500];

Figure contains an axes object. The axes object with title Green vs. Red Pixel Components, xlabel Red Values, ylabel Green Values contains an object of type histogram2. This object represents g vs. r.

使用类似的方法可以比较红色与蓝色以及绿色与蓝色的主导性。

histogram2(r,b,'DisplayStyle','tile','ShowEmptyBins','on',...
    'XBinLimits',[0 255],'YBinLimits',[0 255]);
axis equal
colorbar
xlabel('Red Values')
ylabel('Blue Values')
title('Blue vs. Red Pixel Components')
ax = gca;
ax.CLim = [0 500];

Figure contains an axes object. The axes object with title Blue vs. Red Pixel Components, xlabel Red Values, ylabel Blue Values contains an object of type histogram2. This object represents b vs. r.

histogram2(g,b,'DisplayStyle','tile','ShowEmptyBins','on',...
    'XBinLimits',[0 255],'YBinLimits',[0 255]);
axis equal
colorbar
xlabel('Green Values')
ylabel('Blue Values')
title('Green vs. Blue Pixel Components')
ax = gca;
ax.CLim = [0 500];

Figure contains an axes object. The axes object with title Green vs. Blue Pixel Components, xlabel Green Values, ylabel Blue Values contains an object of type histogram2. This object represents b vs. g.

在每种情况下,蓝色都是最不占主导性的颜色信号。看看所有这三个直方图,红色似乎为主导颜色。

在 RGB 颜色空间中创建一个颜色直方图,对结果进行确认。对于所有这三个颜色分量,较小的 RGB 值都有峰值。但相比其他任何分量,100 以上的值更多出现在红色分量中。

histogram(r,'BinMethod','integers','FaceColor','r','EdgeAlpha',0,'FaceAlpha',1)
hold on
histogram(g,'BinMethod','integers','FaceColor','g','EdgeAlpha',0,'FaceAlpha',0.7)
histogram(b,'BinMethod','integers','FaceColor','b','EdgeAlpha',0,'FaceAlpha',0.7)
xlabel('RGB value')
ylabel('Frequency')
title('Color histogram in RGB color space')
xlim([0 257])

Figure contains an axes object. The axes object with title Color histogram in RGB color space, xlabel RGB value, ylabel Frequency contains 3 objects of type histogram.

另请参阅

|