本文介绍使用不同的阈值方法“二值化”图像
固定阈值分割
图解
代码
import cv2 as cv
# 读入灰度图像
img = cv.imread('baby_g.jpg', 0)
# 阈值127分割图像
ret, th = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
cv.imshow('thresh', th)
cv.waitKey(0)
cv.destroyAllWindows()
函数讲解
cv.threshold()用来实现阈值分割,ret是return value缩写,代表当前的阈值,暂时不用理会。函数有4个参数:
参数1:要处理的原图,一般是灰度图
参数2:设定的阈值
参数3:最大阈值,一般为255
参数4:阈值的方式,主要有5种。
cv.threshold() 参数4阈值方式详解
实验
import cv2 as cv
import matplotlib.pyplot as plt
img = cv.imread('gradient.jpg',0)
# 应用5种不同的阈值方法
ret, th1 = cv.threshold(img, 127, 255, cv.THRESH_BINARY)
ret, th2 = cv.threshold