# coding: utf-8
# !/usr/bin/python
"""
@File : 直方图的计算,绘制与分析.py
@Author : jiaming
@Modify Time: 2020/2/6 14:35
@Contact :
@Version : 1.0
@Desciption : 计算直方图
绘制直方图
cv2.calcHist()
np.histogram()
"""
import os
import sys
import numpy as np
import cv2
import pprint
from matplotlib import pyplot as plt
rawPath = os.path.abspath(__file__)
currentFile = os.path.basename(sys.argv[0])
dataPath = rawPath[:rawPath.find(currentFile)] + r'static\\'
直方图
"""
直方图
通过直方图你可以对整幅图像的灰度分布有一个整体的了解。
x 轴是灰度值(0-255) y 轴是图片中具有同一个灰度值的点的数目。
"""
统计直方图
"""
统计直方图
使用 openCV 提供的函数 cv2.calcHist 可以帮助我们统计一幅图像的直方图。
cv2.calcHist(images, channels, mask, histSize, ranges, [,hist,[,accumulate]])
images: 原图像 uint8 float32 [img]
channels: 需要使用中括号括起来,它会告诉函数我们要统计哪副图像的直方图。灰度图:[0] 彩色图像的色彩通道:[0],[1],[2]
mask:掩模图像 要统计整幅图像的直方图就设置为 None
histSize: BIN的数目 [256], BINS:如果想知道某个灰度范围内像素点的数目,就可以将[0, 256]进行分组,取
每组的总和,每一个小组称为 BIN
ranges: 像素值的范围 通常为[0, 256]
"""
img = cv2.imread(dataPath+'big_500.png', 0)
hist = cv2.calcHist([img], [0], None, [256], [0, 256])
# 使用 numpy 中的函数 np.histogram() 也可以帮我们统计直方图
# img.ravel() 将图像转成一维数组
hist, bins = np.histogram(img.ravel(), 256, [0, 256])
# openCV 的函数要比 np.histgram() 快 40 倍。
绘制直方图
"""
绘制直方图
"""
img = cv2.imread(dataPath+'big_500.png', 0)
plt.hist(img.ravel(), 256, [0, 256])
plt.show()
显示多通道直方图
"""
显示多通道直方图
"""
img = cv2.imread(dataPath+'big_500.png')
color = ('b', 'g', 'r')
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()
使用掩模
"""
使用掩模
要统计图像某个局部区域的直方图只需要构建一副掩模图像。
将要统计的 部分设置为白色,其余部分为黑色,就构成了一副掩模图像。
"""