【问题标题】:python opencv crop using contour hierarchypython opencv裁剪使用轮廓层次结构
【发布时间】:2018-06-18 01:50:11
【问题描述】:

我希望从下图中删除边框

到目前为止,我尝试过的是使用 OpenCV 来获取边缘 代码:

def autocrop(image, threshold=0):
    """Crops any edges below or equal to threshold

    Crops blank image to 1x1.

    Returns cropped image.

    """
    if len(image.shape) == 3:
        flatImage = np.max(image, 2)
    else:
        flatImage = image
    assert len(flatImage.shape) == 2

    rows = np.where(np.max(flatImage, 0) > threshold)[0]
    if rows.size:
        cols = np.where(np.max(flatImage, 1) > threshold)[0]
        image = image[cols[0]: cols[-1] + 1, rows[0]: rows[-1] + 1]
    else:
        image = image[:1, :1]

    return image

no_border = autocrop(new_image)


cv2.imwrite('no_border.png',no_border)

结果是这张图片,接下来如何移除那些框

更新:

我发现该解决方案适用于白色背景,但是当我更改背景颜色时,边框不会被删除

已编辑

我已经尝试了这张图片的解决方案

但是结果是这样的

我怎样才能完全去除边界框。

【问题讨论】:

  • 我已经编写了一个简洁的代码来使用轮廓中的层次概念来识别字符。无需编写复杂的代码来裁剪和切割。请看下面的答案!

标签: python opencv


【解决方案1】:

为此,我们使用floodFill 函数。

import cv2
import numpy as np

if __name__ == '__main__':
    # read image and convert to gray
    img = cv2.imread('image.png',cv2.IMREAD_UNCHANGED)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # threshold the gray image to binarize, and negate it
    _,binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
    binary = cv2.bitwise_not(binary)

    # find external contours of all shapes
    _,contours,_ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

    # create a mask for floodfill function, see documentation
    h,w,_ = img.shape
    mask = np.zeros((h+2,w+2), np.uint8)

    # determine which contour belongs to a square or rectangle
    for cnt in contours:
        poly = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt,True),True)
        if len(poly) == 4:
            # if the contour has 4 vertices then floodfill that contour with black color
            cnt = np.vstack(cnt).squeeze()
            _,binary,_,_ = cv2.floodFill(binary, mask, tuple(cnt[0]), 0)
    # convert image back to original color
    binary = cv2.bitwise_not(binary)        

    cv2.imshow('Image', binary)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

【讨论】:

  • 非常感谢它有效。小编辑,因为 i 未定义
  • 你认为背景颜色的解决方案是什么?
  • @ahmedosama 您的新图像已经具有白色前景。所以不需要这两行:binary = cv2.bitwise_not(binary)。注释掉这两行。
  • 对不起,新图像是蓝色背景,白色背景是代码的输出。我将删除它以使一切清楚
  • 我添加了新图像。代码在上部工作正常,下部显示为黑色,当我删除 binary = cv2.bitwise_not(binary) 链接 imgur.com/a/20Go16w
【解决方案2】:

还有另一个可以在图像中找到字符。这在轮廓中使用了层次结构的概念。

实现在python中:

path = r'C:\Desktop\Stack'
filename = '2.png'

img = cv2.imread(os.path.join(path, filename), 1)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY|cv2.THRESH_OTSU)

_, contours2, hierarchy2 = cv2.findContours(binary, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)

请注意,在cv2.findContours() 函数中,RETR_CCOMP 参数中传递了根据其不同层次结构级别存储轮廓。当一个轮廓位于另一个轮廓内时,层次结构很有用,因此可以实现父子关系。 RETR_CCOMP 有助于识别这种关系。

img2 = img.copy()
l = []
for h in hierarchy2[0]:
    if h[0] > -1 and h[2] > -1:
        l.append(h[2]) 

在上面的 sn-p 中,我将所有有孩子的轮廓传递到列表 l 中。使用l 我在下面的sn-p 中绘制这些轮廓。

for cnt in l:
    if cnt > 0:
        cv2.drawContours(img2, [contours2[cnt]], 0, (0,255,0), 2)

cv2.imshow('img2', img2)          

查看DOCUMENTATION HERE 以了解有关轮廓层次结构的更多信息。

【讨论】:

  • 这是一个不错的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
  • 2021-09-23
  • 2021-02-01
  • 1970-01-01
相关资源
最近更新 更多