简体   繁体   English

在 OpenCV 中裁剪垂直计数,获取边界框边框而不是区域

[英]Cropping vertical countours in OpenCV, getting bounding box borders instead of area

I am trying to extract columns of a table in an image using opencv .我正在尝试使用opencv提取图像中表的列。 I have managed to successfully identify the vertical regions of interest as shown in the image below:我已成功识别出感兴趣的垂直区域,如下图所示:

图片

My problem is when I am trying to extract and save those regions of interest I am getting a 6 vertical lines of the border of the bounding rectangle as opposed to the region in between them.我的问题是,当我尝试提取和保存这些感兴趣的区域时,我得到了边界矩形边界的 6 条垂直线,而不是它们之间的区域。

This is the code I am using to achieve this:这是我用来实现此目的的代码:

import cv2
import numpy as np

image = cv2.imread('x.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3,3), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,50))
vertical_mask = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=1)
 
cnts = cv2.findContours(vertical_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
for c in cnts:
    cv2.drawContours(image, [c], -1, (36,255,12), -1)

idx = 0
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)

    idx+=1
    new_img=image[y:y+h,x:x+w]
    cv2.imwrite(str(idx) + '.png', new_img)

cv2.imshow("im.png",image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Any ideas as to how I can solve this problem?关于如何解决这个问题的任何想法? Edit: This 2 is is the image of the right most border, as you can see there is some text编辑:这2是最右边的边框的图像,你可以看到有一些文字

The bounding boxes you are drawing are from each line, not from the columns.您正在绘制的边界框来自每一行,而不是来自列。 What you should do is take the two points from some line, take the other two points from the line next to it, and using this 4 points you have defined the rectangle which is your column.你应该做的是从某条线上取两个点,从它旁边的线上取另外两个点,并使用这 4 个点定义你的列的矩形。

All this, of course assuming they are sorted from left to right, by coordinates.所有这一切,当然假设它们是按坐标从左到右排序的。 But opencv doesn't guarantee us they are sorted that way.但是 opencv 并不能保证它们是这样排序的。 So sort them first, and then draw rectangles over consecutive two lines所以先对它们进行排序,然后在连续的两行上绘制矩形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM