使用OpenCV,Numpy计算直方图,Matplot绘制直方图及分析
生活随笔
收集整理的這篇文章主要介紹了
使用OpenCV,Numpy计算直方图,Matplot绘制直方图及分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用OpenCV,Numpy計算直方圖,Matplot繪制直方圖及分析
- 1. 效果圖
- 2. 原理
- 3. 源碼
- 3.1 直方圖3種計算方法和2種繪制方法
- 3.2 Mask遮罩圖像直方圖
- 參考
這篇博客將介紹如何使用Python,OpenCV,Numpy函數計算直方圖,并使用 OpenCV 和 Matplotlib 函數繪制直方圖,并對直方圖進行分析。
通過查看圖像的直方圖,可以直觀地了解該圖像的對比度、亮度、強度分布等。
1. 效果圖
原始圖如下:
灰度圖直方圖效果如下:
可以看到左側區域顯示圖像中較暗像素的數量,右側區域顯示較亮像素的數量。從直方圖中可以看到暗區、亮區均不多,并且中間色調(中間范圍的像素值,例如 170/210 左右)的數量非常多。
BGR三通道的直方圖效果圖下:
原始圖 VS Mask遮罩 VS Mask圖像 VS 混合直方圖如下:
在第4個直方圖中,藍線表示完整圖像的直方圖,紅線表示遮罩區域的直方圖。
2. 原理
直方圖可以幫助全面了解圖像的強度分布。 最基本的直方圖是灰度圖像直方圖,在 X 軸上具有像素值(范圍從 0 到 255)和 Y 軸上圖像中相應像素數的圖。
計算直方圖的3種方式:
- hist = cv2.calcHist([img],[0],None,[256],[0,256])
- hist,bins = np.histogram(img.ravel(),256,[0,256])
- np.bincount(img.ravel(),minlength=256)
其中cv2的方式比np.histogram快40倍;
np.bincount比np.histogram快10倍,因此優先使用cv2.calHist()方式;
繪制直方圖的2種方式:
- matplot計算直方圖并繪制:plt.hist(img.ravel(),256,[0,256]); plt.show()
- matplot的簡單繪制方式:histr = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
3. 源碼
3.1 直方圖3種計算方法和2種繪制方法
import cv2
import numpy as np
from matplotlib import pyplot as pltimg = cv2.imread('ml.jpg', 0)# cv計算直方圖
# cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
# - img:要計算直方圖的圖像
# - channels:通道值,如果傳入灰度圖為0,彩色圖[0][1][2]分別計算BGR通道
# - mask:蒙版,并非為整個圖計算直方圖
# - histSize:x軸分多少個范圍
# - ranges: 值的范圍,通常是[0,256]
hist = cv2.calcHist([img], [0], None, [256], [0, 256])# numpy計算直方圖
# np.bincount() 比 np.histogram() 大概快10倍
# cv2.calHist() 比 np.histogram() 大概快40倍
hist, bins = np.histogram(img.ravel(), 256, [0, 256])
hist = np.bincount(img.ravel(), minlength=256)# 繪制直方圖法1:matplot
img = cv2.imread('ml.jpg', 0)
plt.hist(img.ravel(), 256, [0, 256])
plt.show()# 繪制直方圖法2:matplot普通繪制方式
img = cv2.imread('ml.jpg')
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()
3.2 Mask遮罩圖像直方圖
import cv2
import numpy as np
from matplotlib import pyplot as pltimg = cv2.imread('ml.jpg', 0)# 構造一個mask
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:300, 100:400] = 255
masked_img = cv2.bitwise_and(img, img, mask=mask)# 計算整個圖直方圖以及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, color='b'), plt.plot(hist_mask, color='r')
plt.xlim([0, 256])plt.show()
參考
- https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_histograms/py_histogram_begins/py_histogram_begins.html#histograms-getting-started
總結
以上是生活随笔為你收集整理的使用OpenCV,Numpy计算直方图,Matplot绘制直方图及分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你还好吗歌词是哪首歌啊?
- 下一篇: 龙泉宝剑出自哪里?