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

标签 python opencv hsv

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

黑色图像:

Need To detect this

蓝色图像:

e

红色图像:

enter image description here

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()与大津或 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)

您可以针对不同的图像尺寸调整参数,但这些参数适用于大多数图像尺寸。您可以阅读更多关于 cv2.adaptiveThreshold()docs .

输出:

enter image description here

enter image description here

关于python - 如何修复 hsv 中的黑色数字检测?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55556670/

相关文章:

python - 如何等待协程直到满足条件?

python - pandas数据框的条件过滤

opencv - accumulateWeighted导致图像变暗

c++ - 计算平均值 : different result for masked image vs ROI

c++ - Opencv 中的 hsv 范围是多少?

c++ - 100选10,附加条件

python - Django 平面页面 : sort list

c++ - inpaint() 没有产生预期的结果。为什么?

c++ - 使用 inRange 后在 openCV 中从 HSV 转换为 BGR 或从 HSV 转换为 JPEG 时出错

c++ - OpenCV HSV 怪异转换