OpenCV Threshold
# coding: utf-8
# In[20]:
import cv2
# In[21]:
src = cv2.imread('threshold.png',cv2.IMREAD_GRAYSCALE)
# In[22]:
#set the threshold and maxValue
thresh = 0
maxValue = 255
# In[23]:
#binary threshold example
th_binary_1, dst_binary_1 = cv2.threshold(src,thresh,maxValue,cv2.THRESH_BINARY)
cv2.imwrite('dst_binary_1.png',dst_binary_1)
th_binary_2, dst_binary_2 = cv2.threshold(src,127,maxValue,cv2.THRESH_BINARY)
cv2.imwrite('dst_binary_2.png',dst_binary_2)
# In[24]:
#inverse binary thresholding
#Inverse binary thresholding is just the opposite of binary thresholding.
#The destination pixel is set to zero if the corresponding source pixel is greater than the threshold,
#and to maxValue if the source pixel is less than the threshold.
th_binary_inv, dst_binary_inv = cv2.threshold(src,127,200,cv2.THRESH_BINARY)
cv2.imwrite('dst_binary_inv.png',dst_binary_inv)
# In[25]:
#inverse truncate thresholding
#the destination pixel is set to the threshold ( thresh ) if the source pixel value is greater than the threshold.
#Otherwise it is set to the source pixel value. maxValue is ignored.
th_trunc, dst_trunc = cv2.threshold(src,127,200,cv2.THRESH_TRUNC)
cv2.imwrite('dst_trunc.png',dst_trunc)
# In[26]:
#threshold to zero
th_zero, dst_zero = cv2.threshold(src,127,200,cv2.THRESH_TOZERO)
cv2.imwrite('dst_zero.png',dst_zero)
# In[27]:
#inverted threshold to zero
th_zero_inv, dst_zero_inv = cv2.threshold(src,127,200,cv2.THRESH_TOZERO_INV)
cv2.imwrite('dst_zero_inv.png',dst_zero_inv)
相应的输入和输出
threshold.png
dst_binary_1.png
dst_binary_2.png
dst_binary_inv.png
dst_trunc.png
dst_zero.png
dst_zero_inv.png