gpt4 book ai didi

python - Opencv:如何在不删除任何其他字符的情况下删除矩形黑框

转载 作者:行者123 更新时间:2023-12-02 16:29:51 25 4
gpt4 key购买 nike

我想从下面的图像中删除一个矩形的黑匣子。

enter image description here

我进行一些预处理操作以仅保留图像的顶部。我的问题是图像中间的矩形

这是我对此图像执行的预处理操作

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




binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 2)


binary = cv2.fastNlMeansDenoising(binary, None, 65, 5, 21)


ret, thresh1 = cv2.threshold(binary, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

k = np.ones((4,4))
binary = cv2.morphologyEx(thresh1, cv2.MORPH_CLOSE, k)

这是到目前为止的输出

enter image description here

在这里,似乎有3条线连接在一起。我用过 cv2.findContours。但是直到现在我仍然无法删除此矩形。我知道我在轮廓方面做错了。

这是我用于检测轮廓的代码
_,binary = cv2.threshold(image, 150, 255, cv2.THRESH_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= image.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.05*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)

如何在不扭曲字母 的情况下成功删除此黑色矩形Q

最佳答案

我使用了cv2.fillConvexPoly()而不是cv2.floodFill()。为什么?

我首先发现轮廓具有最高的周长,并将其点存储在变量中。然后,我使用cv2.fillConvexPoly()用任何颜色(在本例中为黑色(0, 0, 0))填充具有最高周长的轮廓。

代码:

_, binary = cv2.threshold(im, 150, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('binary', binary)

enter image description here
#--- taking a copy of the image above ---
b = binary.copy()

#--- finding contours ---
i, contours, hierarchy = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

im2 = img.copy()
max_peri = 0 #--- variable to store the maximum perimeter
max_contour = 0 #--- variable to store the contour with maximum perimeter

# determine which contour belongs to a square or rectangle
for cnt in contours:
peri = cv2.arcLength(cnt, True)
print(peri)
if peri > max_peri:
max_peri = peri
max_contour = cnt

#---- filling the particular contour with black ---
res = cv2.fillConvexPoly(b, max_contour, 0)

cv2.imshow('res.jpg', res)

enter image description here

关于python - Opencv:如何在不删除任何其他字符的情况下删除矩形黑框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51005083/

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