天天看點

cv2小記——直方圖的計算,繪制與分析

# 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()      

使用掩模

"""
使用掩模
要統計圖像某個局部區域的直方圖隻需要建構一副掩模圖像。
将要統計的 部分設定為白色,其餘部分為黑色,就構成了一副掩模圖像。
"""      

繼續閱讀