Skip to content
Search

Cv2.threshold

lastmod 2023-11-01created 2023-01-057 edits

Covers Simple thresholding, Adaptive thresholding, and Otsu’s thresholding, the methods of image binarization.

Basic thresholding

Binarization is simple, but it poses a tricky problem. Binarization means processing an image by classifying it into black and white.

The key question here is how to determine the threshold value used as the criterion.

Values greater than the threshold become white, and values less than it become black.

Basic thresholding is a simple form in which the user picks a fixed threshold value and the result is shown.

cv2.threshold(src, thresh, maxval, type) → retval, dst

Parameters

  • src - input image, a single-channel image. (grayscale image)
  • thresh - threshold value
  • maxval - value to apply when the threshold is exceeded
  • type - thresholding type

Thresholding type

  • cv2.THRESH_BINARY
  • cv2.THRESH_BINARY_INV
  • cv2.THRESH_TRUNC
  • cv2.THRESH_TOZERO
  • cv2.THRESH_TOZERO_INV

Cv2.threshold.png

Example

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('gradient.jpg',0)

ret, thresh1 = cv2.threshold(img,127,255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img,127,255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img,127,255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img,127,255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img,127,255, cv2.THRESH_TOZERO_INV)

titles =['Original','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img,thresh1,thresh2,thresh3,thresh4,thresh5]

for i in xrange(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])

plt.show()

Cv2.threshold_-_sample.jpg

Otsus method

For Otsu's binarization algorithm, see that page.

See also

Favorite site

author Zer0 sitemap