top of page

Contours Detection

Summary

  Contours Detection with open cv example.

  Detect contours around objects in an image.

​

Example

   

    import  cv2   

    import numpy as np

    import matplotlib.pyplot as plt

    

    

    img = cv2.imread(file_path,0)


    plt.figure(1)
    plt.imshow(
img,cmap='gray')
   

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

    contours,hierarchy = cv2.findContours(img, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
 

    external_contours = np.ones(img.shape)

    for i in range(len(contours)):
       
if hierarchy[0,i,3]==-1:
            cv2.drawContours(external_contours, contours, i,
255,-1)

​

    plt.figure(2)
    plt.imshow(external_contours,cmap='
gray')

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

 


    internal_contours = np.ones(img.shape)
    for i in range(len(contours)):
        if hierarchy[0,i,3]!=-1:

            cv2.drawContours(internal_contours, contours, i, 255,-1)


    plt.figure(3)
    plt.imshow(internal_contours,cmap='
gray')

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

​

01.png
02.png
03.png
bottom of page