简体   繁体   中英

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)

Using contour detection you can achieve what you want. For that you should have a good knowledge about contour hierarchy style used in OpenCV. There are a few contour retrieval modes. Such as cv2.RETR_LIST , cv2.RETR_TREE , cv2.RETR_CCOMP , cv2.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.

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:

findContours is the function you are looking for. 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: 代码的结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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