生活随笔
收集整理的這篇文章主要介紹了
opencv otsu二值化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在第一部分中我們提到過 retVal,當我們使用 Otsu 二值化時會用到它。那么它到底是什么呢?
在使用全局閾值時,我們就是隨便給了一個數來做閾值,那我們怎么知道我們選取的這個數的好壞呢?答案就是不停的嘗試。如果是一副雙峰圖像(簡單來說雙峰圖像是指圖像直方圖中存在兩個峰)呢?我們豈不是應該在兩個峰之間的峰谷選一個值作為閾值?這就是 Otsu 二值化要做的。簡單來說就是對一副雙峰圖像自動根據其直方圖計算出一個閾值。(對于非雙峰圖像,這種方法得到的結果可能會不理想)。
這里用到到的函數還是 cv2.threshold(),但是需要多傳入一個參數(flag):cv2.THRESH_OTSU。這時要把閾值設為 0。然后算法會找到最優閾值,這個最優閾值就是返回值 retVal。如果不使用 Otsu 二值化,返回的retVal 值與設定的閾值相等。
下面的例子中,輸入圖像是一副帶有噪聲的圖像。第一種方法,我們設127 為全局閾值。第二種方法,我們直接使用 Otsu 二值化。第三種方法,我們首先使用一個 5x5 的高斯核除去噪音,然后再使用 Otsu 二值化??纯丛胍羧コ龑Y果的影響有多大吧。
#!/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()
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的opencv otsu二值化的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。