Search code examples
opencvcontour

Draw a contour around eye


I want to draw the contour around extracted sclera. (Sclera segmentation was done by using this way).

This is the output, I got after follow the below given code.

Output of the following code

This is actual output I want to get.

Output I want

    import numpy as np 
    from cv2 import cv2
    from matplotlib import pyplot as plt
    
    img = cv2.imread('sclera.jpg',1)
    gray = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
    cv2.imshow("Adaptive gray Image",gray)
    
    #Contours
    contours, hierarchy = cv2.findContours(gray,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 
    
    img2 = img.copy()
    index = -1 #if negative all contours are drawn, index of contour to be drawn
    thickness = 2
    color = (5,228,72)
    cv2.drawContours(img2,contours,index,color,thickness)
    # cv2.imshow('Contours',img2)
    
    for cnt in contours:
        area = cv2.contourArea(cnt)
        print("Detected Contour with Area: ", area)
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    img3 = cv2.cvtColor(img2,cv2.COLOR_RGB2BGR)
    plt.imshow(img3)

Is anybody know why I get the lot of contours in my output? Where could be caused to produce the wrong output?

Any suggestions would appreciate.


Solution

  • Before doing binarization, you need to additionally blur the image to eliminate unnecessary details for which the contour detection algorithm of your choice clings. Use Gaussian Blur to eliminate high-frequency data at the expense of a larger blur radius and amount. Then binarize the image. And only after your image looks like a white spot of the sclera on a black background - only then the contour detection algorithm will give you the correct contour of the sclera.

    You can also use the erosion and dilation operations to eliminate many noisy data points and improve contour fit to the shape of the sclera. This should be done after binarization, then you will have a good pre-image for processing by the edge detection algorithm.

    In general, you will have the following sequence of actions:

    1. Converting an image to gray
    2. Gaussian blur with a large kernel
    3. Binarization to black and white image
    4. Sequences of erosion-dilation operations
    5. Finding the contour and choosing the largest