To segment the image using global thresholding, adaptive thresholding and Otsu's thresholding using python and OpenCV.
- Anaconda - Python 3.7
- OpenCV
Load the necessary packages.
Read the Image and convert to grayscale.
Use Global thresholding to segment the image.
Use Adaptive thresholding to segment the image.
Use Otsu's method to segment the image.
Display the results.
import cv2
import numpy as np
import matplotlib.pyplot as plt
ori_img=cv2.imread('kenny.jpg')
ori_img=cv2.resize(ori_img,(460,250))
gray_img=cv2.cvtColor(ori_img,cv2.COLOR_BGR2GRAY)
ret,thresh_img1=cv2.threshold(gray_img,86,255,cv2.THRESH_BINARY)
ret,thresh_img2=cv2.threshold(gray_img,86,255,cv2.THRESH_BINARY_INV)
ret,thresh_img3=cv2.threshold(gray_img,86,255,cv2.THRESH_TOZERO)
ret,thresh_img4=cv2.threshold(gray_img,86,255,cv2.THRESH_TOZERO_INV)
ret,thresh_img5=cv2.threshold(gray_img,100,255,cv2.THRESH_TRUNC)
thresh_img6=cv2.adaptiveThreshold(gray_img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
thresh_img7=cv2.adaptiveThreshold(gray_img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)
ret,thresh_img8=cv2.threshold(gray_img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imshow('original',ori_img)
cv2.imshow('gray',gray_img)
cv2.imshow('binary threshold',thresh_img1)
cv2.imshow('binary to inverse threshold',thresh_img2)
cv2.imshow('to zero threshold',thresh_img3)
cv2.imshow('to zero to inverse threshold',thresh_img4)
cv2.imshow('truncate threshold',thresh_img5)
cv2.imshow('mean adaptive threshold',thresh_img6)
cv2.imshow('gaussian adaptive threshold',thresh_img7)
cv2.imshow('otsu thresold',thresh_img8)
cv2.waitKey(0)
cv2.destroyAllWindows()
Original | Gray Image |
---|---|
![]() |
![]() |
Gray Image | Binary Thresholding | Binary Thresholding - Inverse |
---|---|---|
![]() |
![]() |
![]() |
Truncate Thresholding | To Zero Thresholding | To Zero Thresholding - Inverse |
---|---|---|
![]() |
![]() |
![]() |
Adaptive Thresholding - Mean | Adaptive Thresholding - Gaussian |
---|---|
![]() |
![]() |
Original | Gray Image |
---|---|
![]() |
![]() |
Thus the images are segmented using global thresholding, adaptive thresholding and optimum global thresholding using python and OpenCV.