python opencv 绘制直方图统计及画图方法

python opencv 绘制颜色直方图(曲线)的方法

python 中绘制颜色直方图的方法很多,查看网友资料后在这自己做个总结

  • numpy有histogram(),bincount(()。其中bincount()比np.histogram()快(大约10X)得多。 所以对于一维直方图,你可以更好地尝试。 不要忘记在np.bincount中设置minlength = 256。
    例如,hist = np.bincount(img.ravel(),minlength = 256)
  • OpenCV功能比np.histogram()快大约40X
  • matplotlib有matplotlib.pyplot.hist( )

matplotlib.pyplot.hist( )

在这里插入图片描述

来源:matplotlib api解释

x:(n,) array or sequence of (n,) arrays 
指定要绘制直方图的数据,必须是一维数组.使用.ravel()将你的通道值转为一维数组

bins:integer or sequence or ‘auto’, optional
指定直方图条形的个数,integer或auto,也可以不设置.举例[1,2,3,4],则第一个柱为取值[1,2),一次类推,最后一个是取值[3,4].默认taken from the rcParam hist.bins.

range:tuple or None, optional
数组或者不给.给出数组将指定直方图数据的上下界,超出范围的舍弃.不设置的话包含绘图数据的最大值和最小值;默认为None

density : boolean, optional
如果设为True,则高度值为密度,总体密度为1.默认或False,高度为数量.之前版本的为 参数名为normed

weights:(n, ) array_like or None, optional
为x每一个数据点设置权重,方法为设置与x相同的一组数组,权重和x中的元素一一对应.其实density=True也就是利用了这个方法;默认为None

cumulative:boolean, optional
是否需要计算累计频数(density默认)或频率(density=True).如果你设置了density为1的话,就能看到最后一条的柱子高度为1;默认False

bottom:array_like, scalar, or None
可以是一个x相同元素的数组或者一个值,为直方图的每个条形添加基准线,也就是给每个x元素值加上一个值后画出来,默认为0;

histtype: {‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}, optional
指定直方图的类型,默认为bar,除此还有'barstacked', 'step', 'stepfilled';

align:{‘left’, ‘mid’, ‘right’}, optional
设置条形边界值的对其方式,也就是你的x轴刻度的位置.默认为mid,除此还有'left' 'mid'和'right';

orientation:{‘horizontal’, ‘vertical’}, optional
设置直方图的摆放方向,'horizontal'为水平,'vertical'为垂直.默认为垂直方向;

rwidth:scalar or None, optional
设置直方图条形宽度的百分比;

log:boolean, optional
是否需要对绘图数据进行log变换;

color:color or array_like of colors or None, optional
设置直方图的填充色;

label:string or None, optional
设置直方图的标签,可通过plt.legend()展示带标签的图形;

stacked:boolean, optional
如果是True,当有多个数据时,直方图柱子堆叠摆放,(我也不懂)默认为Flase,邻近摆放;

返回:

n,bins,patches

代码示例

import matplotlib.pyplot as plt
"""
想在同一个图里绘制多条柱状图,只要把color设置不一样就行,不然会被覆盖.或者使用plt.subplot(131)制定图形被分成1行3块之类
"""
img = cv2.imread('hw2_awb.jpg')
b, g, r = cv2.split(img)
# 设置坐标轴标签和标题
#plt.title('直方图')
#plt.xlabel('x')
#plt.ylabel('y')
# 去除图形顶部边界和右边界的刻度
#plt.tick_params(top='off', right='off')
# 去除图像的x,y刻度
#plt.axis('off')
# 设置 x 轴的刻度大小
#plt.xticks(np.arange(1,255,10))
# 设置 X 轴的网格线,风格为 点画线
#plt.grid(axis='x',linestyle='-.')
b_hist = plt.hist(img[:, :, 0].ravel(), bins=50, color='b')
#用B值直接一维化也可以
# b_hist = plt.hist(b.ravel(), bins=50, color='r')
# 显示图例
#plt.legend()
plt.show()

cv2.calcHist()计算直方图

在这里插入图片描述

cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])

calcHist()里边格式要求比较严,前几个不能默认,都需要自己填写。calcHist()的好处是可以添加掩膜

