阈值处理是指将大于某一像素值的设为255,低于某一像素值的设为0。由此可以得到一幅二值图像,有效地实现了前景和背景的分离。OpenCV中提供了函数cv2.threshhold()
和cv2.adaptiveThreshold()
用于阈值处理。本节主要介绍第一个函数。
[TOC]
threshold()
函数的用法
retval, dst = cv2.threshold(src, thresh, maxval, type)
- retval表示返回的阈值
- dst表示返回的阈值分割的图像
- src表示源图像,可以是多通道的,8位的或者32位浮点型数值
- maxval,当type参数为THRESH_BINARY和THRESH_BINARY_INV类型时,需要设定的最大值
- type代表阈值分割的类型,如下图所示。
二值化阈值处理(cv2.THRESH_BINARY
)
这个类型会将直接处理为仅有两个值的二值图像。
- 如上图所示,大于这个阈值直接变为255,小于等于这个阈值直接变为0
例1:使用二值化阈值处理,观察结果。
import cv2
import numpy as np
img = np.random.randint(0, 256, size=[4, 5], dtype=np.uint8)
t, rst = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
print('img=\n', img)
print('t=\n', t)
print('rst=\n', rst)
结果:
img=
[[133 173 81 128 221]
[ 72 204 33 114 166]
[193 31 4 35 239]
[ 61 32 186 184 33]]
t=
127.0
rst=
[[255 255 0 255 255]
[ 0 255 0 0 255]
[255 0 0 0 255]
[ 0 0 255 255 0]]
例2:使用函数cv2.threshold()对图像进行二值化处理。
import cv2
img = cv2.imread('boy.png', 0)
t, rst = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('IMG', img)
cv2.imshow('RST', rst)
cv2.waitKey()
反二值化阈值处理(cv2.THRESH_BINARY_INA
)
反二值化阈值处理的结果也是仅有两个值的二值图像,与二值化阈值处理正好相反。
大于阈值直接变为0,小于等于这个阈值直接变为255
import cv2
img = cv2.imread('boy.png', 0)
t, rst = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('IMG', img)
cv2.imshow('RST', rst)
cv2.waitKey()