使用 cv2.adaptiveThreshold 和 cv2.createTrackbar

# %% todo: 使用 cv2.adaptiveThreshold 和 cv2.createTrackbar
# ==============================================================================
import cv2
import numpy as np

# 新建一个窗口
cv2.namedWindow('img', cv2.WINDOW_NORMAL)   # 可调整窗口大小
cv2.resizeWindow("img", 800, 800)   # 设置窗口的大小

# 滑动条从0开始,为了使用特定的数值,采用数组和序号的方式。
adaptiveMethods_i = 0
adaptiveMethods = [cv2.ADAPTIVE_THRESH_MEAN_C, cv2.ADAPTIVE_THRESH_GAUSSIAN_C]

thresholdType_i = 0
thresholdTypes = [cv2.THRESH_BINARY, cv2.THRESH_BINARY_INV]

blockSize_i = 0
blockSizes = range(3, 100, 2)

c_i = 0
cs = range(-4, 4)

imgGray2 = cv2.imread(r"E:\Testwork\imgGray2.bmp", cv2.IMREAD_GRAYSCALE)
imgBin = cv2.adaptiveThreshold(imgGray2, 255, adaptiveMethods[adaptiveMethods_i],
                               thresholdTypes[thresholdType_i], blockSizes[blockSize_i], cs[c_i],)


flag = 0    # 为了滑动一次,只显示一次滑动结果
def noting(x):
    # 拖动滑动条,cv2.getTrackbarPos 的回调函数不能获得滑动后的位置,只能使用上次的位置。
    # print(f'{adaptiveMethods_i:3d}  {thresholdType_i:3d}  {blockSizes[blockSize_i]:3d} {cs[c_i]}')
    global flag     # 设置成全局变量
    flag = 1

cv2.createTrackbar('adaptiveMethods_i', 'img', 0, 1, noting)
cv2.createTrackbar('thresholdType_i', 'img', 0, 1, noting)
cv2.createTrackbar('blockSize_i', 'img', 0, len(blockSizes)-1, noting)
cv2.createTrackbar('c', 'img', 0, len(cs)-1, noting)

while 1:
    cv2.imshow('img', imgBin)
    adaptiveMethods_i = cv2.getTrackbarPos('adaptiveMethods_i', 'img')
    thresholdType_i = cv2.getTrackbarPos('thresholdType_i', 'img')
    blockSize_i = cv2.getTrackbarPos('blockSize_i', 'img',)
    c_i = cv2.getTrackbarPos('c', 'img',)
    imgBin = cv2.adaptiveThreshold(imgGray2, 255, adaptiveMethods[adaptiveMethods_i],
                                   thresholdTypes[thresholdType_i], blockSizes[blockSize_i], cs[c_i], )
    if flag == 1:    # 为了滑动一次,只显示一次滑动结果
        print(f'{adaptiveMethods_i:3d}  {thresholdType_i:3d}  {blockSizes[blockSize_i]:3d} {cs[c_i]}')
        flag = 0
    if cv2.waitKey(1) == ord('q'):
        break

cv2.destroyAllWindows()
03-27 07:25