# Python matplotlib怎么繪制灰度和彩色直方圖
直方圖是圖像處理中分析像素分布的重要工具。本文將詳細介紹如何使用Python的matplotlib庫繪制灰度圖像和彩色圖像的直方圖,包含完整代碼示例和可視化效果分析。
## 一、直方圖基礎概念
### 1.1 什么是直方圖
直方圖(Histogram)是圖像像素強度分布的圖形表示,橫軸代表像素值(0-255),縱軸代表該像素值在圖像中出現的頻率。
### 1.2 直方圖的作用
- 分析圖像對比度
- 檢測曝光問題
- 圖像分割閾值選擇
- 顏色校正依據
## 二、準備工作
### 2.1 安裝必要庫
```python
pip install matplotlib numpy opencv-python
import cv2
import numpy as np
import matplotlib.pyplot as plt
gray_img = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
plt.hist(gray_img.ravel(), bins=256, range=[0, 256])
plt.title('Grayscale Histogram')
plt.xlabel('Pixel Value')
plt.ylabel('Frequency')
plt.show()
plt.figure(figsize=(10, 6))
plt.hist(gray_img.ravel(), bins=256, range=[0, 256],
color='gray', alpha=0.7, edgecolor='black')
plt.title('Enhanced Grayscale Histogram', fontsize=14)
plt.xlabel('Pixel Intensity', fontsize=12)
plt.ylabel('Pixel Count', fontsize=12)
plt.grid(axis='y', alpha=0.5)
plt.xlim([0, 256])
plt.show()
images = [gray_img, cv2.equalizeHist(gray_img)]
titles = ['Original', 'Histogram Equalized']
plt.figure(figsize=(12, 6))
for i, (img, title) in enumerate(zip(images, titles)):
plt.subplot(1, 2, i+1)
plt.hist(img.ravel(), bins=256, range=[0, 256])
plt.title(title)
plt.tight_layout()
plt.show()
color_img = cv2.imread('color_image.jpg')
color_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2RGB) # 轉換通道順序
colors = ('r', 'g', 'b')
plt.figure(figsize=(10, 6))
for i, color in enumerate(colors):
hist = cv2.calcHist([color_img], [i], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.title('Color Channel Histograms')
plt.xlabel('Pixel Value')
plt.ylabel('Frequency')
plt.legend(['Red', 'Green', 'Blue'])
plt.show()
plt.figure(figsize=(10, 6))
for i, color in enumerate(colors):
hist = cv2.calcHist([color_img], [i], None, [256], [0, 256])
plt.plot(hist, color=color, linewidth=2)
plt.fill_between(range(256), hist.ravel(), color=color, alpha=0.3)
plt.title('Stacked Color Histogram', fontsize=14)
plt.xlabel('Pixel Intensity', fontsize=12)
plt.ylabel('Pixel Count', fontsize=12)
plt.grid(alpha=0.2)
plt.show()
from mpl_toolkits.mplot3d import Axes3D
# 創建3D坐標軸
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')
# 為每個通道生成數據
bins = np.arange(256)
for c, z, color in zip([0, 1, 2], [0, 50, 100], ['r', 'g', 'b']):
hist = cv2.calcHist([color_img], [c], None, [256], [0, 256])
ax.bar(bins, hist.ravel(), zs=z, zdir='y', color=color, alpha=0.7)
ax.set_xlabel('Pixel Value')
ax.set_ylabel('Color Channel')
ax.set_zlabel('Frequency')
ax.set_yticks([0, 50, 100])
ax.set_yticklabels(['Red', 'Green', 'Blue'])
plt.title('3D Color Histogram')
plt.show()
# 分離通道
channels = cv2.split(color_img)
eq_channels = []
for ch in channels:
eq_channels.append(cv2.equalizeHist(ch))
eq_img = cv2.merge(eq_channels)
# 繪制對比
plt.figure(figsize=(14, 8))
for i, (img, title) in enumerate(zip([color_img, eq_img],
['Original', 'Equalized'])):
plt.subplot(2, 1, i+1)
for j, color in enumerate(colors):
hist = cv2.calcHist([img], [j], None, [256], [0, 256])
plt.plot(hist, color=color)
plt.title(f'{title} Image Histogram')
plt.legend(['Red', 'Green', 'Blue'])
plt.tight_layout()
plt.show()
def hist_match(source, template):
# 計算源圖像和目標圖像的累積直方圖
src_hist = cv2.calcHist([source], [0], None, [256], [0,256]).cumsum()
tmpl_hist = cv2.calcHist([template], [0], None, [256], [0,256]).cumsum()
# 歸一化
src_hist = (src_hist - src_hist.min()) / (src_hist.max() - src_hist.min()) * 255
tmpl_hist = (tmpl_hist - tmpl_hist.min()) / (tmpl_hist.max() - tmpl_hist.min()) * 255
# 創建LUT
lut = np.interp(src_hist, tmpl_hist, np.arange(256))
return cv2.LUT(source, lut.astype('uint8'))
# 應用示例
matched = hist_match(gray_img, template_img)
降采樣處理:對大圖像可先縮小尺寸
small_img = cv2.resize(img, (0,0), fx=0.25, fy=0.25)
使用numpy函數:比OpenCV更快
hist, bins = np.histogram(img.ravel(), 256, [0,256])
限制bin數量:減少計算量
plt.hist(img.ravel(), bins=64, range=[0, 256])
Q1:直方圖右側有大量空白? A:說明圖像像素集中在低值區域,可嘗試調整顯示范圍:
plt.xlim([0, np.max(img)*1.1])
Q2:如何比較兩個直方圖?
# 使用直方圖比較方法
correl = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)
Q3:直方圖峰值不明顯? 可嘗試對數變換:
plt.yscale('log')
本文詳細介紹了使用matplotlib繪制圖像直方圖的各種方法,包括: - 基礎灰度直方圖繪制 - 多通道彩色直方圖可視化 - 3D直方圖等高級技巧 - 直方圖均衡化和匹配應用
掌握這些技術能夠幫助您更好地分析圖像特征,為后續的圖像處理任務打下基礎。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。