首页 > 解决方案 > 垂直组合轮廓并获得凸包 - opencv - python

问题描述

我有这样的角色图像:

得到后contours输出convexHull是这样的:

为此,我使用了以下代码:

import cv2
img = cv2.imread('input.png', -1)

ret, threshed_img = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),
                        127, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(threshed_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in contours:
    # get convex hull
    hull = cv2.convexHull(cnt)
    cv2.drawContours(img, [hull], -1, (0, 0, 255), 1)    
cv2.imwrite("output.png", img)

正如您在下图中看到的,已识别出的轮廓与原始字符垂直对齐。但是那些与原始的核心角色是分开的。(这些实际上是僧伽罗语的修饰语 - සිංහල)

现在我想将那些垂直对齐的轮廓与核心角色合并。最终输出应如下所示。我怎样才能有效地做到这一点?

标签: pythonopencvconvex-hullopencv-contour

解决方案


您可以尝试使用具有垂直矩形形状的内核执行形态学操作。这样,原始字符之上的某些字符将被合并为一个。

rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 30))
threshed = cv2.morphologyEx(th2, cv2.MORPH_CLOSE, rect_kernel)
cv2.imshow('threshed', threshed)

在此处输入图像描述

imgContours, Contours, Hierarchy = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for cnt in Contours:
    hull = cv2.convexHull(cnt)
    cv2.drawContours(img2, [hull], -1, (0, 0, 255), 1) 
cv2.imshow('convex hull', img2)

在此处输入图像描述


推荐阅读