如何修复 hsv 中的黑色数字检测?

How to fix Black digit detection in hsv?

我正在尝试检测数字,但无法检测用黑笔书写的数字。我的代码非常适合用黑色以外的其他颜色书写的数字。

黑色图像:

蓝图:

红色图像:

img = cv2.imread("blue.jpg")
image = cv2.resize(img, (660, 600))

hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv, (0, 65, 0), (179, 255, 255))
mask_inv = cv2.bitwise_not(mask)
ret, thresh = cv2.threshold(mask_inv, 127, 255, cv2.THRESH_BINARY_INV)
kernel = np.ones((15, 15), np.uint8)
img_dilation = cv2.dilate(thresh, kernel, iterations=1)
ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])

for i, ctr in enumerate(sorted_ctrs):
    x, y, w, h = cv2.boundingRect(ctr)
    roi = mask_inv[y:y + h, x:x + w]
    if h > 30 and w < 150:

        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('ROIs', image)

当我们需要从相对一致的背景颜色中分割出两种对比鲜明的未知颜色(蓝色或黑色)时,我们可以使用 cv2.threshold() 和 OTSU 或 cv2.adaptiveThreshold()

由于事先不知道墨水颜色,因此定义 HSV 范围不适用于所有情况。我更喜欢 cv2.adaptiveThreshold() 而不是 OTSU,因为它具有适应性。预期输出可以实现为:

def get_mask(img):
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    return cv2.adaptiveThreshold(img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 3, 4)

您可以针对不同的图像尺寸调整参数,但这些参数适用于大多数图像。您可以在 docs.

中阅读有关 cv2.adaptiveThreshold() 的更多信息

输出: