Tutorial: Thresholding and Morphology
Tutorial: Thresholding and Morphology
Deep Learning Image Processing. Updated. 2024.3
I. Introduction
In this tutorial, we will learn how to apply thresholding and morphology algorithms to segment objects from the background. Thresholding is a powerful tool to segment object images into regions or from the background based on the image intensity values. After applying thresholding methods, morphology methods are usually applied for post-processing such as pruning unwanted spikes, filling holes, and connecting broken pieces. Also, you will learn how to draw and analyze the histogram of a digital image to determine the contrast of the image intensity and use this information to balance the contrast and determine an optimal value for the thresholding.
II. Tutorial
Part 1. Binary Thresholding
This tutorial shows how to create a simple code to apply the OpenCV function for local thresholding.
Thresholding: OpenCV
First, read the OpenCV documentation
Sample code
Example 1-1. Select the local threshold value manually.
Download the example code and test images.
Run the code on all test images.
Apply different values of thresholding for each images and find the best threshold values.
Example 1-2. Otsu Threshold
Modify the program to include ‘Otsu method’.
Read this documentation for THRESH_OTSU
Apply on each test image and compare the results with global thresholding output.
Example 1-3. Plot Histogram
Calculate and Plot the histogram for each image in gray-scale and analyze if a clear threshold value exists in a histogram.
Read this documentation for calculating histogram
calcHist()
For plotting histogram, you may use the following function.
See here for full example codes
Example 1: Histogram of GrayScale Image File
Example 2: Histogram of Color Image File
Example 3: Histogram of Webcam Image
Example 1-4. Local Threshold
Apply ‘Local Adaptive Thresholding’ on the following images. Compare the results of the global thresholding.
Refer to adaptiveThreshold()
documentation
Sample code
Part 2. Morphology
Morphology: OpenCV
First, read the OpenCV documentation on morphology.
Sample code
Example 2-1. Morphology selection with trackbar
Download the example code
Apply several morphology to obtain clear segmentation of the object in given images, after Thresholding.
Exercise
Exercise 1
Create a new C++ project in Visual Studio Community
Project Name:
DLIP_Tutorial_Thresholding
Project Folder:
C:\Users\yourID\source\repos\DLIP\Tutorial\
Source File:
DLIP_Tutorial_Thresholding.cpp
Analyze Histogram and apply Thresholding methods on given images.
Find the optimal threshold method and value for the object segmentation.
Show the results to TA before proceeding to Exercise 2.
Exercise 2
Apply Morphology methods after threshold on all test images.
Analyze which morphology methods works best for each images for object segmentation.
Show the results to TA before finishing this tutorial.
Last updated
Was this helpful?