©FuXianjun
阈值处理类似于分段函数处理,设定一个阈值,若图像中的像素点灰度值大于阈值,对其做一定处理;对低于阈值的像素点做另一类处理。如对于一幅灰度图,我们设定阈值为125,大于125的像素点灰度值设为255,小于255的像素点设为0,这样我们就可以得到一副二值图像。
在OpenCV中提供了cv2.threshold()和cv2.adaptiveThreshold()来实现阈值处理。
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()
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()
cv2.adaptiveThreshold()
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()
img=cv2.imread('peppa.jpg',0)
ret,otsu=cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
cv2.imshow("otsu",otsu)
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
img = cv2.imread("peppa_gaussian.jpg")
blur = cv2.blur(img, (7, 7))
box = cv2.boxFilter(img,-1,(7,7), normalize=True)
gaussian = cv2.GaussianBlur(img, (7, 7), 10)
median = cv2.medianBlur(img, 7)
bilater=cv2.bilateralFilter(img,9,75,75)
kernel = np.array((
[-2, -1, 0],
[-1,1,1],
[0, 1, 2]), dtype="float32")
filter2D=cv2.filter2D(img,-1,kernel)#https://my.oschina.net/u/4306156/blog/3598055
cv2.imshow('img',img)
cv2.imshow('blur',blur)
cv2.imshow('box',box)
cv2.imshow('gaussian',gaussian)
cv2.imshow('median',median)
cv2.imshow('bilater',bilater)
cv2.imshow('filter2D',filter2D)
cv2.waitKey()
cv2.destroyAllWindows()