简体   繁体   English

如何从图像中识别最大的边界矩形并使用 Opencv 和 python 将它们分成单独的图像

[英]How to identify largest bounding rectangles from an image and separate them into separate images using Opencv and python

I am new to Opencv and python and trying to identify the largest three rectangles as marked in the sample image and extract them into three separate images.我是 Opencv 和 python 的新手,并试图识别示例图像中标记的最大三个矩形并将它们提取到三个单独的图像中。 I am able to identify contours in the image but all of them are showing up (as shown in second image ) and I am not able to separate out the three largest ones.我能够识别图像中的轮廓,但所有轮廓都显示出来(如第二张图像所示),我无法分离出三个最大的轮廓。 Code I have written so far:到目前为止我写的代码:

import cv2

image = cv2.imread('imgpath')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray, 130, 255, 1)

cnts = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

#largest_contours = sorted(cnts, key=cv2.contourArea)[-3:]
#print(len(largest_contours))
for c in cnts:
    cv2.drawContours(image,[c], 0, (0,255,0), 3)

#cv2.imshow("result", image)
#cv2.drawContours(image, largest_contours, -1, (0,255,0), 3)
cv2.imshow('contours', image)
cv2.waitKey(0)

Sort the contours according to their area and then pick the top three.根据轮廓的面积对轮廓进行排序,然后选择前三个。

    cnts = sorted(cnts, key=lambda c: cv2.contourArea(c), reverse=True)
    for c in cnts[:3]:
        cv2.drawContours(image,[c], 0, (0,255,0), 3)
        (x,y,w,h) = cv2.boundingRect(c)    

(x,y,w,h) represent co-ordinates (x,y), width and height of the contour. (x,y,w,h) 表示轮廓的坐标 (x,y)、宽度和高度。 These values can be used to crop out the rectangle.这些值可用于裁剪矩形。

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

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