繁体   English   中英

如何找到联合矩形的轮廓

[英]how to find the outline of union rectangles

我有每个矩形的坐标,想找到并集矩形的轮廓。 矩形

矩形的轮廓

所以我要做的就是绘制所有带有坐标的矩形并为其上色。 并找到所有矩形的轮廓。 彩色的矩形

但是我想知道是否有某种算法仅使用坐标信息来做同样的事情。 这样我就不需要绘制和着色整个矩形。 (有超过4000个矩形,因此计算量很大)

使用轮廓检测​​可以实现您想要的。 为此,您应该对OpenCV中使用的轮廓层次样式有很好的了解。 有几种轮廓检索模式。 例如cv2.RETR_LISTcv2.RETR_TREEcv2.RETR_CCOMPcv2.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM