使用OpenCV进行身份证号码字符进行分割

前言

经过前面的代码处理,已得到身份证上的唯一的号码区域,那么下面的代码是把号码区域切割成单个字符,这一步是为了以后的识别做准备。

代码

//把整个字符图像分割成单个字符图像
//传入一个切割出来的号码区域,输出一个分割好的单个字符的容器
void charRegion(const Mat &char_area, vector<Mat> &char_dst)
{
	Mat img_threshold;

	//新建一个全白图像
	Mat white_base(char_area.size(), char_area.type(), cv::Scalar(255));
	//相减得到反转的图像
	Mat reversal_mat = white_base - char_area;
#ifdef DEBUG
	imshow("号码区域反转", reversal_mat);
#endif // DEBUG

	//大津法二值化
	threshold(reversal_mat, img_threshold, 0, 255, CV_THRESH_OTSU); 

	int char_index[19] = { 0 };
	short counter = 1;
	short num = 0;

	bool *flag = new bool[img_threshold.cols];

	for (int j = 0; j < img_threshold.cols; ++j)
	{
		flag[j] = true;
		for (int i = 0; i < img_threshold.rows; ++i)
		{

			if (img_threshold.at<uchar>(i, j) != 0)
			{
				flag[j] = false;
				break;
			}
		}
	}

	for (int i = 0; i < img_threshold.cols - 2; ++i)
	{
		if (flag[i] == true)
		{
			char_index[counter] += i;
			num++;
			if (flag[i + 1] == false && flag[i + 2] == false)
			{
				char_index[counter] = char_index[counter] / num;
				num = 0;
				counter++;
			}
		}
	}
	char_index[18] = img_threshold.cols;

	for (int i = 0; i < 18; i++)
	{
		char_dst.push_back(Mat(reversal_mat, Rect(char_index[i], 0, char_index[i + 1] - char_index[i], img_threshold.rows)));
	}
#ifdef DEBUG
	for (int i = 0; i < char_dst.size(); i++)
	{
		string name = to_string(i);
		imshow(name, char_dst.at(i));
		imwrite(name+".png", char_dst.at(i));
	}
#endif // DEBUG
}

函数调用方式:

Mat src = imread("src.png",0);
vector<Mat> char;
charRegion(src,char);

测试:

输入
在这里插入图片描述
输出:
在这里插入图片描述

发布了79 篇原创文章 · 获赞 45 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/matt45m/article/details/99062079
今日推荐