Search code examples
pythonopencvimage-processing

Stripe border or contour detection in grayscale image using OpenCV


I have an grayscale image, and I've tried some methods such as findContour and HoughLinesP to detect the stripe in the image attached. The output does not reflect the expected detection. One of my example codes is below, using findContour. However, the script detects other regions outside the stripe area.

How could the stripe (contour/border) be detected properly?

import cv2
import imutils

img = cv2.imread('image.png', cv2.IMREAD_GRAYSCALE)
img = cv2.GaussianBlur(img, (5, 5), 0)

ret,thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

cnts = cv2.findContours(image=thresh, mode=cv2.RETR_EXTERNAL,
                                   method=cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)

img_col = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

image_copy = img_col.copy()
cv2.drawContours(image=image_copy, contours=[c], contourIdx=-1,
             color=(0, 255, 0), thickness=1, lineType=cv2.LINE_AA)
# see the results
cv2.imshow('Output', image_copy)
cv2.waitKey(0)

Input

Output


Solution

  • if you know dark stripe is horizontal, checking the mean value for each rows may be able to be help.

    The figure below is just drawing each row with mean value. (sinse data is 1D, width of this figure is meaningless).

    enter image description here

    From this data, extracting a pair of y values(upper and lower y value of the dark band) is easy. I obtained the value (200, 219). Drawing them as horizontal lines on source image becomes:

    enter image description here

    I guess, information like this can be used to refine your result.