问题描述
我想在图像中的水印周围画一个方框。我提取了水印并找到了轮廓。但是,轮廓不会围绕水印绘制。轮廓绘制在我的整个图像上。请为我提供正确的代码。
轮廓坐标的输出为:
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
输出图像为:
我的代码段如下:
[array([[[ 0,0]],[[ 0,634]],[[450,0]]],dtype=int32)]
解决方法
函数findContours
很难找到您的盒子轮廓,因为它希望运行在二进制图像上。来自documentation:
为获得更高的准确性,请使用二进制图像。因此,在找到轮廓之前,请应用阈值或坎尼边缘检测。
在OpenCV中,找到轮廓就像从黑色背景中找到白色物体。因此请记住,要找到的对象应该是白色,背景应该是黑色。
因此,在执行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
,则会发现多个框
要在整个文本中找到一个方框,可以在搜索框上搜索iterations
参数的数量。
morphologyEx
函数可创建一个Blob。
...
kernel = np.ones((3,3))
closing = cv2.morphologyEx(bg,cv2.MORPH_CLOSE,kernel,iterations=5)
...
因此,在创建斑点后,应用您已经拥有的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],(127,60,255),2)
cv2.imwrite("output_box.png",img)