Visual Intelligence Summit: Oct 22 in San Francisco Get your ticket

Use cv2.threshold to Apply Image Thresholding

You can use the cv2.threshold function to apply image thresholding to an image.

Thresholding allows you to turn all pixels above a certain greyscale value either white or black. It is useful as a pre-processing step for image contouring.

Before you apply thresholding, your image should be greyscale or converted to greyscale.

To apply thresholding, run:

Python
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
 
image = cv.imread('example.png', cv.IMREAD_GRAYSCALE)
_, thresholded = cv.threshold(image, 127, 255, cv.THRESH_BINARY)

Above, replace 127 with the threshold value.

The code above will turn any pixel whose greyscale value is over 127 white and any pixel whose value is 127 or under black. If you need the opposite, use cv.THRESH_BINARY_INV.

Next steps

OpenCV can be used with the open source supervision Python package.

supervision provides an extensive range of functionalities for working with computer vision models. With supervision, you can:

1. Process and filter detections and segmentation masks from a range of popular models (YOLOv5, Ultralytics YOLOv8, MMDetection, and more).
2. Process and filter classifications.
3. Compute confusion matrices.

And more! To learn about the full range of functionality in supervision, check out the supervision documentation.

Start where you are

Speak with an AI expert

Our team will help you start solving business problems on the first call.

  • Solution architecting
  • Live demonstration
  • Pricing and specifications
  • Feasibility assessment

Over 16,000 organizations build with Roboflow.

Rivian
Pella
Chobani
USG Corporation
BNSF Railway
American Woodmark
Outcomes
Patrick Industries
Peer Robotics