gpt4 book ai didi

python - 围绕水印opencv的轮廓

转载 作者:行者123 更新时间:2023-12-02 15:57:30 30 4
gpt4 key购买 nike

我想在图像中的水印周围画一个框。我提取了水印并找到了轮廓。然而,轮廓并未围绕水印绘制。轮廓是在我的整个图像上绘制的。请帮助我提供正确的代码。

轮廓坐标的输出是:

[array([[[  0,   0]],

[[ 0, 634]],

[[450, 634]],

[[450, 0]]], dtype=int32)]

输出图像为:

enter image description here

我的代码片段如下:

img = cv2.imread('Watermark/w3.png')

gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bg = gr.copy()

closing = cv2.morphologyEx(bg, cv2.MORPH_CLOSE, kernel) #dilation followed by erosion
#plt.imshow(cv2.subtract(img,opening))
plt.imshow(closing)

_,contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(contours)
print(len(contours))

if len(contours)>0 :
cnt=contours[len(contours)-1]
cv2.drawContours(closing, [cnt], 0, (0,255,0), 3)

plt.imshow(closing)

最佳答案

findContours 函数很难找到您的框轮廓,因为它需要运行一个二值图像。来自documentation :

For better accuracy, use binary images. So before finding contours, apply threshold or canny edge detection.

In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black.

因此,在 cvtColor 函数应用 threshold 后确保您有黑色背景。

...
img = cv2.imread('sample.png')
gr = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, bg = cv2.threshold(gr, 127, 255, cv2.THRESH_BINARY_INV)
...

如果您在这个二值图像上运行findContours,您会发现多个框

enter image description here enter image description here

要获得围绕整个文本的单个框,您可以在morphologyEx 函数,创建一个单一的 blob。

...
kernel = np.ones((3,3))
closing = cv2.morphologyEx(bg, cv2.MORPH_CLOSE, kernel, iterations=5)
...

因此,在创建 blob 之后应用您已经拥有的 findContours 并使用 minAreaRect找到包含通过的点集的最小面积的旋转矩形。

...
contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print(len(contours))

for i in range(len(contours)):
rect = cv2.minAreaRect(contours[i])
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img,[box],0,(127,60,255),2)

cv2.imwrite("output_box.png", img)

enter image description here enter image description here

关于python - 围绕水印opencv的轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63763147/

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