Python知识:opencv实现的直方图
給定一幅彩色圖片,畫出三個通道的直方圖。做出對比。
一、學習要點:
1)cv2.calcHist直方圖產生函數
? cv2.calcHist( images, channels, mask, histSize, ranges[, hist[, accumulate ]])
?#計算直方圖函數參數
- 第一個參數必須用方括號括起來,表示被計算的圖像,可以是多幅。
- 第二個參數是用于計算直方圖的通道,這里使用灰度圖計算直方圖,所以就直接使用第一個通道,多幅圖像相當于多通道;
- 第三個參數是Mask,與原圖維度相同,被計算的區域,1計算,0不計算,這里沒有使用,所以用None。
- 第四個參數是histSize,表示這個直方圖分成多少份(即多少個直方柱的數量)。
- 第五個參數是表示直方圖中各個像素的值,[0.0, 256.0]表示直方圖能表示像素值從0.0到256的像素。
2)cv2.normalize歸一化函數
# Normalize the value to fall below 255, to fit in image 'h'
cv2.normalize(source_array, destination_array, alpha, beta, normalization_type)
- source_array 是要歸一化的輸入圖像對應的數組,
- destination_array 是歸一化的輸出圖像對應的數組,
- alpha 表示下限邊界值,
- beta 表示上限邊界值,并且
- normalization_type 表示規范化的類型【 cv2.NORM_MINMAX,】。
3)?pts = np.column_stack函數
np.column_stack((bins, hist))
將兩個列向量合并后,拼成矩陣。
?pts = np.column_stack((bins, hist))??
4) cv2.polylines函數
cv.polylines(img,pts=pts,isClosed=True, color=(255, 255, 255), thickness=3)
參數如下:
img:要在上面畫多邊形的圖像
pts:包含多邊形上頂點的數組
isClosed:標志,決定所繪制的多邊形是否閉合。若為 True ,則畫若干個閉合多邊形;若為 False ,則畫一條連接所有點的折線
color:多邊形顏色
thickness:多邊形線的粗細
lineType:多邊形線的類型
shift:坐標精確到小數點后第幾位
二、代碼部分
#!/usr/bin/python # -*- coding: UTF-8 -*- # .Data:.2019/3/24 import cv2 import numpy as npimg = cv2.imread('D001.jpg') h = np.zeros((300, 256, 3)) # image to draw histogrambins = np.arange(256).reshape(256, 1) # Number of bins, since 256 colors, we need 256 bins color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]for ch, col in enumerate(color):hist_item = cv2.calcHist([img], [ch], None, [256], [0, 256]) # Calculates the histogramcv2.normalize(hist_item, hist_item, 0, 255,cv2.NORM_MINMAX) # Normalize the value to fall below 255, to fit in image 'h'hist = np.int32(np.around(hist_item))pts = np.column_stack((bins, hist)) # stack bins and hist, ie [[0,h0],[1,h1]....,[255,h255]]cv2.polylines(h, [pts], False, col)h = np.flipud(h) # You will need to flip the image verticallycv2.imshow('colorhist', h) cv2.waitKey(0) cv2.destroyAllWindows()三、結果輸出
輸出BGR的三個通道直方圖。
總結
以上是生活随笔為你收集整理的Python知识:opencv实现的直方图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python知识:numpy的维度之变
- 下一篇: python知识:numpy如何保存矩阵