一、图像二值化基本原理:
对灰度图像进行处理,设定阈值,在阈值中的像素值将变为1(白色部分),阈值为的将变为0(黑色部分)。
二、图像二值化处理步骤:
(1)先对彩色图像进行灰度化
//img为原图,imgGray为灰度图
cvtColor(img, imgGray, CV_BGR2GRAY);
(2)对灰度图进行二值化
//imgGray为灰度图,result为二值图像
//100~255为阈值,可以根据情况设定
//在阈值中的像素点将变为0(白色部分),阈值之外的像素将变为1(黑色部分)。
threshold(imgGray, result, 100, 255, CV_THRESH_BINARY);
三、demo
#include<iostream>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\core\core.hpp>
#include <opencv2\imgproc\imgproc.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat img, imgGray,result;
img = imread("test.jpg");
if (!img.data) {
cout << "Please input image path" << endl;
return 0;
}
imshow("原图", img);
cvtColor(img, imgGray, CV_BGR2GRAY);
imshow("灰度图", imgGray);
//blur(imgGray, imgGray, Size(3, 3));
threshold(imgGray, result, 100, 255, CV_THRESH_BINARY);
imshow("二值化后的图", result);
imwrite("二值化的二维码.jpg", result);
cout << "图片已保存" << endl;
waitKey();
return 0;
}