画像

OpenCVで画像のヒストグラムをmatplotlibで出力する

最終更新日 2023.02.18

Python3、OpenCV、matplotlib を使って画像のヒストグラムを出力します。まずは下の画像をグレースケールにしたもののヒストグラムを表します。

import cv2
from matplotlib import pyplot as plt

filename = 'park.jpg'
img = cv2.imread(filename, 0)
plt.hist(img.ravel(), 256, [0, 256])
plt.show()

手順のまとめ:

  1. imread で画像を読む
  2. そのデータを ravel で加工する
  3. matplotlib の hist でヒストグラムを作る
  4. 出力する