我想从下面的图像中删除一个矩形黑框。
我做了一些预处理操作以仅保留图像的顶部。我的问题是图片中间的矩形
这是我对此图片执行的预处理操作
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)
这是到目前为止的输出
在这里出现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
的情况下成功删除该黑色矩形答案 0 :(得分:1)
我使用cv2.fillConvexPoly()
而不是cv2.floodFill()
。为什么?
我首先发现轮廓具有最高的周长,并将其点存储在变量中。然后,我用cv2.fillConvexPoly()
用任何颜色(在本例中为黑色(0, 0, 0)
)填充具有最高周长的轮廓。
代码:
_, binary = cv2.threshold(im, 150, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('binary', binary)
#--- 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)