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
int threshold_value =0;int threshold_type =3;int morphology_type =0;intconst max_value =255;intconst max_type =4;intconst max_BINARY_value =255;Mat src, src_gray, dst, dst_morph;src =imread("coin.jpg",1);/* threshold_type0: Binary1: Binary Inverted2: Threshold Truncated3: Threshold to Zero4: Threshold to Zero Inverted*/threshold(src, dst, threshold_value, max_BINARY_value, threshold_type);
import cv2 as cvimport numpy as npfrom matplotlib import pyplot as pltimg = cv.imread('coin.jpg',0)ret,thresh1 = cv.threshold(img,127,255,cv.THRESH_BINARY)ret,thresh2 = cv.threshold(img,127,255,cv.THRESH_BINARY_INV)ret,thresh3 = cv.threshold(img,127,255,cv.THRESH_TRUNC)ret,thresh4 = cv.threshold(img,127,255,cv.THRESH_TOZERO)ret,thresh5 = cv.threshold(img,127,255,cv.THRESH_TOZERO_INV)titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]for i inrange(6): plt.subplot(2,3,i+1),plt.imshow(images[i],'gray',vmin=0,vmax=255) plt.title(titles[i]) plt.xticks([]),plt.yticks([])plt.show()
Example 1-1. Select the local threshold value manually.
//adaptiveThreshold()
void cv::adaptiveThreshold ( InputArray src,
OutputArray dst,
double maxValue,
int adaptiveMethod,
int thresholdType,
int blockSize,
double C
)
#Python:dst=cv.adaptiveThreshold( src, maxValue, adaptiveMethod, thresholdType, blockSize, C)