Opencv之图像阈值分割函数的使用及Demo分析

1、Simple Thresholding(简单阈值)

函数: cv2.threshold()

参数理解:第一个参数,图片,一般指灰度图像;第二个参数,对像素值进行分类的阈值;第三个参数:替换值,如果像素值大于(或者少于)阈值,就用这个参数替换;第四个参数:openCV自己提供的不同类型的阈值,它由函数参数决定。

  • cv2.THRESH_BINARY
  • cv2.THRESH_BINARY_INV
  • cv2.THRESH_TRUNC
  • cv2.THRESH_TOZERO
  • cv2.THRESH_TOZERO_INV

threshold_type:阈值类型(该函数第四个参数小技巧)    

threshold_type=CV_THRESH_BINARY:

如果 src(x,y)>threshold ,dst(x,y) = max_value; 否则,dst(x,y)=0;

threshold_type=CV_THRESH_BINARY_INV:

如果 src(x,y)>threshold,dst(x,y) = 0; 否则,dst(x,y) = max_value.

threshold_type=CV_THRESH_TRUNC:

如果 src(x,y)>threshold,dst(x,y) = max_value; 否则dst(x,y) = src(x,y).

threshold_type=CV_THRESH_TOZERO:

如果src(x,y)>threshold,dst(x,y) = src(x,y) ; 否则 dst(x,y) = 0.

threshold_type=CV_THRESH_TOZERO_INV:如果 src(x,y)>threshold,dst(x,y) = 0 ; 否则dst(x,y) = src(x,y).

 
# -*- coding: utf-8 -*-
# http://docs.opencv.org/3.3.0/d7/d4d/tutorial_py_thresholding.html
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('../../image/white-and-black.png',0)
ret,thresh1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)  
# 使用不同的opencv阈值函数进行转换
ret,thresh2 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
ret,thresh3 = cv2.threshold(img,127,255,cv2.THRESH_TRUNC)
ret,thresh4 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO)
ret,thresh5 = cv2.threshold(img,127,255,cv2.THRESH_TOZERO_INV)
titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in xrange(6):  # 通过循环来展示图片
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')  # 显示图片
    plt.title(titles[i])            # 显示标题
    plt.xticks([]),plt.yticks([])   # 现在标签和位置
plt.show()

2、Adaptive Thresholding(自适应阈值)

Adaptive Method - It decides how thresholding value is calculated.

  • cv2.ADAPTIVE_THRESH_MEAN_C : threshold value is the mean of neighbourhood area.
  • cv2.ADAPTIVE_THRESH_GAUSSIAN_C : threshold value is the weighted sum of neighbourhood values where weights are a gaussian window.
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('../../image/dushu2.jpg',0)
img = cv2.medianBlur(img,5)
ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)  # 简单阈值
# threshold value is the mean of neighbourhood area.
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)  # 自适应阈值
# threshold value is the weighted sum of neighbourhood values where weights are a gaussian window.
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2)   # 自适应阈值
titles = ['Original Image', 'Global Thresholding (v = 127)','Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in xrange(4):   # 循环遍历图像输出
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

3、Otsu’s Binarization(Otsu阈值)

Otsu binarization can approximately take a value in the middle of those peaks as threshold value. So in simple words, it automatically calculates a threshold value from image histogram for a bimodal image. (For images which are not bimodal, binarization won’t be accurate.)

Bimodal image is an image whose histogram has two peaks.

In the above example. Input image is a noisy image. In first case, I applied global thresholding for a value of 127. In second case, I applied Otsu’s thresholding directly. In third case, I filtered image with a 5x5 gaussian kernel to remove the noise, then applied Otsu thresholding. See how noise filtering improves the result.

import cv2
from matplotlib import pyplot as plt
img = cv2.imread('../../image/noisy_image.png',0)
# global thresholding
ret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)  # 适用普通的阈值转换图像
# Otsu's thresholding
ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)  # 适用Otsu's阈值
# Otsu's thresholding after Gaussian filtering
blur = cv2.GaussianBlur(img,(5,5),0)  # filtering a image with a 5x5 gaussian kernel to remove the noise
# find normalized_histogram, and its cumulative distribution function
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# plot all the images and their histograms
images = [img, 0, th1,
img, 0, th2,
blur, 0, th3]
titles = ['Original Noisy Image','Histogram','Global Thresholding (v=127)',
'Original Noisy Image','Histogram',"Otsu's Thresholding",
'Gaussian filtered Image','Histogram',"Otsu's Thresholding"]
for i in xrange(3):
plt.subplot(3,3,i*3+1),plt.imshow(images[i*3],'gray')
plt.title(titles[i*3]), plt.xticks([]), plt.yticks([])
plt.subplot(3,3,i*3+2),plt.hist(images[i*3].ravel(),256)
plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
plt.subplot(3,3,i*3+3),plt.imshow(images[i*3+2],'gray')
plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])
plt.show()

4、How Otsu’s Bnarization works?

It actually finds a value of t which lies in between two peaks such that variances to both classes are minimum. It can be simply implemented in Python as follows:

# -*- coding: utf-8 -*-
import cv2
import numpy as np
img = cv2.imread('../../image/noisy_image.png',0)
blur = cv2.GaussianBlur(img,(5,5),0)  # filtering a image with a 5x5 gaussian kernel to remove the noise
# find normalized_histogram, and its cumulative distribution function
hist = cv2.calcHist([blur],[0],None,[256],[0,256])  # Otsu’s Binarization 适用 bimodal image
# In simple words, bimodal image is an image whose histogram has two peaks
# Otsu can approximately take a value in the middle of those peaks as threshold value
hist_norm = hist.ravel()/hist.max()
Q = hist_norm.cumsum()
bins = np.arange(256)
fn_min = np.inf
thresh = -1
for i in xrange(1,256):
p1,p2 = np.hsplit(hist_norm,[i]) # probabilities
q1,q2 = Q[i],Q[255]-Q[i] # cum sum of classes
b1,b2 = np.hsplit(bins,[i]) # weights
# finding means and variances
m1,m2 = np.sum(p1*b1)/q1, np.sum(p2*b2)/q2
v1,v2 = np.sum(((b1-m1)**2)*p1)/q1,np.sum(((b2-m2)**2)*p2)/q2
# calculates the minimization function
fn = v1*q1 + v2*q2
if fn < fn_min:
fn_min = fn
thresh = i
# find otsu's threshold value with OpenCV function
ret, otsu = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
print( "{} {}".format(thresh,ret) )   # 112 111.0

5、summary

本文主要是学会了简单阈值(全局阈值),自适应阈值,Otsu的阈值等方法的使用,在使用Otsu阈值方法的时候,提及了双模态图像概念,只有图像满足这个条件,Otsu阈值才有用,本文用Python代码实现了Otsu阈值的相关原理,但是还是不很理解,后续待深入熟悉。

6、Reference Materials

资料1:http://docs.opencv.org/3.3.0/d7/d4d/tutorial_py_thresholding.html

资料2(threshold()函数):

http://docs.opencv.org/3.3.0/d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57

 

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: