OpenCV图像处理—— 图像二值化
图像二值化就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的黑白效果的过程。
1.全局阈值
OpenCV的threshold函数进行全局阈值。其函数原型为:threshold(src, thresh, maxval, type) -> retval, dst
src:输入图像(多通道,8位或32位浮点)。
thresh:阈值。
maxval:与THRESH_BINARY和THRESH_BINARY_INV阈值类型一起使用设置的最大值。
type:阈值类型。
retval:返回的阈值。若是全局固定阈值算法,则返回thresh参数值。若是全局自适应阈值算法,则返回自适应计算得出的合适阈值。
dst:输出与src相同大小和类型以及相同通道数的图像。
阈值类型:
阈值类型图示:
import cv2 as cv
import numpy as np
#全局阈值
def threshold_demo(image):
gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY) #把输入图像灰度化
# 直接阈值化是对输入的单通道矩阵逐像素进行阈值分割。
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
print("threshold value %s" % ret)
cv.namedWindow("binary0", cv.WINDOW_AUTOSIZE)
cv.imshow("binary0", binary)
#局部阈值
def local_threshold(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # 把输入图像灰度化
#自适应阈值化能够根据图像不同区域亮度分布,改变阈值
binary=cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,25,10)
cv.namedWindow("binary1", cv.WINDOW_AUTOSIZE)
cv.imshow("binary1", binary)
#用户自己计算阈值
def custom_threshold(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # 把输入图像灰度化
h, w = gray.shape[:2]
m = np.reshape(gray,[1,w*h])
mean = m.sum()/(w*h)
print("mean: ",mean)
ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
src=cv.imread('F:/Desktop/image/a.JPG')
cv.namedWindow('input_image', cv.WINDOW_AUTOSIZE) #设置为WINDOW_NORMAL可以任意缩放
cv.imshow('input_image', src)
threshold_demo(src)
local_threshold(src)
custom_threshold(src)
cv.waitKey(0)
cv.destroyAllWindows()