gpt4 book ai didi

python opencv crop使用等高线层次结构

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:07 26 4
gpt4 key购买 nike

我想删除下图中的边框 enter image description here

到目前为止,我一直在尝试使用 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)

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

enter image description here

更新:

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

enter image description here

已编辑

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

enter image description here

但是结果是这样的

enter image description here

我如何才能完全移除边界框。

最佳答案

为此我们使用 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()

result

关于python opencv crop使用等高线层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50728186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com