pythonopencvimage-processinggradientimage-thresholding

OpenCV apply threshold in a specific direction


I want to use OpenCV in Python to apply a specific threshold to a grayscale image in a similar manner to OpenCV's cv2.THRESH_TOZERO, but with the particularity that is should be applied from a left dark pixel to right light pixel only.

That is, for a given pixel (x,y), if pixel (x-1, y) is dark enough (say value from 0 to 5), then all the continuous pixels (x+i,y) in the same row who are in range from 0 to 30 (say) should become black, until a lighter pixel is found.


Solution

  • I think the following code does what you describe:

    import numpy as np
    
    height = 200
    width = 200
    threshold1 = 5
    threshold2 = 30
    
    image = np.random.randint(0, 255, (height, width), dtype=int)
    
    for i in range(height):
        dark_enough = False
        for j in range(width):
            if not dark_enough and image[i, j] < threshold1:
                dark_enough = True
            elif dark_enough and image[i, j] < threshold2:
                image[i, j] = 0
            elif dark_enough:
                dark_enough = False            
    

    Granted, this does not use OpenCV. Is OpenCV absolutely required?