1. 程式人生 > >Python OpenCV _2直方圖計算與顯示的四種方式

Python OpenCV _2直方圖計算與顯示的四種方式

此係列原始碼在我的GitHub裡:https://github.com/yeyujujishou19/Python-OpenCV

原圖

一,CV2分通道描繪直方圖: 

import cv2
import numpy as np

#計算並繪製直方圖
def calcAndDrawHist(image, color):
    hist = cv2.calcHist([image],
                        [0],  # 使用的通道
                        None,  # 沒有使用mask
                        [256],  # HistSize
                        [0.0, 255.0])  # 直方圖柱的範圍
    #要求矩陣的最小值,最大值,並得到最大值,最小值的索引
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(hist)
    histImg = np.zeros([256, 256, 3], np.uint8)  #畫板
    hpt = int(0.9 * 256);

    for h in range(256):
        intensity = int(hist[h] * hpt / maxVal)
        cv2.line(histImg, (h, 256), (h, 256 - intensity), color)

    return histImg;

if __name__ == '__main__':
    img = cv2.imread("D:/lena.jpg")
    b, g, r = cv2.split(img)  #分離通道

    histImgB = calcAndDrawHist(b, [255, 0, 0]) #繪製直方圖
    histImgG = calcAndDrawHist(g, [0, 255, 0])
    histImgR = calcAndDrawHist(r, [0, 0, 255])

    cv2.imshow("histImgB", histImgB)
    cv2.imshow("histImgG", histImgG)
    cv2.imshow("histImgR", histImgR)
    cv2.imshow("Img", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows() #登出視窗

程式碼結果:

 

二,CV2折線來描繪直方圖

# coding=utf-8
import cv2
import numpy as np

img = cv2.imread('D:/lena.jpg')
h = np.zeros((256, 256, 3))  # 建立用於繪製直方圖的全0影象

bins = np.arange(256).reshape(256, 1)  # 直方圖中各bin的頂點位置
color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]  # BGR三種顏色
for ch, col in enumerate(color):
    #cv2.calcHist函式得到的是float32型別的陣列
    originHist = cv2.calcHist([img], [ch], None, [256], [0, 256])
    #歸一化函式,該函式將直方圖的範圍限定在0-255×0.9之間。
    cv2.normalize(originHist, originHist, 0, 255 * 0.9, cv2.NORM_MINMAX)

    hist = np.int32(np.around(originHist)) #將整數部分轉成np.int32型別
    pts = np.column_stack((bins, hist)) #將直方圖中每個bin的值轉成相應的座標
    cv2.polylines(h, [pts], False, col) #根據這些點繪製出折線

h = np.flipud(h) #反轉繪製好的直方圖,因為繪製時,[0,0]在影象的左上角

cv2.imshow('colorhist', h)
cv2.waitKey(0)

 程式碼結果:

 

三,NumPy版的直方圖計算 

# coding=utf-8
import cv2
import numpy as np

img = cv2.imread('D:/lena.jpg')
h = np.zeros((300, 256, 3))
bins = np.arange(257)
bin = bins[0:-1]
color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]

for ch, col in enumerate(color):
    item = img[:, :, ch]
    N, bins = np.histogram(item, bins)
    v = N.max()
    N = np.int32(np.around((N * 255) / v))
    N = N.reshape(256, 1)
    pts = np.column_stack((bin, N))
    cv2.polylines(h, [pts], False, col)

h = np.flipud(h)

cv2.imshow('image', h)
cv2.waitKey(0)

程式碼結果:

 

四,通過NumPy和matplotlib繪製出直方圖

import matplotlib.pyplot as plt
import numpy as np
import cv2

img = cv2.imread('D:/lena.jpg')
bins = np.arange(257)

item = img[:, :, 1]
hist, bins = np.histogram(item, bins)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

程式碼結果:

 

 原文地址:https://blog.csdn.net/sunny2038/article/details/9097989

歡迎掃碼關注我的微信公眾號