OpenCV - 自适应阈值/轨迹栏操作

OpenCV - Adaptive thresholding / Trackbar manipulation

我还是 OpenCV(Python) 的新手,我正在尝试 cv2.adaptiveThreshold() 在光线变化时使用网络摄像头 运行 绘制适当的轮廓。主要问题是我在绘制轮廓时得到的大量噪音,所以我尝试设置一个 cv2.countourArea() 阈值,但这似乎不是最好的解决方案。

后来我决定尝试使用一个简单的轨迹栏来操纵 cv2.adaptiveThreshold 的值。

特别是 blockSizeCValue。在 CValue 上一切正常,但我在 blockSize 上确实很挣扎,因为它需要是奇数。我尝试了一些检查 empty 回调函数的值是否为偶数并添加 +1 的方法。但这似乎无法正常工作。稍后我很可能会使用机器学习来更改这些值,但现在我希望轨迹栏用于调试目的。

此处使用轨迹栏操纵 blockSize 的最佳解决方案是什么?

提前致谢! :)

import cv2
import numpy as np

#####################################
winWidth = 640
winHeight = 840
brightness = 100

cap = cv2.VideoCapture(0)
cap.set(3, winWidth)
cap.set(4, winHeight)
cap.set(10, brightness)

kernel = (5, 5)
bSize_default = 1


#######################################################################
def empty(a):
    pass


cv2.namedWindow("TrackBars")
cv2.resizeWindow("TrackBars", 640, 240)
cv2.createTrackbar("cVal", "TrackBars", 2, 20, empty)


def preprocessing(frame, cVal):
    imgGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # mask = cv2.inRange(imgHsv, lower, upper)
    imgBlurred = cv2.GaussianBlur(imgGray, kernel, 3)
    gaussC = cv2.adaptiveThreshold(imgBlurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, cVal)
    imgDial = cv2.dilate(gaussC, kernel, iterations=3)
    imgErode = cv2.erode(imgDial, kernel, iterations=1)

    return imgDial


def getContours(imPrePro):
    contours, hierarchy = cv2.findContours(imPrePro, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 60:
            cv2.drawContours(imgCon, cnt, -1, (255, 0, 0), 3)


#######################################################################################################

while (cap.isOpened()):
    success, frame = cap.read()
    cVal = cv2.getTrackbarPos("cVal", "TrackBars")

    if success == True:
        frame = cv2.flip(frame, 1)
        imgCon = frame.copy()
        imPrePro = preprocessing(frame, cVal)
        getContours(imPrePro)
        cv2.imshow("Preprocessed", imPrePro)
        cv2.imshow("Original", imgCon)

        if cv2.waitKey(1) & 0xFF == ord("q"):
            cv2.destroyAllWindows()
            break

blocksize 的最小值必须为 3,并且 blocksize 必须为奇数,因此:

    value_BSize= cv2.getTrackbarPos("bSize", "TrackBars")
    value_BSize = max(3,value_BSize)
    if (value_BSize % 2 == 0):
          
            value_BSize  += 1
         
tbar = (cv2.getTrackbarPos('trackbar', 'window')&~1)+3  # for smooth operation
tbar = cv2.getTrackbarPos('trackbar', 'window')*2+3  # for fast operation