
まくまく
OpenCV imshowで複数の画像を表示させ、その画像を見ながらトラックバーで2値化の閾値を決めてみたいと思います。
使用するのはopenCV
使用するのは、画像処理ライブラリのopenCVです。ここではopenCVがインストールされているのを前提として書き進めていきます。
サンプルコード
import cv2
import numpy as np
def trackbar(position):
pass
img = cv2.imread("photo1.jpg", 0)
img2 = img.copy()
# トラックバーを表示するウィンドウを作成
cv2.namedWindow("window")
# 初期値
threshold = 100
cv2.createTrackbar("threshold", "window", threshold, 255, trackbar)
while True:
ret, th = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
ret, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU)
#th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, -5)
# トラックバーの位置をthreshholdに代入
threshold = cv2.getTrackbarPos("threshold", "window")
# 画像を表示する
images = np.hstack((th, th2))
cv2.imshow("window", images)
if cv2.waitKey(10) == 27:
print(threshold)
break
cv2.destroyAllWindows()
exit()
出力
コメント
2値化トラックバーは、1画像だけで実施するのが主ですが、隣に大津の方法での2値化画像を表示させてみました。画面の右側は大津の方法による2値化画像です。左側は画面上部のスライダーを動かしてスレッショルドを決定します。OpenCVのimshowで2枚の画像を表示しています。
3つの画像を並べて適応的二値化処理を追加させても良さそうですね。