画像の2値化

2020/11/21

Python3.8.2, OpenCV4.4.0

import cv2

img_src = cv2.imread('img_path')
img_gray = cv2.cvtColor(img_src, cv2.COLOR_RGB2GRAY)
threshold = 125
ret, img_thresh = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY)

#表示
cv2.imshow("thresh image", img_thresh)
cv2.waitKey()
cv2.destroyAllWindows()


ノイズ処理と閾値の自動化した2値化

import cv2

img = cv2.imread('img_path')
img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img = cv2.GaussianBlur(img,(5,5),0)
ret,img = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imwrite(os.path.join(output_path),img)


フォルダ内の画像をまとめて変換

# -*- coding: utf-8 -*-

import os
import cv2

input_dir_path = './input/'
output_dir_path ='./output/'

file_list = os.listdir(input_dir_path)
for fname in file_list:
    path = os.path.join(input_dir_path,fname)
    if os.path.isfile(path):
        img = cv2.imread(path)
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        ret, img = cv2.threshold(img, 120, 255, cv2.THRESH_BINARY)
        cv2.imwrite(os.path.join(output_dir_path,fname),img)
print('done')



OpenCV-Pythonチュートリアル 画像のしきい値処理
http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html