合并轮廓区域非常接近

时间:2017-10-31 02:41:08

标签: python opencv

我正在处理从收据中解析优惠券代码,不幸的是,这些字母不是实线。它们由小的单个点组成。我设法做了一些图像操作并找到了点,但这就是我被困的地方。有没有办法连接或合并彼此接近的点?有一个简单的解决方案吗?

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

enter image description here enter image description here enter 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()

0 个答案:

没有答案