Search code examples
pythonopencvimage-thresholding

Can I add a bias to Otsu thresholding in OpenCV?


Here's my example. Left to right:

  1. original image
  2. grayscale + (3,3) gaussian blur
  3. Otsu thresholding + invert pixels

enter image description here

I want to capture more of the faint part of the pen stroke. I understand that Otsu Thresholding tries to apply the threshold point in between two peaks of the pixel intensity histogram, but I'd like to bias that a bit so I can capture some of the lighter pixels.

Is it possible out of the box? Or do I need to do something manual?


Solution

  • I have an answer courtesy of the rubber duck phenomenon.

    th, th_img = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    

    The 0th index of the returned tuple (th) is the threshold value that the Otsu Binarization algorithm chose. I can discard th_img and apply whatever bias I like to th before using it in regular binary thresholding.

    desired_th = th*1.2
    _, th_img = cv2.threshold(blur, desired_th, 255, cv2.THRESH_BINARY)
    

    Here's what I get. By cleaning up the unwanted speckles that could appear on the outside, I'll get what I was looking for.

    enter image description here