LoginSignup
1
2

More than 3 years have passed since last update.

Pythonによる画像処理100本ノック#3 二値化

Last updated at Posted at 2020-09-17

はじめに

どうも、らむです。
これまた画像処理ではお馴染みの二値化を実装します。

3本目:二値化

二値化は画像を白黒の2色のみのモノクロ画像に変換する処理です。
通常グレースケール画像に対し行います。
また、二値化の際に閾値と呼ばれる基準の値を決めます。閾値未満の画素値は白、閾値以上の画素値を持つ画素は黒に置き換えます。

binarization.py
import numpy as np
import cv2
import matplotlib.pyplot as plt
plt.gray()


def binarization(img):
  # 画像コピー
  dst = img.copy()
  # グレースケール化
  gray = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)

  # 閾値
  th = 128
  # 二値化
  idx = np.where(gray < th)
  gray[idx] = 0
  idx = np.where(gray >= th)
  gray[idx] = 255

  return gray


# 画像読込
img = cv2.imread('../assets/imori.jpg')

# 二値化
mono = binarization(img)

# 画像保存
cv2.imwrite('result.jpg', mono)
# 画像表示
plt.imshow(mono)
plt.show()

ファイル名 ファイル名

画像左は入力画像、画像右は出力画像です。
グレースケール画像のように灰色が無く白と黒のみの画像になっています。

おわりに

もし、質問がある方がいらっしゃれば気軽にどうぞ。
imori_imoriさんのGithubに公式の解答が載っているので是非そちらも確認してみてください。

1
2
0

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
1
2