首页 > 解决方案 > Python - cv2 查找轮廓

问题描述

想把文档里所有的大元素都找出来,但是不知道怎么控制大小(文档是从网上下载的:))

我有一个文件

在此处输入图像描述

我写了一个简单的代码

import cv2
import pytesseract

image = cv2.imread('2.png')

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7, 7), 0)
thresh = cv2.threshold(
    blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

kernal = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 50))
dilate = cv2.dilate(thresh, kernal, iterations=1)

cv2.imwrite('1_dilated.png', dilate)

cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cnts = cnts[0] if len(cnts) == 2 else cnts[1]

cnts = sorted(cnts, key=lambda x: cv2.boundingRect(x)[1])

for c in cnts:
    x, y, w, h = cv2.boundingRect(c)
    if h > 100 and w > 100:
        roi = image[y:y+h, x:x+w]
        cv2.rectangle(image, (x, y), (x+w, y+h), (36, 255, 12), 2)
        # ocr = pytesseract.image_to_string(roi)
        # print(ocr)
cv2.imwrite('1_boxes4.png', image)

但只检测到它

在此处输入图像描述

我想要这个

在此处输入图像描述

如何控制检测区域的大小?

非常感谢您的所有评论

标签: pythonopencvpython-tesseract

解决方案


你很接近,但你需要增加dilate操作的迭代次数。此外,矩形structuring element可能有助于更好地形成文本块。让我们检查一下您的代码的一些可能的改进:

# imports:
import cv2
import numpy as np

# Set image path
imagePath = "D://opencvImages//"
imageName = "F74Yq.png"    

# Read image:
inputImage = cv2.imread(imagePath + imageName)

# Store a deeep copy for results:
inputCopy = inputImage.copy()

# Convert BGR to grayscale:
grayInput = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)

# Threshold via Otsu
_, binaryImage = cv2.threshold(grayInput, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)

第一部分生成输入图像的二进制图像,这里没有什么花哨的 - 只是通过Otsu's 方法的直接阈值。这是获得的二值图像:

现在,让我们应用该dilate操作。让我们使用一个9 x 9矩形内核并将迭代次数设置为5。一定要小心不要dilate太多,因为来自文档不同部分的文本块最终可能会合并:

# Set kernel (structuring element) size:
kernelSize = (9, 9)

# Set operation iterations:
opIterations = 5

# Get the structuring element:
morphKernel = cv2.getStructuringElement(cv2.MORPH_RECT, kernelSize)

# Perform Dilate:
dilateImage = cv2.morphologyEx(binaryImage, cv2.MORPH_DILATE, morphKernel, None, None, opIterations, cv2.BORDER_REFLECT101)

这是结果:

好的,现在让我们检测外部轮廓并获取它们bounding boxes,以便我们可以在目标区域周围绘制矩形。请注意,我在输入的深层副本上绘制矩形:

# Find the contours on the binary image:
contours, hierarchy = cv2.findContours(dilateImage, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Look for the outer bounding boxes (no children):
for _, c in enumerate(contours):

    # Get the contours bounding rectangle:
    boundRect = cv2.boundingRect(c)

    # Get the dimensions of the bounding rectangle:
    rectX = boundRect[0]
    rectY = boundRect[1]
    rectWidth = boundRect[2]
    rectHeight = boundRect[3]

    # Set bounding rectangle:
    color = (0, 0, 255)
    cv2.rectangle( inputCopy, (int(rectX), int(rectY)),
                   (int(rectX + rectWidth), int(rectY + rectHeight)), color, 5 )

    cv2.imshow("Bounding Rectangles", inputCopy)
    cv2.waitKey()

这是最终结果:


推荐阅读