Welcome to DOFBOT-Ultra repository
14. Binary Image
Binary Image
The core idea of binarization is to set a threshold. Values greater than the threshold become 0 (black) or 255 (white), turning the image into a black-and-white image. The threshold can be fixed or adaptive. Adaptive thresholding is generally the comparison of a pixel with the average value or Gaussian distribution weighted sum of the pixels in its neighborhood region, with or without an optional offset.
Global threshold:
Python-OpenCV provides the threshold function: cv2.threshold(src, threshold, maxValue, method)

src original image: dashed line represents the value to be thresholded; dotted line represents the threshold

cv2.THRESH_BINARY: The grayscale value of pixels greater than the threshold is set to maxValue (e.g., maximum 255 for 8-bit grayscale), and the grayscale value of pixels less than the threshold is set to 0.

cv2.THRESH_BINARY_INV: The grayscale value of pixels greater than the threshold is set to 0, and the grayscale value of pixels less than the threshold is set to maxValue.

cv2.THRESH_TRUNC: The grayscale value of pixels less than the threshold remains unchanged, and the grayscale value of pixels greater than the threshold is set to the threshold value.

cv2.THRESH_TOZERO: The grayscale value of pixels less than the threshold remains unchanged, and the grayscale value of pixels greater than the threshold becomes 0.

cv2.THRESH_TOZERO_INV: The grayscale value of pixels greater than the threshold remains unchanged, and the grayscale value of pixels less than the threshold becomes 0.
Code path:
~/dofbot_opencv/scripts/3.draw_picture/02_binarization.ipynb
ximport cv2import numpy as npimport matplotlib.pyplot as pltimg = cv2.imread('yahboom.jpg',1)GrayImage = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to grayscale imageret,thresh1=cv2.threshold(GrayImage,10,255,cv2.THRESH_BINARY)ret,thresh2=cv2.threshold(GrayImage,10,255,cv2.THRESH_BINARY_INV)ret,thresh3=cv2.threshold(GrayImage,10,255,cv2.THRESH_TRUNC)ret,thresh4=cv2.threshold(GrayImage,10,255,cv2.THRESH_TOZERO)ret,thresh5=cv2.threshold(GrayImage,10,255,cv2.THRESH_TOZERO_INV)titles = ['Gray Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']images = [GrayImage, thresh1, thresh2, thresh3, thresh4, thresh5]for i in range(6): plt.subplot(2,3,i+1),plt.imshow(images[i],'gray') plt.title(titles[i]) plt.xticks([]),plt.yticks([])plt.show()