Как мне очертить несколько самых больших объектов на изображении - PullRequest
0 голосов
/ 27 апреля 2020

Я пытаюсь извлечь контуры нескольких самых больших объектов в изображении. В настоящее время я могу извлечь только один из самых больших объектов, а другие объекты не очерчены. Это изображение после порога, с которым я тестирую.

testing image enter image description here

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

Это код, который я сейчас использую, извлекает только один объект.

1 Ответ

0 голосов
/ 27 апреля 2020

Попробуйте это:

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

Вот правка вышеуказанного кода.

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)

Результат : Result for the second Code

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...