OpenCV - 自适应阈值/有效降噪?

时间:2021-01-25 19:37:50

标签: python numpy opencv computer-vision threshold

我是 OpenCV 的新手,刚刚阅读了 cv2.adaptiveThreshold() 并决定尝试一下。 可悲的是,我似乎无法摆脱如此巨大的噪音。

有哪些有效的方法可以减少噪音,以便我可以绘制正确的轮廓?最佳做法是什么?为什么?

这是片段:

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)

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

def preprocessing(frame):
    imgGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # mask = cv2.inRange(imgHsv, lower, upper)
    imgBlurred = cv2.GaussianBlur(imgGray, kernel, 1)
    gaussC = cv2.adaptiveThreshold(imgBlurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
    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:
        cv2.drawContours(imgCon, cnt, -1, (255, 0, 0), 3)





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

while (cap.isOpened()):
    success, frame = cap.read()
    if success == True:
        frame = cv2.flip(frame, 1)
        imgCon = frame.copy()
        imPrePro = preprocessing(frame)
        getcontours(imPrePro)
        cv2.imshow("Preprocessed", imPrePro)
        cv2.imshow("Original", imgCon)

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

1 个答案:

答案 0 :(得分:1)

我认为最好查看 blockSizeC 参数。

形成source

<块引用>

blockSize:用于计算像素阈值的像素邻域大小:3、5、7 等。

<块引用>

C:从平均值或加权平均值中减去的常数(参见下面的详细信息)。通常为正,但也可能为零或负。

在您的示例中,您将 C 设置为 2:

gaussC = cv2.adaptiveThreshold(imgBlurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
<头>
C=2 C=8
enter image description here enter image description here

如您所见,您需要使用 blockSizeC 参数才能从自适应阈值中获得所需的结果。

在这个问题中,我们通过增加 C 参数来减少噪音。

相关问题