在Opencv中,cv2.threshold
函數用于對圖像進行閾值處理,將圖像的像素值轉換為二進制形式。其用法如下:
retval, thresholded_img = cv2.threshold(src, thresh, maxval, type)
參數說明:
src
:輸入的圖像thresh
:閾值maxval
:當像素值超過閾值時賦予的值type
:閾值處理的類型,包括:
cv2.THRESH_BINARY
:超過閾值的像素賦予maxval
,否則賦予0cv2.THRESH_BINARY_INV
:超過閾值的像素賦予0,否則賦予maxval
cv2.THRESH_TRUNC
:超過閾值的像素保持不變,否則賦予閾值cv2.THRESH_TOZERO
:超過閾值的像素保持不變,否則賦予0cv2.THRESH_TOZERO_INV
:超過閾值的像素賦予0,否則保持不變函數返回值:
retval
:實際使用的閾值thresholded_img
:處理后的二值化圖像示例代碼:
import cv2
img = cv2.imread('image.jpg', 0) # 以灰度模式讀取圖像
retval, thresholded_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('Thresholded Image', thresholded_img)
cv2.waitKey(0)
cv2.destroyAllWindows()