文本检测:获取边界框

时间:2018-04-24 11:15:19

标签: python-3.x opencv image-segmentation

我有一张黑白图像,一张文字文件。我希望能够获得每个角色的边界框列表。我自己尝试过一种算法,但这需要花费的时间过长,而且只是有些成功。有没有我可以用来查找边界框的python库?我一直在研究opencv,但文档很难遵循。在这个tutorial中,我甚至无法破译是否找到了边界框,因为我无法轻易找到函数的实际功能。

2 个答案:

答案 0 :(得分:4)

您可以使用boundingRect()。确保图像背景为黑色,图像中的文本为白色。使用此代码可以在图像中的文本周围绘制矩形。要获取每个矩形的列表,请根据您的要求添加相应的代码段。

import cv2
img = cv2.imread('input.png', 0) 
cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU,img)

image, contours, hier = cv2.findContours(img, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
for c in contours:
    # get the bounding rect
    x, y, w, h = cv2.boundingRect(c)
    # draw a white rectangle to visualize the bounding rect
    cv2.rectangle(img, (x, y), (x + w, y + h), 255, 1)

cv2.drawContours(img, contours, -1, (255, 255, 0), 1)

cv2.imwrite("output.png",img)

答案 1 :(得分:2)

我建议您查看openCV库中的boundingRect()函数:

https://docs.opencv.org/2.4/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html

文档基于cpp,但也可以在python中实现。