来源:opencv api
  images: 
  Source arrays. They all should have the same depth, CV_8U or CV_32F , and the same size. Each of them  can 
  have an arbitrary number of channels.
  图片列表,每个通道要格式相同,是个数组,单个通道也可以直接写上
 
  channel:
  List of the dims channels used to compute the histogram. The first array channels are numerated from 0 to 
  images[0].channels()-1 , the second array channels are counted from images[0].
  channels() to images[0].channels() + images[1].channels()-1, and so on.
  需要计算直方图的通道。[0]表示计算通道0的直方图,[0,1,2]表示计算通道0,1,2所表示颜色的直方图
  
  mask:
  Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size as images[i] . 
  The non-zero mask elements mark the array elements counted in the histogram.
  蒙版,只计算值>0的位置上像素的颜色直方图,取None表示无蒙版 
  
  histSize:
  Array of histogram sizes in each dimension
  每个维度上直方图的大小,[8]表示把通道0的颜色取值等分为8份后计算直方图 ,[256]表示分为256份
  
  ranges:
  Array of the dims arrays of the histogram bin boundaries in each dimension. 
  每个维度的取值范围,[lower0, upper0, lower1, upper1, ...],lower可以取到,upper无法取到 
   
  hist:Output histogram, which is a dense or sparse dims -dimensional array. 
  保存结果的ndarray对象 
   
  accumulate:Accumulation flag. If it is set, the histogram is not cleared in the beginning when it is allocated. This
  feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time.
  是否累积,如果设置了这个值,hist不会被清零,直方图结果直接累积到hist中,或者有利于及时更新直方图
img=cv2.imread('11.jpg')
img_B = cv2.calcHist([img], [0], None, [256], [0, 256]) 
plt.plot(img_B, label='B', color='b')                #曲线
#plt.legend() 
#x轴x的取值范围,xticks()是x的刻度
#plt.xlim([0, 256])
#plt.title('B') 
#plt.xlabel('Bins') 
#plt.ylabel('Pixels') 
plt.show()

numpy.histogram()计算直方图

numpy.histogram(a, bins=10, range=None, normed=False, weights=None, density=None)[source]

Compute the histogram of a set of data.
Parameters:	

a : array_like
    Input data. The histogram is computed over the flattened array.
    a是要测的一维数组

bins : int or sequence of scalars, optional
    If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence,
    it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths.
    bins是统计区间的个数,即对统计范围的等分数,默认为10

range : (float, float), optional
    The lower and upper range of the bins. If not provided, range is simply (a.min(), a.max()). Values outside 
    the range are ignored.
    range统计的范围,超出范围的数被舍去

normed : bool, optional
    This keyword is deprecated in Numpy 1.6 due to confusing/buggy behavior. 
    It will be removed in Numpy 2.0. Use the density keyword instead. 
    If False, the result will contain the number of samples in each bin. 
    If True, the result is the value of the probability density function at the bin,  normalized 
    such that the integral over the range is 1. 
    Note that this latter behavior is known to be buggy with unequal bin widths; use density instead.
    numpy2.0是density,默认统计频数,设为True就是统计密度
    
weights : array_like, optional
    An array of weights, of the same shape as a. Each value in a only contributes its associated weight towards 
    the bin count (instead of 1). If normed is True, the weights are normalized, so that 
    the integral of the density over the range remains 1
    a的权重
    
density : bool, optional
    If False, the result will contain the number of samples in each bin. 
    If True, the result is the value of the probability density function at the bin, normalized
    such that the integral over the range is 1. Note that the sum of the histogram values 
    will not be equal to 1 unless bins of unity width are chosen; 
    it is not a probability mass function. Overrides the normed keyword if given.
    统计频数还是密度的标志,注意直方图和不一定为1,除非制定

Returns:

hist : array
    The values of the histogram. See normed and weights for a description of the possible semantics.
    直方图的统计结果组成的数组

bin_edges : array of dtype float
    Return the bin edges (length(hist)+1).
    数组,存储每个统计区间的起点。range为[0,256]时,bins有257个元素,因为Numpy计算bins是以0-0.99,1-1.99等,
    所以最后一个是255-255.99。为了表示这一点,他们还在bins的末端添加了256

代码示例

img = cv2.imread('hw2_awb.jpg')
b, g, r = cv2.split(img)
print(img.shape)
#plt.figure()
# img_B = cv2.calcHist([img], [0], None, [256], [0, 256])
#r_hist = plt.hist(b.ravel(), bins=256, color='r')    #柱状图
plt.show()
plt.figure()
hists,bins=np.histogram(b.flatten(),256,[0,256])  #和注释掉的绘图效果一样,不过是曲线
plt.plot(hists,color='r')
plt.show()
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiangz201

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值