生活随笔
收集整理的這篇文章主要介紹了
opencv otsu二值化
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在第一部分中我們提到過 retVal,當(dāng)我們使用 Otsu 二值化時(shí)會(huì)用到它。那么它到底是什么呢?
在使用全局閾值時(shí),我們就是隨便給了一個(gè)數(shù)來做閾值,那我們?cè)趺粗牢覀冞x取的這個(gè)數(shù)的好壞呢?答案就是不停的嘗試。如果是一副雙峰圖像(簡(jiǎn)單來說雙峰圖像是指圖像直方圖中存在兩個(gè)峰)呢?我們豈不是應(yīng)該在兩個(gè)峰之間的峰谷選一個(gè)值作為閾值?這就是 Otsu 二值化要做的。簡(jiǎn)單來說就是對(duì)一副雙峰圖像自動(dòng)根據(jù)其直方圖計(jì)算出一個(gè)閾值。(對(duì)于非雙峰圖像,這種方法得到的結(jié)果可能會(huì)不理想)。
這里用到到的函數(shù)還是 cv2.threshold(),但是需要多傳入一個(gè)參數(shù)(flag):cv2.THRESH_OTSU。這時(shí)要把閾值設(shè)為 0。然后算法會(huì)找到最優(yōu)閾值,這個(gè)最優(yōu)閾值就是返回值 retVal。如果不使用 Otsu 二值化,返回的retVal 值與設(shè)定的閾值相等。
下面的例子中,輸入圖像是一副帶有噪聲的圖像。第一種方法,我們?cè)O(shè)127 為全局閾值。第二種方法,我們直接使用 Otsu 二值化。第三種方法,我們首先使用一個(gè) 5x5 的高斯核除去噪音,然后再使用 Otsu 二值化。看看噪音去除對(duì)結(jié)果的影響有多大吧。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 11:42:56 2019@author: lg
"""import cv2
import numpy as np
from matplotlib import pyplot as pltimg = cv2.imread('cc.jpeg',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 thresholding after Gaussian filtering
blur = cv2.GaussianBlur(img,(5,5),0)
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 range(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()import numpy as np
import cv2
from matplotlib import pyplot as plt#img = cv2.imread('messi5.jpg',0)
plt.imshow(images[2], cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔為你收集整理的opencv otsu二值化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。