python圖像二值化處理
一、圖像二值化
圖像二值化是指將圖像上像素點的灰度值設定為0或255,即整個圖像呈現明顯的黑白效果的過程。
二、python圖像二值化處理
1.opencv簡單閾值cv2.threshold
2.opencv自適應閾值cv2.adaptiveThreshold
有兩種方法可用于計算自適應閾值:mean_c和guassian_c
3.Otsu's二值化
三、示例:
importcv2
importnumpyasnp
frommatplotlibimportpyplotasplt
img=cv2.imread('scratch.png',0)
#globalthresholding
ret1,th1=cv2.threshold(img,127,255,cv2.THRESH_BINARY)
#Otsu'sthresholding
th2=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,11,2)
#Otsu'sthresholding
#閾值一定要設為0!
ret3,th3=cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
#plotalltheimagesandtheirhistograms
images=[img,0,th1,img,0,th2,img,0,th3]
titles=[
'OriginalNoisyImage','Histogram','GlobalThresholding(v=127)',
'OriginalNoisyImage','Histogram',"AdaptiveThresholding",
'OriginalNoisyImage','Histogram',"Otsu'sThresholding"
]
#這里使用了pyplot中畫直方圖的方法,plt.hist,要注意的是它的參數是一維數組
#所以這里使用了(numpy)ravel方法,將多維數組轉換成一維,也可以使用flatten方法
#ndarray.flat1-Diteratoroveranarray.
#ndarray.flatten1-Darraycopyoftheelementsofanarrayinrow-majororder.
foriinrange(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()
以上內容為大家介紹了python圖像二值化處理,希望對大家有所幫助,如果想要了解更多Python相關知識,請關注IT培訓機構:千鋒教育。

相關推薦HOT
更多>>
python cmd中怎么運行python文件
運行Python,可在交互模式下運行,或者命令行中。命令行中運行的是Python的.py文件。cmd中執行Python程序的方法,如下打開cmdC:\Users\Administ...詳情>>
2023-11-06 14:37:04
pythondict是啥意思
Python中的dict表示的字典數據類型。字典是另一種可變容器模型,且可存儲任意類型對象。字典是python語言中唯一的映射類型映射類型對象里哈希值...詳情>>
2023-11-06 13:56:05
python如何創建模塊
Python模塊(Module),是一個Python文件,以.py結尾,包含了Python對象定義和Python語句。模塊讓你能夠有邏輯地組織你的Python代碼段。把相關的...詳情>>
2023-11-06 13:36:31
python解釋器寫代碼如何換行
使用以下方法可以使Python的代碼換行:用反斜杠鏈接多行代碼,示例輸出:55a=22+\33printa用小括號括起來,示例輸出:55a=(22+33)printa提示:針...詳情>>
2023-11-06 13:17:12熱門推薦
技術干貨






