[英]how to find the outline of union rectangles
使用轮廓检测可以实现您想要的。 为此,您应该对OpenCV中使用的轮廓层次样式有很好的了解。 有几种轮廓检索模式。 例如cv2.RETR_LIST
, cv2.RETR_TREE
, cv2.RETR_CCOMP
, cv2.RETR_EXTERNAL
。 您可以查看文档以获取更多信息。
在您的情况下,应使用cv2.RETR_EXTERNAL
来检索图像的外部轮廓。
这是解决方案代码:
import cv2
im = cv2.imread('test.png')
imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
cv2.bitwise_not(imgray,imgray)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(im, contours, -1, (0,255,0), 3)
cv2.imshow("image", im)
cv2.waitKey(0)
OUTPUT:
findContours
是您要寻找的功能。 下面的代码说明了它是如何工作的。
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("./outline_rect.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
thresh = 255-thresh
_, cnts, _ = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
maxArea = 0
best = None
for contour in cnts:
area = cv2.contourArea(contour)
if area > maxArea :
maxArea = area
best = contour
cv2.drawContours(img, [best], 0, (0, 0, 255), 3)
while True:
cv2.imshow("result", img)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.