首页 > 解决方案 > 如何轮廓图像中的多个最大对象

问题描述

我正在尝试提取图像中多个最大对象的轮廓。目前我只能提取最大的对象之一,其他对象没有轮廓。这是阈值后的图像,我正在测试。

测试图像 在此处输入图像描述

cntrs = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
# create black background image
result = np.zeros_like(src)
area_thresh = 0
for c in cntrs:
    area = cv2.contourArea(src)
    if area > area_thresh:
        area_thresh = area
        big_contour = c

这是我目前使用的代码,它只提取一个对象。

标签: pythonopencv

解决方案


Try this:

import cv2

# Read the image
img=cv2.imread('test.jpg')

# Convert to Gray
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply threshold and Dilate (to bring out the lines of the plane)
ImgThresh = cv2.threshold(imgGray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
ImgThreshDilation = cv2.dilate(ImgThresh,(3,3),iterations = 2)

# Find edges
imgEdges = cv2.Canny(ImgThreshDilation,100,200)

# Find contour
contours,hierarchy =cv2.findContours(imgEdges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 

# Loop through contours and find the two biggest area.
for cont in contours:
    area=cv2.contourArea(cont)
    if area>300:
        #print(area)
        cv2.drawContours(img,cont,-1,(0,0,255),2)

cv2.imshow('Image with planes in Red',img)

Final Result in red

Here is an edit of the above code.

import cv2

# Read the image
img=cv2.imread('test.jpg')
imgCont=img.copy()

# Convert to Gray
imgGray =255- cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Find edges
imgEdges = cv2.Canny(imgGray,150,200)

# Find contour
contours,hierarchy =cv2.findContours(imgEdges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 

# Loop through contours and find the two biggest area.
for cont in contours:
    area=cv2.contourArea(cont)
    if area>150:
        #print(area)
        cv2.drawContours(imgCont,cont,-1,(0,0,255),5)

# Save your pictures with the contour in red
cv2.imwrite('Image with planes in Red.jpg',imgCont)

The result: Result for the second Code


推荐阅读