import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread("../SampleImages/pomeranian.png", cv.IMREAD_COLOR)
print(img.shape)
#圖像直方圖計(jì)算
#cv.calcHist(images, channels, mask, histSize, ranges, hist, accumulate)
#images:原圖像(圖像格式為 uint8 或 float32)。當(dāng)傳入函數(shù)時(shí)應(yīng)該 用中括號(hào) [] 括起來,例如:[img]。
#channels:同樣需要用中括號(hào)括起來,它會(huì)告訴函數(shù)我們要統(tǒng)計(jì)那幅圖 像的直方圖。如果輸入圖像是灰度圖,它的值就是 [0];如果是彩色圖像 的話,傳入的參數(shù)可以是 [0],[1],[2] 它們分別對(duì)應(yīng)著通道 B,G,R。
#mask: 掩模圖像。要統(tǒng)計(jì)整幅圖像的直方圖就把它設(shè)為 None。但是如 果你想統(tǒng)計(jì)圖像某一部分的直方圖的話,你就需要制作一個(gè)掩模圖像,并 使用它。
#histSize:BIN 的數(shù)目。也應(yīng)該用中括號(hào)括起來,例如:[256]。
#ranges: 像素值范圍,通常為 [0,256]
#hist:是一個(gè) 256x1 的數(shù)組作為返回值,每一個(gè)值代表了與次灰度值對(duì)應(yīng)的像素點(diǎn)數(shù)目。
#accumulate:是一個(gè)布爾值,用來表示直方圖是否疊加。
#參考資料:https://blog.csdn.net/yukinoai/article/details/87900860
#1. mask為None,對(duì)整幅圖計(jì)算直方圖
hist_b = cv.calcHist(img, [0], None, [256], [0,256])
hist_g = cv.calcHist(img, [1], None, [256], [0,256])
hist_r = cv.calcHist(img, [2], None, [256], [0,256])
#2. 使用mask計(jì)算局部圖像直方圖
# mask的使用:https://www.coder.work/article/2087445
mask = np.zeros(img.shape[:2], np.uint8)
mask[100:200,100:200]=255
hist_mask_b = cv.calcHist([img], [0], mask, [256], [0,256])
hist_mask_g = cv.calcHist([img], [1], mask, [256], [0,256])
hist_mask_r = cv.calcHist([img], [2], mask, [256], [0,256])
#顯示圖像
fig,axes = plt.subplots(nrows=3, ncols=1, figsize=(10,10), dpi=100)
axes[0].imshow(img[:,:,::-1])
axes[0].set_title("Original")
axes[1].set_title("Histogram")
axes[1].plot(hist_b, color='b')
axes[1].plot(hist_g, color='g')
axes[1].plot(hist_r, color='r')
axes[2].plot(hist_mask_b, color='b')
axes[2].plot(hist_mask_g, color='g')
axes[2].plot(hist_mask_r, color='r')
?文章來源:http://www.zghlxwxcb.cn/news/detail-666310.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-666310.html
到了這里,關(guān)于Python Opencv實(shí)踐 - 直方圖顯示的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!