opencv for python (12) Otsu's二值化原理及代码总结

Otsu’s非常适合于图像灰度直方图具有双峰的情况,他会在双峰之间找到一个值作为阈值
opencv for python (12) Otsu's二值化原理及代码总结_第1张图片

ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) 会将大津法得到的阈值,做为第一个参数
函数plt.hist(images[i*3].ravel(),256) 是绘制图像直方图,ravel是将图像的多维数组降维,变成一维数组,256是将横轴分为256组

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

img = cv2.imread('CAM003.png',0)
ret1,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
ret2,th2 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
blur = cv2.GaussianBlur(img,(5,5),0)
ret3,th3 = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

titles = ['orgianl Noisy Image','Histogram','Global Threshold(v=127)',
          'orgianl Noisy Image','Histogram',"Otsu's THresholding",
          'Guassian filtered Image','Histogram',"Otsu's Thresholding"]
images = [img,0,th1,
          img,0,th2,
          blur,0,th3]

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()

你可能感兴趣的:(opencv for python (12) Otsu's二值化原理及代码总结)