我是 Opencv 和 python 的新手,试图识别示例图像中标记的最大的三个矩形,并将它们提取到三个单独的图像中。我能够识别图像中的轮廓,但所有轮廓都显示出来(如第二张图所示),并且我无法区分出三个最大的轮廓。到目前为止我写的代码:
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)
Run Code Online (Sandbox Code Playgroud)