? 在图像处理过程中,阈值的使用使得图像的像素值更单一,进而使得图像的效果更简单。首先,把一副彩色图像转换为灰度图像,这样图像的像素值的取值范围即可简化为0~255.然后,通过阈值使得转换后的灰度图像呈现出只有纯黑色和纯白色的视觉效果。
? 例如,当阈值为127时,把小于127的所有像素值都转换为0(即纯黑色),把大一127的所有像素值都转换为255(即纯白色)。虽然会丢失一些灰度细节,但是会更明显地保留灰度图像主体地轮廓。
阈值处理方法
retval,dst = cv2.threshold(src,thresh,maxval,type)
类型 | 含义 |
---|
cv2.THRESH_BINARY | 二值化阈值处理 | cv2.THRESH_BINARY_INV | 反二值化阈值处理 | cv2.THRESH_TOZERO | 低于阈值零处理 | cv2.THRESH_TOZERO_INV | 超出阈值零处理 | cv2.THRESH_TRUNC | 截断阈值处理 |
二值化处理白黑渐变图
import cv2
img = cv2.imread("logo.jpg",0)
t1,dst1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
cv2.imshow('img',img)
cv2.imshow('dst1',dst1)
cv2.waitKey()
反二值化处理图像
import cv2
img = cv2.imread("logo.jpg",0)
t1,dst1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
t4,dst4 = cv2.threshold(img,127,255,cv2.THRESH_BINARY_INV)
cv2.imshow('img',img)
cv2.imshow('dst1',dst1)
cv2.imshow('dst4',dst4)
cv2.waitKey()
常用的5种阈值处理
import cv2
img = cv2.imread("boooMa.png")
img_Gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
t1,dst1 = cv2.threshold(img_Gray,127,255,cv2.THRESH_BINARY)
t4,dst2 = cv2.threshold(img_Gray,127,255,cv2.THRESH_BINARY_INV)
t4,dst3 = cv2.threshold(img_Gray,127,255,cv2.THRESH_TOZERO)
t4,dst4 = cv2.threshold(img_Gray,127,255,cv2.THRESH_TOZERO_INV)
t4,dst5 = cv2.threshold(img_Gray,127,255,cv2.THRESH_TRUNC)
cv2.imshow('img',img)
cv2.imshow('GRAY',img_Gray)
cv2.imshow('BINARY',dst1)
cv2.imshow('BINARY_INV',dst2)
cv2.imshow('TOZERO',dst3)
cv2.imshow('TOZERO_INV',dst4)
cv2.imshow('TRUNC',dst5)
cv2.waitKey()
自适应处理
dst = cv2.adaptiveThreshold(src,maxValue,adaptiveMethod,thresholdType,blockSize,C)
计算方法 | 含义 |
---|
cv2,ADPTIVE_THRESH_MEAN_C | 对一个正方形区域内的所有像素平均加权 | cv2.ADAPTIVE_THRESH_GAUSSIAN_C | 根据高斯函数按照像素与中心点的距离对一个正方形区域内的所欲像素进行加权计算 |
import cv2
img = cv2.imread("boooMa.png")
img_GRAY = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
athdMEAM = cv2.adaptiveThreshold(img_GRAY,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,5,3)
athdGAUS = cv2.adaptiveThreshold(img_GRAY,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,5,3)
cv2.imshow("MEAN_C",athdMEAM)
cv2.imshow("GAUSSIAN_C",athdGAUS)
cv2.waitKey()
Otsu方法
Otsu方法能够遍历所有可能的阈值,从中找到最合适的阈值。
retval,dst = cv2.threshold(src,thresh,maxval,type)
import cv2
img = cv2.imread("boooMa.png")
img_GRAY = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
t1,dst1 = cv2.threshold(img_GRAY,127,255,cv2.THRESH_BINARY)
t2,dst2 = cv2.threshold(img_GRAY,0,255,cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.putText(dst2,"best threshold:" + str(t2),(0,30),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,0),2)
cv2.imshow("BINARY",dst1)
cv2.imshow("OTSU",dst2)
cv2.waitKey()
|