如何使用 Python OpenCV 對影像執行不同的簡單閾值化?


在**簡單閾值化**中,我們定義一個閾值,如果畫素值大於閾值,則將其分配一個值(例如 255),否則將其分配另一個值(例如 0)。

可以使用函式 cv2.threshold()應用簡單閾值化。它接受四個引數 - 源影像、閾值、maxVal 和閾值型別。

**OpenCV** 提供以下不同型別的閾值化 -

  • cv2.THRESH_BINARY - 在此閾值化中,大於閾值的畫素值分配為 255,否則分配為 0。

  • cv2.THRESH_BINARY_INV - 它是 cv2.THRESH_BINARY 的反例。

  • cv2.THRESH_TRUNC - 在此閾值化中,大於閾值的畫素值分配為閾值,其他畫素保持不變。

  • cv2.THRESH_TOZERO - 在此閾值化中,小於閾值的畫素值分配為零,其他畫素保持不變。

  • cv2.THRESH_TOZERO_INV - cv2.THRESH_TOZERO 的反例。

語法

cv2.threshold(img, thresh_val, max_val, thresh_type)

引數

  • img - 輸入灰度影像。它是一個numpy.ndarray

  • thresh_val - 用於對畫素值進行分類的閾值。如果畫素值高於閾值,則分配一個值,否則分配另一個值。

  • max_val - 如果畫素值大於(有時小於)閾值,則要分配給畫素的最大值。

  • thresh_type - 要應用的閾值型別。

它返回全域性閾值和閾值影像。

讓我們藉助一些 Python 示例來了解不同的簡單閾值化。

輸入影像

我們將在以下示例中使用此影像作為輸入檔案。

示例 1

在此程式中,我們對輸入影像應用二值閾值化。

# Python program to illustrate # a simple thresholding type on an image # import required libraries import cv2 # read the input image as a gray image img = cv2.imread('floor.jpg', 0) # applying binary thresholding technique on the input image # all pixels value above 127 will be set to 255 _, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # display the image after applying binary thresholding cv2.imshow('Binary Threshold', thresh) cv2.waitKey(0) cv2.destroyAllWindows()

輸出

執行上述程式時,將產生以下輸出 -

以上輸出顯示了應用**二值閾值化**後的閾值影像。

示例 2

在此程式中,我們將對輸入影像應用不同的**簡單閾值化**。

# Python program to illustrate # simple thresholding type on an image # import required libraries import cv2 import matplotlib.pyplot as plt # read the input image as a gray image img = cv2.imread('floor.jpg',0)
# applying different thresholding techniques on the input image ret1, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) ret2, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV) ret3, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC) ret4, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO) ret5, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV) titles = ['Original Image','BINARY','BINARY_INV','TRUNC','TOZERO','TOZERO_INV'] images = [img,thresh1,thresh2,thresh3,thresh4,thresh5] for i in range(6): plt.subplot(2,3,i+1) plt.imshow(images[i], 'gray') plt.title(titles[i]) plt.axis("off") plt.show()

輸出

執行上述 Python 程式時,將產生以下輸出 -

以上輸出顯示了應用不同簡單閾值化後的不同影像。

更新於: 2022-09-27

763 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告