简体   繁体   English

如何找到联合矩形的轮廓

[英]how to find the outline of union rectangles

I have coordinates of each rectangles and want to find the outlines of union rectangles. 我有每个矩形的坐标,想找到并集矩形的轮廓。 矩形

矩形的轮廓

So what I did is that just drew and colored all rectangles with the coordinates. 所以我要做的就是绘制所有带有坐标的矩形并为其上色。 And found the contour of all rectangles. 并找到所有矩形的轮廓。 彩色的矩形

But I want to know that if there are some kind of algorithms doing the same thing only with coordinates information. 但是我想知道是否有某种算法仅使用坐标信息来做同样的事情。 So that I don't need to draw and color the whole rectangles. 这样我就不需要绘制和着色整个矩形。 (there are more than 4000 rectangles so it is computationally expensive) (有超过4000个矩形,因此计算量很大)

Using contour detection you can achieve what you want. 使用轮廓检测​​可以实现您想要的。 For that you should have a good knowledge about contour hierarchy style used in OpenCV. 为此,您应该对OpenCV中使用的轮廓层次样式有很好的了解。 There are a few contour retrieval modes. 有几种轮廓检索模式。 Such as cv2.RETR_LIST , cv2.RETR_TREE , cv2.RETR_CCOMP , cv2.RETR_EXTERNAL . 例如cv2.RETR_LISTcv2.RETR_TREEcv2.RETR_CCOMPcv2.RETR_EXTERNAL You can check the documentation for more information. 您可以查看文档以获取更多信息。

In your case you should use cv2.RETR_EXTERNAL in order to retrieve extreme outer contour of the image. 在您的情况下,应使用cv2.RETR_EXTERNAL来检索图像的外部轮廓。

This is the solution code: 这是解决方案代码:

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: OUTPUT:

findContours is the function you are looking for. findContours是您要寻找的功能。 The code bellow explains how it works. 下面的代码说明了它是如何工作的。

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

The result: 结果: 代码的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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