import cv2 as cv
img = cv.imread('/Users/richzha/Desktop/CV/Image/Cat4.jpg')
cv.imshow('Cat', img)
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
Simple Thresholding
Thresholding is the binarization of an image, it is useful when we want to convert a normal image to a binary image, that is an image where pixels are either 0 (black) or 255 (white). We would provide the computer a thresholding value, and compare each pixel of the image to this thresholded value. If that pixel intensity is less than the threshold value, we set that pixel intensity to 0 and if it is above the thresholding value, we set that pixel intensity to 255.
# Simple Thresholding
threshold, thresh = cv.threshold(gray, 150, 255, cv.THRESH_BINARY)
cv.imshow('Simple Thresholded', thresh)
threshold, thresh_inverse = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV)
cv.imshow('Simple Thresholded Inverse', thresh_inverse)


Adaptive Thresholding
Different images have their own best thresholding value. In this case, we can let the computer to find the optimum thresholding value by itself automatically.
# Adaptive Threshold
adaptive_thresh = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 11, 3)
cv.imshow("Adaptive Thresholding", adaptive_thresh)
adaptive_thresh_inverse = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 11, 3)
cv.imshow("Adaptive Thresholding Inverse", adaptive_thresh_inverse)
cv.waitKey(0)


OpenCV 13: Thresholding