图像处理之图像直方图

直方图绘制
目的:直方图是对图像像素的统计分布,它统计了每个像素(0到255)的数量。
函数:cv2.calcHist(images, channels, mask, histSize, ranges)
参数说明:参数1:待统计图像,需用中括号括起来; 参数2:待计算的通道; 参数3:Mask,这里没有使用,所以用None。 参数4:histSize,表示直方图分成多少份; 参数5:是表示直方图中各个像素的值,[0.0, 256.0]表 示直方图能表示像素值从0.0到256的像素。直方图是 对图像像素的统计分布,它统计了每个像素(0到255) 的数量。
Python代码实现
直方图绘制 方法1
from matplotlib import pyplot as plt
import cv2

girl = cv2.imread("girl.jpg")
cv2.imshow("girl", girl)
# girl.ravel()函数是将图像的三位数组降到一维上去,
#256为bins的数目,[0, 256]为范围
plt.hist(girl.ravel(), 256, [0, 256])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
效果展示:在这里插入图片描述在这里插入图片描述
直方图绘制 方法2
from matplotlib import pyplot as plt
import cv2
import numpy as np
img = cv2.imread('girl.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

plt.imshow(img_gray, cmap=plt.cm.gray)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])


plt.figure()
plt.title("Grayscale Histogram")
plt.xlabel("Bins")
plt.ylabel("# of Pixels")
plt.plot(hist)
plt.xlim([0, 256])
plt.show()
效果展示:在这里插入图片描述
三通道直方图绘制
Python代码
from matplotlib import pyplot as plt
import cv2
girl = cv2.imread("girl.jpg")
cv2.imshow("girl", girl)
color = ("b", "g", "r")
#使用for循环遍历color列表,enumerate枚举返回索引和值
for i, color in enumerate(color):
    hist = cv2.calcHist([girl], [i], None, [256], [0, 256])
    plt.title("girl")
    plt.xlabel("Bins")
    plt.ylabel("num of perlex")
    plt.plot(hist, color = color)
    plt.xlim([0, 260])
plt.show()
cv2.waitKey(0)
cv2.destroyAllWindows()
效果展示:在这里插入图片描述
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值