图像的二值化就是将图像上的像素点的灰度值设置为0或255,这样将使整个图像呈现出明显的黑白效果。在数字图像处理中,二值图像占有非常重要的地位,图像的二值化使图像中数据量大为减少,从而能凸显出目标的轮廓。OpenCV中提供了函数cv::threshold();
注意:作者采用OpenCV 3.0.0
函数原型
参数说明
src:源图像,可以为8位的灰度图,也可以为32位的彩色图像。(两者由区别)
dst:输出图像
thresh:阈值
maxval:dst图像中最大值
type:阈值类型,可以具体类型如下:
编号 | 阈值类型枚举 | 注意 |
1 | THRESH_BINARY |
|
2 | THRESH_BINARY_INV |
|
3 | THRESH_TRUNC |
|
4 | THRESH_TOZERO |
|
5 | THRESH_TOZERO_INV |
|
6 | THRESH_MASK | 不支持 |
7 | THRESH_OTSU | 不支持32位 |
8 | THRESH_TRIANGLE | 不支持32位 |
具体如下表
生成关系如下表
函数参考可以至http://docs.opencv.org/3.0.0/examples.html
测试代码
Mat gray; cvtColor(src, gray, CV_BGR2GRAY); // 全局二值化 int th = 100; cv::Mat threshold1,threshold2,threshold3,threshold4,threshold5,threshold6,threshold7,threshold8; cv::threshold(gray, threshold1, th, 255, THRESH_BINARY); cv::threshold(gray, threshold2, th, 255, THRESH_BINARY_INV); cv::threshold(gray, threshold3, th, 255, THRESH_TRUNC); cv::threshold(gray, threshold4, th, 255, THRESH_TOZERO); cv::threshold(gray, threshold5, th, 255, THRESH_TOZERO_INV); //cv::threshold(gray, threshold6, th, 255, THRESH_MASK); cv::threshold(gray, threshold7, th, 255, THRESH_OTSU); cv::threshold(gray, threshold8, th, 255, THRESH_TRIANGLE); cv::imshow("THRESH_BINARY", threshold1); cv::imshow("THRESH_BINARY_INV", threshold2); cv::imshow("THRESH_TRUNC", threshold3); cv::imshow("THRESH_TOZERO", threshold4); cv::imshow("THRESH_TOZERO_INV", threshold5); //cv::imshow("THRESH_MASK", threshold6); cv::imshow("THRESH_OTSU", threshold7); cv::imshow("THRESH_TRIANGLE", threshold8); cv::waitKey(0); |
测试结果
原图 | |
THRESH_BINARY | |
THRESH_BINARY_INV | |
THRESH_TRUNC | |
THRESH_TOZERO | |
THRESH_TOZERO_INV | |
THRESH_OTSU | |
THRESH_TRIANGLE | |
注意:
如果采用彩色图像进行计算会得到彩色效果,而不是预期的二值化结果
彩色源图 | 灰度源图 |
| |