opencv use cv2.threshold () to achieve image thresholding

First, some function: ret, dst = cv2.threshold (src, thresh, maxval, type) of each parameter meaning

  1. src: enter, only single-channel image input, general grayscale image
  2. thresh: Threshold
  3. maxval: When the pixel value exceeds the threshold or smaller than the threshold value, the pixel value to be assigned according to the determined type
type meaning
cv2.THRESH_BINARY Takes part exceeding the threshold value MAXVAL (maximum value), and 0 otherwise
cv2.THRESH_BINARY_INV THRESH_BINARY reversal
cv2.THRESH_TRUNC Section greater than the threshold set threshold, otherwise unchanged
cv2.THRESH_TOZERO Greater than the threshold section does not change, otherwise set to 0
cv2.THRESH_TOZERO_INV THRESH_TOZERO reversal
  1. dst: Output FIG.
  2. ret: Threshold
    The following specifically about how to use it for the effect of the image after threshold processing and a processing example by a look
img=cv2.imread('cat.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)

titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, 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()

Here Insert Picture Description

Published 27 original articles · won praise 20 · views 1555

Guess you like

Origin blog.csdn.net/qq_39507748/article/details/104506306