图像二值化是将一幅图像的所有像素值转换为只有两个值之间的操作。通常情况下,这两个像素值是0和255,分别代表黑色和白色。
图像二值化可以通过选择一个阈值来实现。对于每个像素,将其灰度值与阈值进行比较,如果大于阈值,则将像素值设置为255(白色),否则将像素值设置为0(黑色)。这样,图像中的像素要么为黑色,要么为白色,从而实现了二值化。
通常使用threshold()函数来实现图像的二值化
1、threshold()函数
double cv::threshold(InputArray src,
OutputArray dst,
double thresh,
double maxval,
int type
)
src:待二值化的图像,图像只能是CV_8U和CV_32F两种数据类型。对于图像通道数目的要求和选择的二值化方法相关
dst:二值化后的图像,与输入图像具有相同的尺寸、数据类型和通道数
thresh:二值化的阈值
maxval:二值化过程的最大值,此函数只在THRESH_BINARY和THRESH_BINARY_INV两种二值化方法中才使用,但是在使用其他方法是也需要输入
type:选择图像二值化方法的标志
例:
#include <opencv2\opencv.hpp>
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
int main()
{
Mat img = imread("lena.png");
if (img.empty())
{
cout << "请确认图像文件名称是否正确" << endl;
return -1;
}
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);//转换为灰度图像
Mat img_B, img_B_V, gray_B, gray_B_V, gray_T, gray_T_V, gray_TRUNC;
//彩色图像二值化
threshold(img, img_B, 125, 255, THRESH_BINARY);
threshold(img, img_B_V, 125, 255, THRESH_BINARY_INV);
imshow("img_B", img_B);
imshow("img_B_V", img_B_V);
//灰度图BINARY二值化
threshold(gray, gray_B, 125, 255, THRESH_BINARY);
threshold(gray, gray_B_V, 125, 255, THRESH_BINARY_INV);
imshow("gray_B", gray_B);
imshow("gray_B_V", gray_B_V);
//灰度图像TOZERO变换
threshold(gray, gray_T, 125, 255, THRESH_TOZERO);
threshold(gray, gray_T_V, 125, 255, THRESH_TOZERO_INV);
imshow("gray_T", gray_T);
imshow("gray_T_V", gray_T_V);
//灰度图像TRUNC变换
threshold(gray, gray_TRUNC, 125, 255, THRESH_TRUNC);
imshow("gray_TRUNC", gray_TRUNC);
waitKey(0);
return 0;
}
附:选择图像二值化方法的标志