LoginSignup
62
68

More than 3 years have passed since last update.

OpenCV 画像の二値化

Last updated at Posted at 2019-04-27

概要

OpenCVを使った画像の二値化について書きます。

画像の二値化(自分で閾値を設定)

画像は有名なLenaを使います。
グレースケールで読み込むので、cv2.imreadの第二引数に"0"を書きます。
二値化はcv2.thresholdで行います。
cv2.threshold(画像, 閾値, 閾値を超えた場合に変更する値, 二値化の方法)
閾値と、二値化された画像を返すので、変数を二つ用意(retとimg_thresh)。

画像の読み込みと表示.py
import cv2

# 画像の読み込み
img = cv2.imread("./data/Lena.jpg", 0)

# 閾値の設定
threshold = 100

# 二値化(閾値100を超えた画素を255にする。)
ret, img_thresh = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)

# 二値化画像の表示
cv2.imshow("img_th", img_thresh)
cv2.waitKey()
cv2.destroyAllWindows()

lena_th_bi.jpg
ちょっと白く飛びすぎ?

閾値を自動で設定

上記は閾値を自分で設定したが、画像に応じて自動で決定してくれる便利なものもある。
cv2.thresholdcv2.THRESH_OTSUを使う

change_windowsize.py
ret2, img_otsu = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)

#閾値がいくつになったか確認
print("ret2: {}".format(ret2))

#画像の確認
cv2.imshow("otsu", img_otsu)
cv2.waitKey()
cv2.destroyAllWindows()

ret2: 117.0

lena_th_otsu.jpg

自動では閾値は117になり、
より自然な画像となった。

まとめ

とりあえず二値化について2つの方法を書いてみた。
他にも種類があるのでまた試したい。

62
68
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
62
68