【问题标题】:Extract contours from bounding-box从边界框中提取轮廓
【发布时间】:2018-02-10 16:24:36
【问题描述】:

我找到了这个关于 SWT 轮廓的示例:Extracting text OpenCV

在我的示例(如下)中效果很好,但我需要从代码中再做一件事:它检测到的矩形(在文本内)应该被一一提取。

如何使用以下代码做到这一点?我想到了一个循环,但我不知道该怎么做。

import cv2

image = cv2.imread("card.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours

# for each contour found, draw a rectangle around it on original image
for contour in contours:
    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # discard areas that are too large
    if h>300 and w>300:
        continue

    # discard areas that are too small
    if h<40 or w<40:
        continue

    # draw rectangle around contour on original image
    cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)

# write original image with added contours to disk  
cv2.imwrite("contoured.jpg", image)

根据要求,这是原始图像:

【问题讨论】:

  • 发布您的原始图片。
  • 添加原图

标签: python opencv bounding-box


【解决方案1】:

首先使用形态学运算确保所有数字格式正确并去除噪声,然后使用 findcontour 函数分别获取每个数字

【讨论】:

  • 嗨看看我的(自我)答案。它似乎做得很好:answer
【解决方案2】:

使用此代码来完成这项工作。它检测图像中的文本/数字区域。

import cv2

image = cv2.imread("C:\\Users\\Bob\\Desktop\\PyHw\\images\\test5.png")
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # grayscale
_,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV) # threshold
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(3,3))
dilated = cv2.dilate(thresh,kernel,iterations = 13) # dilate
_, contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) # get contours


idx =0
# for each contour found, draw a rectangle around it on original image
for contour in contours:

    idx += 1

    # get rectangle bounding contour
    [x,y,w,h] = cv2.boundingRect(contour)

    # discard areas that are too large
    if h>300 and w>300:
        continue

    # discard areas that are too small
    if h<40 or w<40:
        continue

    # draw rectangle around contour on original image
    #cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,255),2)

    roi = image[y:y + h, x:x + w]

    cv2.imwrite('C:\\Users\\Bob\\Desktop\\' + str(idx) + '.jpg', roi)

    cv2.imshow('img',roi)
    cv2.waitKey(0)

代码基于其他问题/答案:Extracting text OpenCV

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    相关资源
    最近更新 更多