We can detect the borders of objects with contour. It is often first step of many interesting applications such as image foreground extraction, image segmentation, detection and recogination
What is contours?
When we join all the points on the boundary of an object, we get a contour. Typically, a specific contour refers to boundary pixels that have same color and intensity. Opencv prodives 2 simple functions
1. findCountours (assosisated with 2 differen algorithms CHAIN_APPROX_SIMPLE, CHAIN_APPROX_NONE)
2. drawContours()
Steps to detect and draw contours
1. Read image
2. Apply binary thresholding (binary thresholding or canny edge detection to gray image, this will convert the image to black and white, highlight the objects of interest to make things easy for contours detection.
3. find and draw Countours
image = cv2.imread(‘xxxx’)
image_gray = cv2.cvtColor(BGR2GRAY)
ret, thresh = cv2.threshhold(image_gray, 200. 255, cv2.THRESH_BINARY)
contours, hie = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
image_copy = np.zeros(image.shape, np.uint8)
image_copy[:]= (0,0,255)
count = 0
for contour in contours:
if cv2.contourArea(contour) < 100000: continue
if cv.contourArea(contour) > 200000: continue
(x,y,w,h) = cv2.boundingRect(contour)
cv2.rectangle(image_copy, (x,y), (x+w, y+h),(0,255,0),2)
count += 1
cv2.imwrite(“data/tf_” +str(count)+”.jpg”, image[y:y+h, x:x+w])
cv2.imshow(‘CONTOURS’, image_copy)
cv2.waitKey(0)
Cv2.destroyAllWindows()