近距离合并等高线区域

2024-05-06 00:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析收据上的优惠券代码,不幸的是,字母不是实线。它们由单个的小点组成。我设法做了一些图像处理,找到了这些点,但这就是我遇到的问题。有没有一种方法来连接或合并彼此靠近的点?有没有简单的解决办法?在

这是原始图像,也是找到圆点后的图像。在

enter image description hereenter image description hereenter image description here

这是我想出的密码。在

import cv2
import numpy as np


def load_local_image(image):
    c_img = cv2.imread(image, cv2.IMREAD_COLOR)
    g_img = cv2.imread(image, cv2.IMREAD_GRAYSCALE)
    return (cv2.resize(c_img, (800, 800)), cv2.resize(g_img, (800, 800)))


def find_letters(binary_image, rgb_image, settings):
    contours, hierarchy = cv2.findContours(binary_image.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    letters = []

    for contour in contours:
        if cv2.contourArea(contour) > settings['contour_area_threshold']:
            # four points of bounding box for each character
            x, y, w, h = cv2.boundingRect(contour)
            # draw the bounding rectangle from points above
            cv2.rectangle(rgb_image, (x, y), (x + w, y + h), settings['outline_color'], settings['outline_thickness'])
            # print 'x:{}, y:{}, width:{}, height:{}'.format(x, y, w, h)
            letters.append((x, y, w, h))
    return sorted(letters, key=lambda x: x[0])


def alter_image(img):
    blur = cv2.GaussianBlur(g, (3, 3), 0)
    ret, thresh1 = cv2.threshold(blur, 50, 255, cv2.THRESH_BINARY)
    bitwise = cv2.bitwise_not(thresh1)
    erosion = cv2.erode(bitwise, np.ones((1, 1) ,np.uint8), iterations=1)
    dilation = cv2.dilate(erosion, np.ones((3, 3) ,np.uint8), iterations=1)
    return dilation


c, g = load_local_image('img.jpg')
altered_img = alter_image(g)

contour_settings = {
    'contour_area_threshold': 1,
    'outline_thickness': 1,
    'outline_color': (66, 116, 244)
}
letters_crop = find_letters(altered_img, c, contour_settings)

cv2.imshow('color', c)
cv2.imshow('gray', altered_img)
cv2.waitKey()
cv2.destroyAllWindows()

Tags: 图像imageimgthresholdreturnsettingsdefnp