© Fu Xianjun. All Rights Reserved.
阈值处理是指剔除图像内像素值高于一定值或者低于一定值的像素点。例如,设定阈值为180,然后:
1.将图像中所有像素值小于180的设置为0
2. 将图像中所有像素值大于等于180的设置为255
通过上述方式能够得到一副二值图像,如效果图所示,按照上述阈值处理方式将一副灰度图像处理为一副二值图像,有效地实现了前景和背景的分离。
效果图
原图:
处理后的原图:
OpenCV提供了函数cv2.threshold()和函数cv2.adaptiveThreshold(),用于实现阈值处理。
ret, dst = cv2.threshold(src, thresh, maxval, type)
src: 输入图,只能输入单通道图像,通常来说为灰度图
dst: 输出图
thresh: 阈值
maxval: 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
type:二值化操作的类型,包含以下5种类型:
cv2.THRESH_BINARY;
cv2.THRESH_BINARY_INV;
cv2.THRESH_TRUNC;
cv2.THRESH_TOZERO;
cv2.THRESH_TOZERO_INV
cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
cv2.THRESH_BINARY_INV THRESH_BINARY的反转
cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变
cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转
函数的使用
peppa = cv2.imread('peppa.jpg')
img=cv2.cvtColor(peppa,cv2.COLOR_BGR2GRAY)
cv2.imshow('Peppa',img)
ret,thresh1 = cv2.threshold(img,200,255,cv2.THRESH_BINARY) #二值化阈值处理
ret,thresh2 = cv2.threshold(img,200,255,cv2.THRESH_BINARY_INV) #反二值化阈值处理
ret,thresh3 = cv2.threshold(img,200,255,cv2.THRESH_TRUNC) #截断阈值化处理
ret,thresh4 = cv2.threshold(img,200,255,cv2.THRESH_TOZERO) #超阈值零处理
ret,thresh5 = cv2.threshold(img,200,255,cv2.THRESH_TOZERO_INV) #低阈值零处理
cv2.imshow('BINARY',thresh1)
cv2.imshow('BINARY_INV',thresh2)
peppa_body=cv2.bitwise_and(peppa,peppa,mask=thresh2)
cv2.imshow('peppa_body',peppa_body)
cv2.waitKey()
cv2.destroyAllWindows()
import cv2
Type=0 #阈值处理类型值
Value=0 #使用的阈值
def onType(a):
Type= cv2.getTrackbarPos(tType, windowName)
Value= cv2.getTrackbarPos(tValue, windowName)
ret, dst = cv2.threshold(img, Value,255, Type)
cv2.imshow(windowName,dst)
def onValue(a):
Type= cv2.getTrackbarPos(tType, windowName)
Value= cv2.getTrackbarPos(tValue, windowName)
ret, dst = cv2.threshold(img, Value, 255, Type)
cv2.imshow(windowName,dst)
img = cv2.imread("peppa.jpg",0)
windowName = "Peppa" #窗体名
cv2.namedWindow(windowName)
cv2.imshow(windowName,img)
#创建两个滑动条
tType = "Type" #用来选取阈值处理类型的滚动条
tValue = "Value" #用来选取阈值的滚动条
cv2.createTrackbar(tType, windowName, 0, 4, onType)
cv2.createTrackbar(tValue, windowName,0, 255, onValue)
cv2.waitKey()
cv2.destroyAllWindows()
img=cv2.imread('peppa.jpg',0)
athdMEAN=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,7,5)
athdGAUS=cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,3)
cv2.imshow("athMEAN",athdMEAN)
cv2.imshow("athGAUS",athdGAUS)
cv2.waitKey(0)
cv2.destroyAllWindows()
Otsu阈值处理的实现
import cv2
import numpy as np
img=cv2.imread('peppa.jpg',0)
ret,otsu=cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imshow("img",img)
cv2.imshow("otsu",otsu)
cv2.waitKey(0)
cv2.destroyAllWindows()