pythonopencvimage-processingimage-thresholding

Opencv Threshold Otsu with Threshold Binary Logic


At the opencv threshold page there is a code like:

    import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('noisy2.png',0)
# global thresholding
ret1,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
# Otsu's thresholding
ret2,th2 = cv.threshold(img,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
# Otsu's thresholding after Gaussian filtering
blur = cv.GaussianBlur(img,(5,5),0)
ret3,th3 = cv.threshold(blur,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
# plot all the images and their histograms
images = [img, 0, th1,
          img, 0, th2,
          blur, 0, th3]
titles = ['Original Noisy Image','Histogram','Global Thresholding (v=127)',
          'Original Noisy Image','Histogram',"Otsu's Thresholding",
          'Gaussian filtered Image','Histogram',"Otsu's Thresholding"]
for i in range(3):
    plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
    plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)
    plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
    plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
plt.show()

My question here is that the cv.THRESH_BINARY refers to 0 and cv.THRESH_OTSU refers to 8. if I add them together 0+8 =8 so why I use cv.THRESH_BINARY? I tried without thresh binary and I can't see difference with my eyes. Is there another rule that I don't know?


Solution

  • In cv.THRESH_BINARY+cv.THRESH_OTSU, the cv.THRESH_BINARY+ is quite meaningless. It's just a placeholder, since you can combine Otsu with other methods like cv.THRESH_BINARY_INV+cv.THRESH_OTSU. Just consider cv.THRESH_BINARY+ as the default behaviour. Also you shouldn't care about the actual value of an enumeration: it's an implemetation detail and may change in future releases.

    Thanks to @Miki for this precious answer.