python - OpenCV Python : find contours/edges/rectangle in an image

标签 python opencv computer-vision ocr tesseract

我使用的是Python2.7.12和OpenCV 3.0.0-rc1

我正在从事一个文本识别项目。

这就是我现在得到的。 Original iamge after findContour, line 34

正如您所看到的,图像包含很多“框”,其中有文本。

我的方法是找到这些框,将它们剪切成单独的图像,然后将它们输入 TesseractOCR。

程序将整个图像视为一个轮廓。 我怎样才能找到里面较小的那个?

或者,如果您有其他方法,欢迎

代码:

import cv2


def threshold(im, method):
    # make it grayscale
    im_gray = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)

    if method == 'fixed':
        threshed_im = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY)

    elif method == 'mean':
        threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 10)

    elif method == 'gaussian':
        threshed_im = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5, 7)

    else:
        return None

    return threshed_im


image = cv2.imread('demo4.jpg')

# threshold it
thresh = threshold(image, 'mean')

# find contours
_, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print len(cnts)

cv2.drawContours(image, cnts, -1, (0, 255, 0), 20)
cv2.imshow('contours', image)
cv2.waitKey()

cv2.drawContours(thresh, cnts, -1, (0, 255, 0), 20)
cv2.imshow('contours', thresh)

cv2.waitKey()

`

最佳答案

由于您指定了cv2.RETR_EXTERNAL,因此您仅获得最外层轮廓。要获取图像的所有轮廓,您应该调用如下方法:

cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

看看OpenCV documentation看看这个函数是如何工作的。

关于python - OpenCV Python : find contours/edges/rectangle in an image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38348322/

相关文章:

c++ - 使用 OpenCV 丢弃细胞图像中的异常值 SIFT 关键点

python - 如何只提取括号之间的字符串部分?

python - int ('1010' ,2) 的时间复杂度是多少?

opencv - 使用图像序列的 3D 模型

ios - opencv sift算法,如何从findHomography获得置信度

opencv - 使用OpenCV检测拐角后绘制一个不相交的多边形

python - 让 python -m 模块为用 C 实现的模块工作

python - 将列表列表附加到 pd.Dataframe()

c++ - OpenCV VideoCapture() 不起作用 - Ubuntu

c++ - 复制排序矩阵的一行并保存到文件 - opencv3