OpenCV cv2.threshold Explained

The cv2.threshold function in Opencv is used to perform threshold processing on an image, converting the pixel values of the image into binary form. Here is how it is used:

retval, thresholded_img = cv2.threshold(src, thresh, maxval, type)

Description of parameters:

  1. Input image
  2. thresh: threshold
  3. maxval: the value assigned when the pixel value exceeds the threshold
  4. Threshold processing types include:

    – cv2.THRESH_BINARY: pixels exceeding the threshold are assigned maxval, otherwise assigned 0
    – cv2.THRESH_BINARY_INV: pixels exceeding the threshold are assigned 0, otherwise assigned maxval
    – cv2.THRESH_TRUNC: pixels exceeding the threshold remain unchanged, otherwise assigned the threshold
    – cv2.THRESH_TOZERO: pixels exceeding the threshold remain unchanged, otherwise assigned 0
    – cv2.THRESH_TOZERO_INV: pixels exceeding the threshold are assigned 0, otherwise remain unchanged

Function return value:

  1. actual threshold value in use
  2. processed binary image

Example code:

import cv2

img = cv2.imread('image.jpg', 0)  # 以灰度模式读取图像
retval, thresholded_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

cv2.imshow('Thresholded Image', thresholded_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
bannerAds