溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在python中處理圖像二值化

發(fā)布時(shí)間:2021-04-23 16:44:50 來源:億速云 閱讀:430 作者:Leah 欄目:編程語言

怎么在python中處理圖像二值化?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。

Python主要用來做什么

Python主要應(yīng)用于:1、Web開發(fā);2、數(shù)據(jù)科學(xué)研究;3、網(wǎng)絡(luò)爬蟲;4、嵌入式應(yīng)用開發(fā);5、游戲開發(fā);6、桌面應(yīng)用開發(fā)。

一、圖像二值化

圖像二值化是指將圖像上像素點(diǎn)的灰度值設(shè)定為0或255,即整個(gè)圖像呈現(xiàn)明顯的黑白效果的過程。

二、python圖像二值化處理

1.opencv簡單閾值cv2.threshold

2.opencv自適應(yīng)閾值cv2.adaptiveThreshold

有兩種方法可用于計(jì)算自適應(yīng)閾值:mean_c和guassian_c

3.Otsu's二值化

三、示例:

import cv2
import numpy as np
from matplotlib import pyplot as plt
 
img = cv2.imread('scratch.png', 0)
# global thresholding
ret1, th2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# Otsu's thresholding
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
# Otsu's thresholding
# 閾值一定要設(shè)為 0 !
ret3, th4 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# plot all the images and their histograms
images = [img, 0, th2, img, 0, th3, img, 0, th4]
titles = [
  'Original Noisy Image', 'Histogram', 'Global Thresholding (v=127)',
  'Original Noisy Image', 'Histogram', "Adaptive Thresholding",
  'Original Noisy Image', 'Histogram', "Otsu's Thresholding"
]
# 這里使用了 pyplot 中畫直方圖的方法, plt.hist, 要注意的是它的參數(shù)是一維數(shù)組
# 所以這里使用了( numpy ) ravel 方法,將多維數(shù)組轉(zhuǎn)換成一維,也可以使用 flatten 方法
# ndarray.flat 1-D iterator over an array.
# ndarray.flatten 1-D array copy of the elements of an array in row-major order.
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()

看完上述內(nèi)容,你們掌握怎么在python中處理圖像二值化的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI