1.概述
字符分割有很多方法,但并不是每一种方法是万能的,那么就需要根据自己的需要来分析。例如:我现在项目的需求是将一串编号给切分开来。查了网上的资料和文献,大致适合项目的有两种方法:投影分割法和连通域分割法。当然还有其他的一些改进的算法,今天就不作深入讨论,以后研究了再分享。
2.分析
投影法的原理其实很简单,利用二值化图片的像素的分布直方图进行分析,从而找出相邻字符的分界点进行分割。

上图其实已经看的很明白,投影所反应的就是在垂直方向上数字区域像素个数。接下来我们只需判断投影的每一列,即可找出分割点。
3.实现过程
首先,定义一个数组用来储存每一列像素中白色像素的个数。
int perPixelValue;
int* projectValArry = new int[width];
memset(projectValArry, 0, width*4);
然后,遍历二值化后的图片,将每一列中白色的(也就是数字区域)像素记录在数组中。
for (int col = 0; col < width; ++col)
{
for (int row = 0; row < height; ++row)
{
perPixelValue = binImg.at<uchar>(row, col);
if (perPixelValue == 255)
{
projectValArry[col]++;
}
}
}
最后,根据数组里的灰度值画出投影图
Mat verticalProjectionMat(height, width, CV_8UC1);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
perPixelValue = 255;
verticalProjectionMat.at<uchar>(i, j) = perPixelValue;
}
}
for (int i = 0; i < width; i++)
{
for (int j = 0; j < projectValArry[i]; j++)
{
perPixelValue = 0;
verticalProjectionMat.at<uchar>(height - 1 - j, i) = perPixelValue;
}
}
imshow("【投影】",verticalProjectionMat);
delete[] projectValArry;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
有了投影图做切割就很容易了,其实最主要的就是那个储存灰度值的数组,下面就需要根据这个数组的内容来找到相邻字符间的分割点。
vector<Mat> roiList;
int startIndex = 0;
int endIndex = 0;
bool inBlock = false;
for (int i = 0; i < srcImg.cols; ++i)
{
if (!inBlock && projectValArry[i] != 0)
{
inBlock = true;
startIndex = i;
cout << "startIndex is " << startIndex << endl;
}
else if (projectValArry[i] == 0 && inBlock)
{
endIndex = i;
inBlock = false;
Mat roiImg = srcImg(Range(0,srcImg.rows),Range(startIndex,endIndex+1));
roiList.push_back(roiImg);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
最后来看下效果图:

4.总结
做图像分割的时候要选择合适的方法,例如我这张样本图的布局是左右型,就适合用垂直投影的方法,反之若是上下型,则做水平投影即可。若图像内的字符是纵横交错的话就需要先垂直投影分割再水平分割,或者采用连通域分割法,取出字符范围。