Combine contours vertically and get convex hull - opencv - python

Ish*_*awa 2 python opencv convex-hull opencv-contour

I have character images like this:

After getting contours and convexHull the output is like this:

For that I used following code:

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)
Run Code Online (Sandbox Code Playgroud)

As you can see in the following image there are identified contours which are vertically aligned with the original character. But those are separated with the original core character. (Those are actually modifiers of the language called sinhala - ?????)

Now I want to merge those vertically aligned contours with the core character. Ultimately the output should be as follows. How could I do that efficiently?

Jer*_*uke 6

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

rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 30))
threshed = cv2.morphologyEx(th2, cv2.MORPH_CLOSE, rect_kernel)
cv2.imshow('threshed', threshed)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明