Search code examples
pythonopencvimage-thresholding

Thresholding image using opencv library in python with different flags using for loop


I imported cv2 as cv, created a list of threshold flags, concatenated 'cv.' with the flags and then created a for loop for passing the flags as arguments. But python shows TypeError. I have attached the image of the output. Kindly help me create all the possible thresholds using a loop or some other way except for explicitly mentioning the flags every time.

[Output of the code - Jupyter]


Solution

  • In OpenCV, the given threshold options (e.g. cv.THRESH_BINARY or cv.THRESH_BINARY_INV) are actually constant integer values. You are trying to use strings instead of these integer values. That is the reason why you get the Type Error. If you want to apply all these different thresholds in a loop, one option is to create a different list for these options, like this:

    threshold_options = [cv.THRESH_BINARY, cv.THRESH_BINARY_INV, ...]
    

    That way, you can then use the values of this list in the loop as follows:

    retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])
    

    The entire code would be as follows:

    titles = [ 'THRESH_BINARY',
    'THRESH_BINARY_INV',
    'THRESH_MASK',
    'THRESH_OTSU',
    'THRESH_TOZERO',
    'THRESH_TOZERO_INV',
    'THRESH_TRIANGLE',
    'THRESH_TRUNC']
    
    threshold_options = [ cv.THRESH_BINARY,
    cv.THRESH_BINARY_INV,
    cv.THRESH_MASK,
    cv.THRESH_OTSU,
    cv.THRESH_TOZERO,
    cv.THRESH_TOZERO_INV,
    cv.THRESH_TRIANGLE,
    cv.THRESH_TRUNC]
    
    
    for i in range(len(titles)):
        retval, thresh = cv.threshold(img, 127, 255, threshold_options[i])
        plt.subplot(2,3,i+1), plt.title(titles[i]), plt.imshow(thresh, 'gray')
    plt.show()