(image: Mat, mode: Any, method: int, contours: ... = ..., hierarchy: ... = ..., offset: ... = ...) -> Any image Source, an 8-bit single-channel image. Non-zero pixels are treated as1's. Zero findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> contours, hierarchy @brief Finds contours in a binary image. The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the OpenCV sample directory.
@brief Draws contours outlines or filled contours.
The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve connected components from the binary image and label them: :
area = [] for j inrange(len(contours)): area.append(cv2.contourArea(contours[j])) max_idx = np.argmax(area) area[max_idx] = 0 sub_max_idx = np.argmax(area)
for k inrange(len(contours)): if k != max_idx and k != sub_max_idx: cv2.fillPoly(img, [contours[k]], 0) cv2.imshow("img",img) cv2.waitKey(0) cv2.destroyAllWindows()
deffind_max_contour(img): ''' input shape: (300, 300, 3) first channel: background second channel: class 1 third channel: class 2 ''' h,w,d = img.shape label = np.zeros((h,w)) for i inrange(d): if i == 0: continue else: img_channel = img[:,:,i] contours, _ = cv2.findContours(img_channel, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) area = [] for j inrange(len(contours)): area.append(cv2.contourArea(contours[j])) max_idx = np.argmax(area) for k inrange(len(contours)): if k == max_idx: cv2.fillPoly(label, [contours[k]], i) return label