前言:对于印刷体图片来说,进行水平投影和垂直投影可以很快的进行分割,本文在OpenCV中如何进行水平投影和垂直投影通过代码进行说明。
水平投影:二维图像在y轴上的投影
垂直投影:二维图像在x轴上的投影
由于投影的图像需要进行二值化,本文采用积分二值化的方式,对图片进行处理。
具体代码如下:
1 //积分二值化 2 void thresholdIntegral (Mat inputMat, Mat& outputMat) 3 { 4 5 int nRows = inputMat.rows; 6 int nCols = inputMat.cols; 7 8 // create the integral image 9 Mat sumMat; 10 integral (inputMat, sumMat); 11 12 int S = MAX (nRows, nCols) / 8; 13 double T = 0.15; 14 15 // perform thresholding 16 int s2 = S / 2; 17 int x1, y1, x2, y2, count, sum; 18 19 int* p_y1, *p_y2; 20 uchar* p_inputMat, *p_outputMat; 21 22 for (int i = 0; i < nRows; ++i) 23 { 24 y1 = i - s2; 25 y2 = i + s2; 26 27 if (y1 < 0) 28 { 29 y1 = 0; 30 } 31 if (y2 >= nRows) 32 { 33 y2 = nRows - 1; 34 } 35 36 p_y1 = sumMat.ptr<int> (y1); 37 p_y2 = sumMat.ptr<int> (y2); 38 p_inputMat = inputMat.ptr<uchar> (i); 39 p_outputMat = outputMat.ptr<uchar> (i); 40 41 for (int j = 0; j < nCols; ++j)