2021年6月27日日曜日

【OpenCV】thresholdによる画像の二値化

画像処理ライブラリOpenCVで画像を二値化するthresholdについて説明する。


OpenCVを使うには次のようにインポートが必要。
import cv2


1. thresholdによる画像の二値化

thresholdは入力画像(グレースケール画像)に対して、ピクセル値が閾値よりも大きければ255に、ピクセル値が閾値よりも小さければ0に変換する。これにより閾値を境界として画像を二値化する。
書式は以下。

retval, dst=cv.threshold(src, thresh, maxval, type[, dst])
引数 意味
src 入力画像
dst 出力画像
thresh 閾値
maxval THRESH_BINARY、THRESH_BINARY_INVをthresholding typeに用いた場合の最大値
type thresholding type

入力画像として以下でグラデーションのあるグレースケール画像を作成し'gray.png'で保存。

import numpy as np
import cv2

img = np.zeros((100, 256, 1), np.uint8)
for x in range(256):
    img[:, x, :] = x
cv2.imwrite('gray.png', img)

実行結果




thresholding typeは以下を用いることができる。

引数 意味
THRESH_BINARY 閾値よりも大きければmaxval、小さければ0に変換(一般的な二値化)
THRESH_BINARY_INV 閾値よりも大きければ0、小さければmaxvalに変換
THRESH_TRUNC 閾値よりも大きければ閾値に、それ以外は元の値
THRESH_TOZERO 閾値よりも大きければ元の値、それ以外は0に
THRESH_TOZERO_INV 閾値よりも大きければ0に、それ以外は元の値

thresholding typeTHRESH_BINARYを用いた場合。threshは127、maxvalは255。

import cv2

img = cv2.imread('gray.png')
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imwrite('thresh.png', thresh)

実行結果




thresholding typeTHRESH_TRUNC_INVを用いた場合。threshは127、maxvalは255。

import cv2

img = cv2.imread('gray.png')
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imwrite('thresh.png', thresh)

実行結果




thresholding typeTHRESH_TRUNCを用いた場合。threshは127、maxvalは255。

import cv2

img = cv2.imread('gray.png')
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
cv2.imwrite('thresh.png', thresh)

実行結果




thresholding typeTHRESH_TOZEROを用いた場合。threshは127、maxvalは255。

import cv2

img = cv2.imread('gray.png')
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
cv2.imwrite('thresh.png', thresh)

実行結果




thresholding typeTHRESH_TOZERO_INVを用いた場合。threshは127、maxvalは255。

import cv2

img = cv2.imread('gray.png')
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
cv2.imwrite('thresh.png', thresh)

実行結果




2. リファレンス

OpenCV > Image Thresholding
OpenCV > Miscellaneous Image Transformations > threshold() OpenCV > Miscellaneous Image Transformations > ThresholdTypes

使用したバージョン:Python 3.7.0 / OpenCV 4.0.0

0 件のコメント:

コメントを投稿