openCV+Python 数字图像处理(6)——图像直方图(histogram)

1.基本概念

图像直方图是不同像素值范围的像素个数统计图,无空间信息。
在这里插入图片描述

2.API 介绍

  • (1)利用matplotlib画直方图
plt.hist(x: Any,  bins: Any = None, range: Any = None, density: Any = None, weights: Any = None, cumulative: bool = False, bottom: Any = None, histtype: str = 'bar', align: str = 'mid', orientation: str = 'vertical', rwidth: Any = None, log: bool = False, color: Any = None, label: Any = None, stacked: bool = False, normed: Any = None,
*, data: Any = None, **kwargs: Any)
属性说明类型
x数据数值类型
bins条形数int
rangex轴的范围
范围之外的将被舍弃。
数组元组(起,终)
density是否以密度形式显示bool
bottomy轴的起始位置数值类型
histtype线条类型‘bar’,方形;
“barstacked”:柱形,
“step”:“未填充线条”
“stepfilled”:“填充线条”
  • (2)利用openCV画直方图
cv2.calcHist(images: Any, channels: Any, mask: Any, histSize: Any, ranges: Any, hist: Any = None, accumulate: Any = None)

images: 表示输入图像,传入时应该用中括号 [ ] 括起来
channels: 这个值也得用 [ ] 传入。
mask: 表示掩膜图像。如果统计整幅图,那么为None。主要是如果要统计部分图的直方图,就得构造相应的掩膜来计算。
histSize 表示灰度级的个数,需要中括号,比如[256]

3.代码示例

import cv2
from matplotlib import pyplot as plt
def show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
one = cv2.imread('E:/PycharmProjects/one.jpg')
show('img', one)

# 1.matplotlib画直方图
def plt_his(img):
    plt.hist(img.ravel(), 256, [0, 256]) #ravel功能是将多维数组降为一维数组
    plt.show()

plt_his(one)

# 2.利用openCV的API画三个通道的直方图
def img_his(img):
    color = ('blue', 'green', 'red')  #画笔颜色的值可以为大写或小写或只写首字母或大小写混合
    for i, color in enumerate(color): #enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据,一般用在 for 循环当中。
        hist = cv2.calcHist([img], [i], None, [256], [0, 256])
        plt.plot(hist, color=color)
        plt.xlim([0, 256])
    plt.show()

img_his(one)

cv2.destroyAllWindows()

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标和数据,一般用在 for 循环当中。

4.结果展示

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值