场景:已知图片OCR结果(字符串内容、字符串坐标),需要对图片进行分类,进而进一步定位每列的属性,对每个字符串x+20做垂直方向投影,统计投影结果,二次处理时排除干扰项
int CExtractInfo::getK(cv::Mat &srcImg)
{
cv::Mat grayImg, binImage;
if (srcImg.channels() == 1)
grayImg = srcImg.clone();
else
cv::cvtColor(srcImg, grayImg, cv::COLOR_RGB2GRAY);
cv::threshold(grayImg, binImage, 100, 255, THRESH_OTSU);
//构造mask
Mat histogramImage(binImage.rows, binImage.cols, CV_8UC1);
for (int i = 0; i < binImage.rows; i++)
{
for (int j = 0; j < binImage.cols; j++)
{
histogramImage.at<uchar>(i, j) = 255;
}
}
Mat histogramImage2 = histogramImage.clone();
Mat histogramImage3 = histogramImage.clone();
for (int k = 0; k < OrgRecoglList.size(); k++)
{
int startCol = OrgRecoglList[k].Pos[0]; //列
int startRow = OrgRecoglList[k].Pos[1]; //行
for (; startRow <= (OrgRecoglList[k].Pos[1] + OrgRecoglList[k].Pos[3]); startRow++)
{
for (; startCol <= (OrgRecoglList[k].Pos[0] + OrgRecoglList[k].Pos[2]); startCol++)
{
histogramImage.at<uchar>(startRow, startCol) = 0;
}
startCol = OrgRecoglList[k].Pos[0];;
}
}
for (int k = 0; k < OrgRecoglList.size(); k++)
{
int startCol = OrgRecoglList[k].Pos[0]; //列
int startRow = OrgRecoglList[k].Pos[1]; //行
for (; startRow <= (OrgRecoglList[k].Pos[1] + OrgRecoglList[k].Pos[3]); startRow++)
{
for (int p = 1; p < 21; p++)
histogramImage2.at<uchar>(startRow, startCol + p) = 0;
}
}
vector<int> res(histogramImage2.cols, 0);
for (int i = 0; i < histogramImage2.cols; i++)
{
for (int j = 0; j < histogramImage2.rows; j++)
{
if (histogramImage2.at<uchar>(j, i) == 0)
res[i]++;
}
}
for (int i = 0; i < histogramImage2.cols; i++)
{
for (int j = 0; j < res[i]; j++)
{
histogramImage3.at<uchar>(histogramImage2.rows - 1 - j, i) = 0;
}
}
vector<vector<int>> slist;//直方图每列累计值->空白行为间隔
for (int i = 0; i <res.size(); i++)
{
vector<int> temp;
while (res[i] != 0)
{
temp.push_back(res[i]);
i++;
}
if (temp.size() != 0)
slist.push_back(temp);
}
//imwrite("c:/histogramImage1.jpg", histogramImage);
//imwrite("c:/histogramImage2.jpg", histogramImage2);
//imwrite("c:/histogramImage3.jpg", histogramImage3);
return slist.size();
}