Date:

Share:

Simple Thresholding with OpenCV and Python

Related Articles

Last updated: April 4, 2023


Welcome to an exciting tutorial on computer vision! Today, we’ll dive into a simple threshold using OpenCV and Python. We’ll break down the OpenCV threshold into easy-to-understand concepts and examples that you can follow to master this skill.

What is a threshold?

Threshold is a basic concept in computer vision and image processing. This is a technique that separates an image into separate regions based on pixel intensity values. The goal is to make the image easier to understand so that a computer can analyze it and extract useful information.

Imagine a grayscale image where each pixel has a value between 0 (black) and 255 (white). We can apply thresholding to create a binary image, where each pixel is either black or white. This makes it easier for the computer to recognize and process features such as edges, shapes and textures.

Why use Thresholding?

The threshold has many practical applications, including:

  1. Object detection and tracking
  2. Image segmentation
  3. optical character recognition (OCR)
  4. edge detection
  5. Noise reduction

We will now take a closer look at how to implement a simple threshold using OpenCV and Python.

Setting up your environment

First, we need to install OpenCV and Python. you can find Installation guides for OpenCV here and Installation guides for Python here.

Let’s create and run a Python virtual environment:

python -m venv thresholddemo
source thresholddemo/bin/activate

and install our tools:

pip install opencv-python matplotlib numpy

Once you’ve set up your environment, create a new Python file and import the following libraries:

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

Loading a picture

To start, let’s load a grayscale image. You can use any image you want, but we’ll use this example image of a pickup truck for this tutorial.

I took this picture. You can use it however you want. Download it here

Save the image in your project folder and load it using the following code:

image = cv2.imread("images/pickup.jpg", cv2.IMREAD_GRAYSCALE)

Apply a simple threshold

With our image loaded, it’s time to apply a threshold. In OpenCV, we can use the threshold() function to do this. The function takes three arguments: the source image, a threshold and a maximum value. It returns two values: the threshold value used and the threshold image.

threshold_value = 127
max_value = 255

ret, thresholded_image = cv2.threshold(image, threshold_value, max_value, cv2.THRESH_BINARY)

In this example, we set the threshold value to 127. If the pixel intensity is greater than or equal to 127, it will be set to the maximum value (white). Otherwise, it will be set to black.

Visualize the results

Let’s visualize our original and thresholded images using matplotlib:

plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.axis("off")

plt.subplot(1, 2, 2)
plt.imshow(thresholded_image, cmap='gray')
plt.title("Thresholded Image")
plt.axis("off")

plt.show()

This code will display both the original grayscale image and the threshold image, allowing you to compare the results. You should see that the threshold image is much simpler, with a clear distinction between the pickup and the background.

Simple OpenCV Python Threshold

Binary Threshold is just one of many techniques. You can choose a technique based on what produces the best output for your purposes. Let’s look at them.

Threshold techniques

There are five techniques at our disposal to perform a simple threshold.

  1. THRESH_binary
  2. THRESH_BINARY_INV
  3. THRESH_TRUNC
  4. THRESH_TOZERO
  5. THRESH_TOZERO_INV

Let’s see what our image looks like, using each of these techniques.

THRESH_BINARY_INV

This is similar to THRESH_BINARY, but the roles of black and white are reversed. Pixels with intensity values ​​higher than the threshold value are set to 0, while all other pixels are set to the maximum intensity value.

Simple OpenCV Python Threshold

THRESH_TRUNC

In this technique, pixels with intensity values ​​higher than the threshold value are set to the threshold value, while all other pixels remain unchanged.

Simple OpenCV Python Threshold

THRESH_TOZERO

In this technique, pixels with intensity values ​​lower than the threshold value are set to 0, while all other pixels remain unchanged.

Simple OpenCV Python Threshold

THRESH_TOZERO_INV

This is similar to THRESH_TOZERO, but the roles of black and white are reversed. Pixels with intensity values ​​lower than the threshold value are set to the maximum intensity value, while all other pixels remain unchanged.

Simple OpenCV Python Threshold

Trying different thresholds

Feel free to experiment with different threshold values ​​to see how they affect the resulting image. For example, setting the threshold value to 100 or 150 and observing the changes. A lower threshold value will produce more white pixels, while a higher value will produce more black pixels.

# Set different threshold values
threshold_values = [100, 150]

for value in threshold_values:
    ret, thresholded_image = cv2.threshold(image, value, max_value, cv2.THRESH_BINARY)

    plt.imshow(thresholded_image, cmap='gray')
    plt.title(f"Thresholded Image with Value {value}")
    plt.axis("off")
    plt.show()

finishing

Mazel Tov! You learned how to make a simple threshold with OpenCV and Python. Now you have a solid foundation to build on and learn more advanced thresholding techniques, such as adaptive thresholding and Otsu’s method.

Remember to keep experimenting and modifying your code to better understand how thresholding works and how it can be applied to different computer vision tasks.

Happy coding, and see you in the next tutorial.

– Jeremy

I have a lot OpenCV demos On GitHub you can download and run. I build them on mine Computer Vision live broadcast

Questions, comments? Yell at me!


Source

Popular Articles