Search code examples
pythonopencvimage-processing

How to detect black contour in image using open-cv


I have an image showed below (this image is a result of pre-processing of original image I had):

enter image description here

What I am trying to do is to detect the contour for the Black region bounded by 2 white regions (please note that white regions are not always solid and there could be 2, 3,... disconnected white region on top - for most of pictures the white regions are continuous; however, there are some examples where top white region is not continuous - Please see update section of my question to see example of non-continuous region)

Do you have any suggestion as how I can detect the boundary of black region and separate the black region?


Solution

  • Here is how:

    import cv2
    import numpy as np
    
    img = cv2.imread(r"D:\OpenCV Projects\Black Contour\image.jpg")
    
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    lower = np.array([0, 0, 75])
    upper = np.array([179, 179, 115])
    mask = cv2.inRange(img_hsv, lower, upper)
    
    mask_blur = cv2.GaussianBlur(mask, (3, 3), 1)
    _, thresh = cv2.threshold(mask_blur, 200, 255, cv2.THRESH_BINARY)
    
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    
    cv2.drawContours(img, [max(contours, key=cv2.contourArea)], -1, (255, 0, 0), 3)
    cv2.imshow("Image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    Output:

    enter image description here

    Here is all the processing the image went through during the execution of the above code:

    BGR to HSV:

    enter image description here

    HSV to mask:

    enter image description here

    Mask to blurred mask:

    enter image description here

    Blurred mask to thresholded mask:

    enter image description here

    From here, simply detect the contour from the image above and draw it onto the image.