先选定一个特定的阈值量,比如:127
新的阈值产生规则为:
- ≥ 127的像素点,灰度值设定为最大值(如8为灰度值最大为255)
- < 127的像素点,灰度值设定为0
d s t ( x , y ) = { m a x V a l i f s r c ( x , y ) > t h r e s h 0 , o t h e r w i s e dst(x,y)=\begin{cases} maxVal \quad if \quad src(x,y)>thresh \\ 0,otherwise \end{cases} dst(x,y)={maxValifsrc(x,y)>thresh0,otherwise
与二进制阈值化相似,先选定一个特定的灰度值作为阈值
- 大于阈值的设定为0
- 小于该阈值的设定为255
d s t ( x , y ) = { 0 i f s r c ( x , y ) > t h r e s h m a x V a l , o t h e r w i s e dst(x,y)=\begin{cases} 0 \quad if \quad src(x,y)>thresh \\ maxVal,otherwise \end{cases} dst(x,y)={0ifsrc(x,y)>threshmaxVal,otherwise
首先选定一个阈值,图像中大于该阈值的像素点被设定为该阈值,小于该阈值的保持不变,例如:阈值选取为127
- 小于127的阈值不变化
- 大于等于127的像素点设定为该阈值127
d s t ( x , y ) = { t h r e s h o l d i f s r c ( x , y ) > t h r e s h s r c ( x , y ) , o t h e r w i s e dst(x,y)=\begin{cases} threshold \quad if \quad src(x,y)>thresh \\ src(x,y),otherwise \end{cases} dst(x,y)={thresholdifsrc(x,y)>threshsrc(x,y),otherwise
先选定一个阈值,然后对图像做如下处理:
- 大于等于阈值的像素点变为0
- 小于该阈值的像素点值保持不变
d s t ( x , y ) = { 0 i f s r c ( x , y ) > t h r e s h s r c ( x , y ) , o t h e r w i s e dst(x,y)=\begin{cases} 0 \quad if \quad src(x,y)>thresh \\ src(x,y),otherwise \end{cases} dst(x,y)={0ifsrc(x,y)>threshsrc(x,y),otherwise
先选定一个阈值,然后对图像做如下处理:
- 大于等于阈值的像素点,值保持不变
- 小于该阈值的像素点,值变为0
d s t ( x , y ) = { s r c ( x , y ) i f s r c ( x , y ) > t h r e s h 0 , o t h e r w i s e dst(x,y)=\begin{cases} src(x,y) \quad if \quad src(x,y)>thresh \\ 0,otherwise \end{cases} dst(x,y)={src(x,y)ifsrc(x,y)>thresh0,otherwise
retval, dst = cv2.threshold(src, thresh, maxval, type)
- retval:阈值
- dst:处理结果
- src:源图像
- thresh:阈值
- maxval:最大值
- type:类型
# 二进制阈值化
cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
# 反二进制阈值化
cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)
# 截断阈值化
cv2.threshold(image, 127, 255, cv2.THRESH_TRUNC)
# 反阈值化为0
cv2.threshold(image, 127, 255, cv2.THRESH_TOZERO_INV)
# 阈值化为0
cv2.threshold(image, 127, 255, cv2.THRESH_TOAERO)
import cv2
gray = cv2.imread('image/gray.jpg', cv2.IMREAD_UNCHANGED)
cv2.imshow('gray', gray)
retval, binary = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY) # 二进制阈值化
cv2.imshow('binary', binary)
retval, binary_inv = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY_INV) # 反二进制阈值化
cv2.imshow('binary_inv', binary_inv)
retval, trunc = cv2.threshold(gray, 128, 255, cv2.THRESH_TRUNC) # 截断阈值化
cv2.imshow('trunc', trunc)
retval, tozero_inv = cv2.threshold(gray, 128, 255, cv2.THRESH_TOZERO_INV) # 反阈值化为0
cv2.imshow('zero', tozero_inv)
retval, tozero = cv2.threshold(gray, 128, 255, cv2.THRESH_TOZERO) # 阈值化为0
cv2.imshow('tozero', tozero)
cv2.waitKey(0)
cv2.destroyAllWindows()