O'Reilly logo

Computer Vision with Python 3 by Saurabh Kapur

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Thresholding

We learned about thresholding in Chapter 2, Filters and Features. Now, let’s see how it can be implemented using OpenCV. OpenCV has an inbuilt threshold() function, which takes a grayscale image, threshold value, and new value to be assigned if the value is greater than the threshold and type of thresholding as input. The types of thresholding are:

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

The following code is an example for thresholding:

>>> import cv2>>> img = cv2.imread("image.jpg")>>> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)>>> new_img = cv2.threshold(gray,120,255,cv2.THRESH_BINARY)>>> cv2.imwrite("thresholding.jpg", new_img[1])>>> cv2.imshow("thresholding", new_img[1]) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required