OpenCVとヒストグラム
OpenCVは、画像処理やコンピュータビジョンの分野で広く活用されているオープンソースライブラリです。画像のヒストグラムとは、横軸に画素値、縦軸に頻度をとったヒストグラムです。カラー画像の場合はチャンネルごとにヒストグラムを作成します。
ヒストグラムの作成
OpenCVの cv2.calcHist()
を使用すると、画像から指定したチャンネルのヒストグラムを計算できます。以下に、グレースケール画像のヒストグラムを作成するPythonコードを示します。
import cv2
import matplotlib.pyplot as plt
import numpy as np
# 画像をグレースケール形式で読み込む。
img = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
# 1次元ヒストグラムを作成する。
n_bins = 100 # ビンの数
hist_range = [0, 256] # 集計範囲
hist = cv2.calcHist([img], channels=[0], mask=None, histSize=[n_bins], ranges=hist_range)
hist = hist.squeeze(axis=-1) # (n_bins, 1) -> (n_bins,)
# 描画する。
def plot_hist(bins, hist, color):
centers = (bins[:-1] + bins[1:]) / 2
widths = np.diff(bins)
ax.bar(centers, hist, width=widths, color=color)
bins = np.linspace(*hist_range, n_bins + 1)
fig, ax = plt.subplots()
ax.set_xticks([0, 256])
ax.set_xlim([0, 256])
ax.set_xlabel("Pixel Value")
plot_hist(bins, hist, color="k")
plt.show()
このコードは、指定した画像をグレースケールで読み込み、そのヒストグラムを作成し、表示します。
カラー画像のヒストグラム
カラー画像のヒストグラムを作成する場合、チャンネルごとにヒストグラムを計算します。以下に、カラー画像のヒストグラムを作成するPythonコードを示します。
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread("sample.jpg")
n_bins = 256
hist_range = [0, 256]
hists = []
channels = {0: "blue", 1: "green", 2: "red"}
for ch in channels:
hist = cv2.calcHist([img], channels=[ch], mask=None, histSize=[n_bins], ranges=hist_range)
hist = hist.squeeze(axis=-1)
hists.append(hist)
def plot_hist(bins, hist, color):
centers = (bins[:-1] + bins[1:]) / 2
widths = np.diff(bins)
ax.bar(centers, hist, width=widths, color=color)
bins = np.linspace(*hist_range, n_bins + 1)
fig, ax = plt.subplots()
ax.set_xticks([0, 256])
ax.set_xlim([0, 256])
ax.set_xlabel("Pixel Value")
for hist, color in zip(hists, channels.values()):
plot_hist(bins, hist, color=color)
plt.show()
このコードは、指定した画像を読み込み、各チャンネル(赤、緑、青)のヒストグラムを作成し、表示します。
ヒストグラムの均一化
ヒストグラムの均一化とは、ヒストグラムの累積度数のグラフの傾きが一定になるよう変換する処理を指します。ヒストグラム均一化処理を施すことで、全体のコントラストや輝き度の偏りの改善が可能です。以下に、ヒストグラム均一化を行うPythonコードを示します。
import cv2
# 画像読込
img = cv2.imread("image_data.jpg", 0)
# ヒストグラム均一化した画像
img_hist = cv2.equalizeHist(img)
# 画像比較
cv2.imshow("img_gray", img)
cv2.imshow("img_hist", img_hist)
cv2.waitKey(0)
cv2.destroyAllWindows()
このコードは、指定した画像を読み込み、ヒストグラム均一化を行い、元の画像と均一化後の画像を表示します。
以上、PythonとOpenCVを使用して画像のヒストグラムを作成し、ヒストグラムの均一化を行う方法について説明しました。これらの技術は、画像処理やコンピュータビジョンの分野で広く活用されています。今後もPythonとOpenCVを活用して、さまざまな画像処理を行ってみてください。.