使用凸壳坐标提取字符 - opencv - python

时间:2018-05-17 13:16:58

标签: python opencv crop image-segmentation convex-hull

我有这样的角色形象:

使用以下代码我可以获得轮廓和凸包,然后我可以为每个角色绘制凸起。

import cv2
img = cv2.imread('test.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)
    print(hull)
cv2.imwrite("contours.jpg", img)

结果如下:

我可以得到这样的船体坐标(对于一个角色):

[[[546 134]]
 [[534 149]]
 [[532 151]]
 [[527 153]]
 [[523 154]]
 [[522 154]]
 [[520 109]]
 [[521 107]]
 [[524 106]]
 [[533 106]]
 [[539 111]]
 [[543 117]]
 [[546 122]]]

现在我想用convexHull坐标分隔每个字符。 分离后,图像会像,

。 。 。

我想使用convexHull坐标的主要原因是我可以分割在垂直图像空间中重叠的字符。您可以使用以下图片了解我的意思:

我无法准确分割字符,因为大多数图片都包含上述字符。所以我想使用convexHull坐标来分割字符。

1 个答案:

答案 0 :(得分:4)

  • 获得一个角色的凸包后,我找到了相应的轮廓并将其填满。
  • 我用原始图像掩盖每个单独的字段轮廓以获得段

以下是代码:

import cv2
import numpy as np

img = cv2.imread(r'C:\Users\selwyn77\Desktop\letters.png', -1)
img2 = img.copy()
cv2.imshow("original.jpg", img)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, threshed_img = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
image, contours, hier = cv2.findContours(threshed_img, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

#--- Black image to be used to draw individual convex hull ---
black = np.zeros_like(img)
cv2.imshow("black.jpg", black)

contours = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0]) #added by OP : this sorts contours left to right, so images come in order

for cnt in contours:
    hull = cv2.convexHull(cnt)

    img3 = img.copy()
    black2 = black.copy()

    #--- Here is where I am filling the contour after finding the convex hull ---
    cv2.drawContours(black2, [hull], -1, (255, 255, 255), -1)
    g2 = cv2.cvtColor(black2, cv2.COLOR_BGR2GRAY)
    r, t2 = cv2.threshold(g2, 127, 255, cv2.THRESH_BINARY)
    cv2.imshow("t2.jpg", t2)

    masked = cv2.bitwise_and(img2, img2, mask = t2)    
    cv2.imshow("masked.jpg", masked)

    print(len(hull))
    cv2.waitKey(0)

cv2.destroyAllWindows()

现在,您可以使用cv2.imwrite()保存每个细分受众群。

以下是一些细分字符:

enter image description here

enter image description here

enter image description here