Reputation: 37
I'm trying to extract the contours of multiple largest objects within an image. Currently I can only extract the one of the largest objects and the other objects are not contoured. This is the image after threshold, that i'm testing with.
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
This is the code I'm currently using that only extracts one object.
Upvotes: 1
Views: 1214
Reputation: 462
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)
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)
Upvotes: 3