OpenCV-Python官方教程-15-直方图的计算、绘制与分析

  • 什么是直方图呢?
    通过直方图你可以对整幅图像的灰度分布有一个整体的了解。直方图的 x 轴是灰度值(0 到 255),y 轴是图片中具有同一个灰度值的点的数目。直方图其实就是对图像的另一种解释,通过直方图我们可以对图像的对比度,亮度,灰度分布等有一个直观的认识。
  • 统计直方图
    函数 cv2.calcHist (images,channels,mask,histSize,ranges)可以帮助我们统计一幅图像的直方图。其中,(1)images是原图,当传入函数时应该用中括号[]括起来,例如:[img]。
    (2)channels:同样需要中括号括起来。如果传入的时灰度图,它就是[0];如果是彩色图像的话,传入的参数就可以是[0],[1],[2]它们分别对应通道B,G,R。
    (3)mask:掩膜图像。要统计整幅图像的直方图就把它设置成None。
    (4)histSize:BIN的数目。也需要用[]括起来,如:[256]。
    (5)ranges:像素值范围,通常为[0,256]。
import cv2
import numpy as np
img = cv2.imread('x.png',0)
hist = cv2.calcHist([img],[0],None,[256],[0,256])
print (hist.shape)
# print (hist)
#img.ravel()将图像转为一维数组,这里没有中括号
hist,bins = np.histogram(img.ravel(),256,[0,256])
print (hist.shape)
print (len(bins))

(256, 1)
(256,)
257

hist 是一个 256x1 的数组,每一个值代表了灰度值对应的像素点数目。Numpy 中的函数 np.histogram() 也可以帮
我们统计直方图。hist 与上面计算的一样。但是这里的 bins 是 257,因为 Numpy 计算bins 的方式为:0-0.99,1-1.99,2-2.99 等。所以最后一个范围是 255-255.99。为了表示它,所以在 bins 的结尾加上了 256。
cv2.calcHist() 函数要比 np.histogram() 快 40 倍。所以坚持使用OpenCV 函数。

  • 绘制直方图
    使用 Matplotlib Matplotlib 中有直方图绘制函数:matplotlib.pyplot.hist()它可以直接统计并绘制直方图。你应该使用函数 calcHist() 或 np.histogram()统计直方图。

1.灰度直方图

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('apple.jpg',0)
plt.hist(img.ravel(),256,[0,256])
plt.show()

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

可以只使用 matplotlib 的绘图功能,这在同时绘制多通道(BGR)的直方图,很有用。

2.BGR三通道直方图

import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('apple.jpg')
color = ('b','g','r')
# 对一个列表或数组既要遍历索引又要遍历元素时,
#使用内置enumerate函数会有更加直接和优美
#enumerate会将数组或列表组成一个索引序列
#是我们再获取索引内容的时候更加方便
for i,col in enumerate(color):
    histr = cv2.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color=col)
    plt.xlim([0,256])
plt.show()

在这里插入图片描述
3.使用掩膜

img = cv2.imread('apple.jpg',0)
#creat a mask
mask = np.zeros(img.shape,dtype=np.uint8)
mask[100:200,100:200] = 255
masked_img = cv2.bitwise_and(img,img,mask=mask)
#calculate histogram with mask and without mask
#check third argument for mask
hist_full = cv2.calcHist([img],[0],None,[256],[0,256])
hist_mask = cv2.calcHist([img],[0],mask,[256],[0,256])
plt.subplot(221),plt.imshow(img,'gray')
plt.subplot(222),plt.imshow(mask,'gray')
plt.subplot(223),plt.imshow(masked_img,'gray')
plt.subplot(224),plt.plot(hist_full),plt.plot(hist_mask)
plt.xlim([0,256])
plt.show()

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值