利用该方法对图形进行二值化处理,能够很好的除去光线对图片的影响
#include<iostream>
#include<opencv2\opencv.hpp>
using namespace cv;
using namespace std;
void thresholdIntegral2(Mat inputMat, Mat outputMat)
{
int nRows = inputMat.rows;
int nCols = inputMat.cols;
// create the integral image
Mat sumMat;
integral(inputMat, sumMat);
int S = MAX(nRows, nCols) / 8;
double T = 0.15;
// perform thresholding
int s2 = S / 2;
int x1, y1, x2, y2, count, sum;
int* p_y1, *p_y2;
uchar* p_inputMat, *p_outputMat;
for (int i = 0; i < nRows; ++i)
{
y1 = i - s2;
y2 = i + s2;
if (y1 < 0)
{
y1 = 0;
}
if (y2 >= nRows)
{
y2 = nRows - 1;
}
p_y1 = sumMat.ptr<int>(y1);
p_y2 = sumMat.ptr<int>(y2);
p_inputMat = inputMat.ptr<uchar>(i);
p_outputMat = outputMat.ptr<uchar>(i);
for (int j = 0; j < nCols; ++j)
{
// set the SxS region
x1 = j - s2;
x2 = j + s2;
if (x1 < 0)
{
x1 = 0;
}
if (x2 >= nCols)
{
x2 = nCols - 1;
}
count = (x2 - x1)* (y2 - y1);
sum = p_y2[x2] - p_y1[x2] - p_y2[x1] + p_y1[x1];
if ((int)(p_inputMat[j] * count) < (int)(sum* (1.0 - T)))
{
p_outputMat[j] = 0;
}
else
{
p_outputMat[j] = 255;
}
}
}
}
int main()
{
Mat src = imread("img2.jpg");
Mat grad;
cvtColor(src, grad, CV_BGR2GRAY);
//Mat bw2 = Mat::zeros(grad.size(), CV_8UC1);
thresholdIntegral2(grad, grad);
imshow("【二值化图】", grad);
imwrite("img2Grad.jpg", grad);
waitKey(0);
return 0;
}
结果如下图所示:
一般方法进行二值化处理
#include<iostream>
#include<opencv2\opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
IplImage *MBDst = cvLoadImage("img2.jpg");
IplImage* MBSrc = cvCreateImage(cvGetSize(MBDst), MBDst->depth, MBDst->nChannels);
cvCopy(MBDst, MBSrc);
cvShowImage("原图", MBSrc);
cvThreshold(MBSrc, MBSrc, 120, 255, CV_THRESH_BINARY);
cvShowImage("【二值化图】", MBSrc);
cvWaitKey(0);
return 0;
}
结果如下图所示: