使用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);

測試:

輸入
在這裏插入圖片描述
輸出:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章