Compare commits

..

58 Commits

Author SHA1 Message Date
zoeda 24a4eff533 泛读报告
1 year ago
zoeda 2dacb00554 Merge branch 'liuchengxin_branch' into develop
1 year ago
zoeda bd8569c03a 泛读报告完善
1 year ago
zhangtengyuan 12f677eca7 2
1 year ago
pmuy8zkev b4df52f6b0 Merge pull request '评注完毕' (#27) from gewenlin_branch into develop
1 year ago
zhangtengyuan 76ac41ebe0 1
1 year ago
p8bwig6of 4d9a3513f7 修改chars_segment
1 year ago
golden 7b213de4b8 new
1 year ago
gewenlin 831103c2f6 评注完毕
1 year ago
heureux 5eca185d11 zhy修改
1 year ago
zoeda e4f6eba330 删除了多余的报告doc
1 year ago
zoeda 52d52f4238 把黄炳城搞错的文件夹全删除了
1 year ago
zoeda 7ae4300828 Merge branch 'liuchengxin_branch' into develop
1 year ago
zoeda 7b4abff14f lcx complete /src/core_func.cpp
1 year ago
pmuy8zkev b6ca2514ae Merge pull request '泛读报告' (#23) from liuchengxin_branch into develop
2 years ago
zoeda 9001952a13 泛读报告
2 years ago
pmuy8zkev 31ece3b7f8 Merge pull request '评注代码+用例图' (#22) from gewenlin_branch into develop
2 years ago
gewenlin f98d9757f8 评注文件+用例图
2 years ago
p74f62umr c0e91d6576 Merge pull request 'core_func.cpp评注WXP2.0' (#21) from wuxiuping_branch into develop
2 years ago
www-369 1809748e2f WXP2.1
2 years ago
www-369 d25d52f469 WXP2.0
2 years ago
p8bwig6of d195201cd8 Merge pull request '软件描述' (#20) from huangbingcheng-branch into develop
2 years ago
golden f63769b99e 软件
2 years ago
pktmsxg6u 4ce4d5d103 Merge pull request 'god' (#15) from zhaohaoyi_branch into develop
2 years ago
heureux 5f06f531b3 zhaohaoyi
2 years ago
www-369 5e82037ce5 Merge branch 'develop' of https://bdgit.educoder.net/pmuy8zkev/Galaxy into wuxiuping_branch
2 years ago
www-369 e8e1874816 WXP1.0
2 years ago
p8bwig6of aa8753f44a Merge pull request '修改chars_segment.cpp' (#13) from huangbingcheng_branch into develop
2 years ago
golden c9acbeb31a chars_segment
2 years ago
heureux b5a5b7dd0d zhaohaoyi
2 years ago
www-369 0d03268573 Merge branch 'develop' into wuxiuping_branch
2 years ago
www-369 2ed8bbe608 WXP0
2 years ago
pmuy8zkev 9bc075c78e Merge pull request 'chars_identify' (#11) from liuchengxin_branch into develop
2 years ago
zhangtengyuan 44fe88aba9 注释了ann_train的整体代码
2 years ago
mgvupb28w 568f69d4fa Delete '1.txt'
2 years ago
mgvupb28w 9260817edd Merge pull request '训练目录,存放模型训练的代码部分评注' (#10) from zhanzhipeng_branch into develop
2 years ago
pmuy8zkev db4138a2c9 Merge pull request '注释了src文件夹下core文件夹下的chars_recognise.cpp文法' (#8) from gewenlin_branch into develop
2 years ago
p8bwig6of 0b74540fab Merge pull request 'src' (#9) from huangbingcheng_branch into develop
2 years ago
gewenlin a4352299fc 修改
2 years ago
Www-369 7428e17395 Merge branch 'wuxiuping_branch' of https://bdgit.educoder.net/pmuy8zkev/Galaxy into wuxiuping_branch
2 years ago
golden 4b6c4c4035 src
2 years ago
Www-369 923538ba37 WXP
2 years ago
gewenlin f652ce2b33 删除
2 years ago
Www-369 fa1a23a978 WXP
2 years ago
gewenlin 05d502de0d Merge branch 'gewenlin_branch' of https://bdgit.educoder.net/pmuy8zkev/Galaxy into develop
2 years ago
gewenlin e177967097 注释
2 years ago
zzp 010c141028 训练目录,存放模型训练的代码评注
2 years ago
zzp 0886cf2a1b 训练目录,存放模型训练的代码评注
2 years ago
pmuy8zkev 682a5d4669 Merge pull request 'EasyPR' (#6) from liuchengxin_branch into develop
2 years ago
gewenlin 724586c390 Merge branch 'gewenlin_branch' of https://bdgit.educoder.net/pmuy8zkev/Galaxy into gewenlin_branch
2 years ago
gewenlin d42e6086dc 2
2 years ago
gewenlin 5d2a15ac00 22
2 years ago
gewenlin 96915c4f22 23
2 years ago
pmuy8zkev db39095cf9 Merge pull request 'new target' (#5) from liuchengxin_branch into develop
2 years ago
gewenlin b4f37273f2 s
2 years ago
pmuy8zkev a6b43bc244 Merge pull request 'able' (#4) from liuchengxin_branch into develop
2 years ago
zzp 737e427c4c zhanzhipeng_branch
2 years ago
gewenlin debf3e2eab 11
2 years ago

@ -1 +0,0 @@
123123

Binary file not shown.

@ -7,18 +7,23 @@
using namespace cv; using namespace cv;
namespace easypr { namespace easypr
{
CharsIdentify* CharsIdentify::instance_ = nullptr; CharsIdentify *CharsIdentify::instance_ = nullptr;
CharsIdentify* CharsIdentify::instance() { CharsIdentify *CharsIdentify::instance()
if (!instance_) { {
if (!instance_)
{
instance_ = new CharsIdentify; instance_ = new CharsIdentify;
} }
return instance_; return instance_;
} }
CharsIdentify::CharsIdentify() { // 主要用于加载和管理预训练的神经网络模型,用于字符识别
CharsIdentify::CharsIdentify()
{
LOAD_ANN_MODEL(ann_, kDefaultAnnPath); LOAD_ANN_MODEL(ann_, kDefaultAnnPath);
LOAD_ANN_MODEL(annChinese_, kChineseAnnPath); LOAD_ANN_MODEL(annChinese_, kChineseAnnPath);
LOAD_ANN_MODEL(annGray_, kGrayAnnPath); LOAD_ANN_MODEL(annGray_, kGrayAnnPath);
@ -27,95 +32,128 @@ CharsIdentify::CharsIdentify() {
kv_->load(kChineseMappingPath); kv_->load(kChineseMappingPath);
extractFeature = getGrayPlusProject; extractFeature = getGrayPlusProject;
} }
void CharsIdentify::LoadModel(std::string path) { void CharsIdentify::LoadModel(std::string path)
if (path != std::string(kDefaultAnnPath)) { {
if (path != std::string(kDefaultAnnPath))
{
if (!ann_->empty()) if (!ann_->empty())
ann_->clear(); ann_->clear();
LOAD_ANN_MODEL(ann_, path); LOAD_ANN_MODEL(ann_, path);
} }
} }
void CharsIdentify::LoadChineseModel(std::string path) { void CharsIdentify::LoadChineseModel(std::string path)
if (path != std::string(kChineseAnnPath)) { {
if (path != std::string(kChineseAnnPath))
{
if (!annChinese_->empty()) if (!annChinese_->empty())
annChinese_->clear(); annChinese_->clear();
LOAD_ANN_MODEL(annChinese_, path); LOAD_ANN_MODEL(annChinese_, path);
} }
} }
void CharsIdentify::LoadGrayChANN(std::string path) { void CharsIdentify::LoadGrayChANN(std::string path)
if (path != std::string(kGrayAnnPath)) { {
if (path != std::string(kGrayAnnPath))
{
if (!annGray_->empty()) if (!annGray_->empty())
annGray_->clear(); annGray_->clear();
LOAD_ANN_MODEL(annGray_, path); LOAD_ANN_MODEL(annGray_, path);
} }
} }
void CharsIdentify::LoadChineseMapping(std::string path) { void CharsIdentify::LoadChineseMapping(std::string path)
{
kv_->clear(); kv_->clear();
kv_->load(path); kv_->load(path);
} }
void CharsIdentify::classify(cv::Mat featureRows, std::vector<int>& out_maxIndexs, // 对输入的特征行进行预测,并识别出最可能的字符。
std::vector<float>& out_maxVals, std::vector<bool> isChineseVec){ void CharsIdentify::classify(cv::Mat featureRows, std::vector<int> &out_maxIndexs,
std::vector<float> &out_maxVals, std::vector<bool> isChineseVec)
{
// 获取特征行的行数。
int rowNum = featureRows.rows; int rowNum = featureRows.rows;
// 创建一个新的矩阵output大小为特征行的行数rowNum乘以总的字符数量
cv::Mat output(rowNum, kCharsTotalNumber, CV_32FC1); cv::Mat output(rowNum, kCharsTotalNumber, CV_32FC1);
// 使用预先训练好的模型ann_对输入的特征行进行预测结果保存在output矩阵中
ann_->predict(featureRows, output); ann_->predict(featureRows, output);
// 循环遍历每一行输出:
for (int output_index = 0; output_index < rowNum; output_index++) { // 对于每一行,首先获取该行的预测结果
for (int output_index = 0; output_index < rowNum; output_index++)
{
Mat output_row = output.row(output_index); Mat output_row = output.row(output_index);
int result = 0; int result = 0;
float maxVal = -2.f; float maxVal = -2.f;
bool isChinses = isChineseVec[output_index]; bool isChinses = isChineseVec[output_index];
if (!isChinses) { // 如果该行不是中文字符由isChineseVec向量确定
// 则遍历前kCharactersNumber个预测结果找出值最大的那个并记录其索引和值。
if (!isChinses)
{
result = 0; result = 0;
for (int j = 0; j < kCharactersNumber; j++) { for (int j = 0; j < kCharactersNumber; j++)
{
float val = output_row.at<float>(j); float val = output_row.at<float>(j);
// std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
} }
else { // 如果该行是中文字符,
// 则从kCharactersNumber开始遍历后面的预测结果找出值最大的那个并记录其索引和值。
else
{
result = kCharactersNumber; result = kCharactersNumber;
for (int j = kCharactersNumber; j < kCharsTotalNumber; j++) { for (int j = kCharactersNumber; j < kCharsTotalNumber; j++)
{
float val = output_row.at<float>(j); float val = output_row.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
} }
// 将记录的最大索引和最大值分别赋值给out_maxIndexs和out_maxVals的相应位置
out_maxIndexs[output_index] = result; out_maxIndexs[output_index] = result;
out_maxVals[output_index] = maxVal; out_maxVals[output_index] = maxVal;
} }
} }
void CharsIdentify::classify(std::vector<CCharacter>& charVec){ // 接受一个CCharacter类型的向量charVec并对每个字符进行分类。
void CharsIdentify::classify(std::vector<CCharacter> &charVec)
{
size_t charVecSize = charVec.size(); size_t charVecSize = charVec.size();
if (charVecSize == 0) if (charVecSize == 0)
return; return;
// 创建一个名为featureRows的Mat对象并通过循环将每个字符的特征提取出来并添加到featureRows中。
Mat featureRows; Mat featureRows;
for (size_t index = 0; index < charVecSize; index++) { for (size_t index = 0; index < charVecSize; index++)
{
Mat charInput = charVec[index].getCharacterMat(); Mat charInput = charVec[index].getCharacterMat();
Mat feature = charFeatures(charInput, kPredictSize); Mat feature = charFeatures(charInput, kPredictSize);
featureRows.push_back(feature); featureRows.push_back(feature);
} }
// 创建一个输出矩阵output并使用预先训练好的模型ann_对特征进行预测。
cv::Mat output(charVecSize, kCharsTotalNumber, CV_32FC1); cv::Mat output(charVecSize, kCharsTotalNumber, CV_32FC1);
ann_->predict(featureRows, output); ann_->predict(featureRows, output);
for (size_t output_index = 0; output_index < charVecSize; output_index++) { // 遍历每个输出,对于每个输出,首先获取对应的字符(通过索引),
CCharacter& character = charVec[output_index]; // 然后获取该字符的预测结果行(通过索引)。然后,函数检查该字符是否为中文字符,
// 如果不是,它就在循环中找出值最大的预测结果,并记录其索引和值。
// 最后,函数根据这个最大值和索引确定预测的字符,并将其作为标签。
for (size_t output_index = 0; output_index < charVecSize; output_index++)
{
CCharacter &character = charVec[output_index];
Mat output_row = output.row(output_index); Mat output_row = output.row(output_index);
int result = 0; int result = 0;
@ -123,212 +161,277 @@ void CharsIdentify::classify(std::vector<CCharacter>& charVec){
std::string label = ""; std::string label = "";
bool isChinses = character.getIsChinese(); bool isChinses = character.getIsChinese();
if (!isChinses) { if (!isChinses)
{
result = 0; result = 0;
for (int j = 0; j < kCharactersNumber; j++) { for (int j = 0; j < kCharactersNumber; j++)
{
float val = output_row.at<float>(j); float val = output_row.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
label = std::make_pair(kChars[result], kChars[result]).second; label = std::make_pair(kChars[result], kChars[result]).second;
} }
else { // 如果字符是中文字符,函数则从预测结果的后面部分开始查找最大值,并记录其索引和值。
// 然后函数根据这个最大值和索引确定预测的字符并通过键值对kv_查找对应的省份将字符和省份作为标签。
else
{
result = kCharactersNumber; result = kCharactersNumber;
for (int j = kCharactersNumber; j < kCharsTotalNumber; j++) { for (int j = kCharactersNumber; j < kCharsTotalNumber; j++)
{
float val = output_row.at<float>(j); float val = output_row.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
const char* key = kChars[result]; const char *key = kChars[result];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
label = std::make_pair(s, province).second; label = std::make_pair(s, province).second;
} }
/*std::cout << "result:" << result << std::endl; /*std::cout << "result:" << result << std::endl;
std::cout << "maxVal:" << maxVal << std::endl;*/ std::cout << "maxVal:" << maxVal << std::endl;*/
// 函数将预测的最大值和标签分别设置到对应字符对象的得分和字符串属性中。
character.setCharacterScore(maxVal); character.setCharacterScore(maxVal);
character.setCharacterStr(label); character.setCharacterStr(label);
} }
} }
void CharsIdentify::classifyChineseGray(std::vector<CCharacter>& charVec){ // 对输入的中文字符进行分类
void CharsIdentify::classifyChineseGray(std::vector<CCharacter> &charVec)
{
size_t charVecSize = charVec.size(); size_t charVecSize = charVec.size();
if (charVecSize == 0) if (charVecSize == 0)
return; return;
Mat featureRows; Mat featureRows;
for (size_t index = 0; index < charVecSize; index++) { // 通过循环提取每个字符的特征并存储在featureRows中
for (size_t index = 0; index < charVecSize; index++)
{
Mat charInput = charVec[index].getCharacterMat(); Mat charInput = charVec[index].getCharacterMat();
cv::Mat feature; cv::Mat feature;
extractFeature(charInput, feature); extractFeature(charInput, feature);
featureRows.push_back(feature); featureRows.push_back(feature);
} }
// 创建一个输出矩阵output然后使用预先训练好的模型annGray_对特征进行预测并将结果存储在output中
cv::Mat output(charVecSize, kChineseNumber, CV_32FC1); cv::Mat output(charVecSize, kChineseNumber, CV_32FC1);
annGray_->predict(featureRows, output); annGray_->predict(featureRows, output);
for (size_t output_index = 0; output_index < charVecSize; output_index++) { // 对于输出矩阵中的每一行(每个字符的预测结果),
CCharacter& character = charVec[output_index]; // 如果该字符是中文字符,函数会从预测结果的后面部分开始查找最大值,并记录其索引和值。
for (size_t output_index = 0; output_index < charVecSize; output_index++)
{
CCharacter &character = charVec[output_index];
Mat output_row = output.row(output_index); Mat output_row = output.row(output_index);
bool isChinese = true; bool isChinese = true;
float maxVal = -2; float maxVal = -2;
int result = 0; int result = 0;
for (int j = 0; j < kChineseNumber; j++) { for (int j = 0; j < kChineseNumber; j++)
{
float val = output_row.at<float>(j); float val = output_row.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
// no match // no match
if (-1 == result) { if (-1 == result)
{
result = 0; result = 0;
maxVal = 0; maxVal = 0;
isChinese = false; isChinese = false;
} }
// 根据这个最大值和索引确定预测的字符。
// 这是通过查找kChars数组实现的其中kChars可能是一个预定义的字符集。
auto index = result + kCharsTotalNumber - kChineseNumber; auto index = result + kCharsTotalNumber - kChineseNumber;
const char* key = kChars[index]; const char *key = kChars[index];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
/*std::cout << "result:" << result << std::endl; /*std::cout << "result:" << result << std::endl;
std::cout << "maxVal:" << maxVal << std::endl;*/ std::cout << "maxVal:" << maxVal << std::endl;*/
// 将预测的最大值、预测的字符以及对应的省份作为标签,
// 分别设置到对应字符对象的得分、字符串属性和是否为中文字符属性中
character.setCharacterScore(maxVal); character.setCharacterScore(maxVal);
character.setCharacterStr(province); character.setCharacterStr(province);
character.setIsChinese(isChinese); character.setIsChinese(isChinese);
} }
} }
void CharsIdentify::classifyChinese(std::vector<CCharacter>& charVec){ // 使用OpenCV库和神经网络进行中文字符识别
void CharsIdentify::classifyChinese(std::vector<CCharacter> &charVec)
{
size_t charVecSize = charVec.size(); size_t charVecSize = charVec.size();
if (charVecSize == 0) if (charVecSize == 0)
return; return;
Mat featureRows; Mat featureRows;
for (size_t index = 0; index < charVecSize; index++) { // 通过循环遍历每个字符提取其特征并将其存储在featureRows中。
// 这里charFeatures函数被用于提取每个字符的特性kChineseSize可能是一个预定义的特性大小。
for (size_t index = 0; index < charVecSize; index++)
{
Mat charInput = charVec[index].getCharacterMat(); Mat charInput = charVec[index].getCharacterMat();
Mat feature = charFeatures(charInput, kChineseSize); Mat feature = charFeatures(charInput, kChineseSize);
featureRows.push_back(feature); featureRows.push_back(feature);
} }
// 创建一个输出矩阵output并使用预先训练好的模型annChinese_对特征进行预测。预测结果存储在output中。
cv::Mat output(charVecSize, kChineseNumber, CV_32FC1); cv::Mat output(charVecSize, kChineseNumber, CV_32FC1);
annChinese_->predict(featureRows, output); annChinese_->predict(featureRows, output);
for (size_t output_index = 0; output_index < charVecSize; output_index++) { // 遍历每个预测结果,并对每个结果进行处理。对于每个预测结果,函数查找最大值及其索引。
CCharacter& character = charVec[output_index]; // 如果最大值小于或等于-1则将最大值设置为0并将result设置为0同时将isChinese设置为false。
for (size_t output_index = 0; output_index < charVecSize; output_index++)
{
CCharacter &character = charVec[output_index];
Mat output_row = output.row(output_index); Mat output_row = output.row(output_index);
bool isChinese = true; bool isChinese = true;
float maxVal = -2; float maxVal = -2;
int result = 0; int result = 0;
for (int j = 0; j < kChineseNumber; j++) { for (int j = 0; j < kChineseNumber; j++)
{
float val = output_row.at<float>(j); float val = output_row.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
// no match // no match
if (-1 == result) { if (-1 == result)
{
result = 0; result = 0;
maxVal = 0; maxVal = 0;
isChinese = false; isChinese = false;
} }
// 计算索引值并使用该索引从kChars数组中获取对应的字符。
// 同时通过键值对kv_查找与该字符对应的省份。
auto index = result + kCharsTotalNumber - kChineseNumber; auto index = result + kCharsTotalNumber - kChineseNumber;
const char* key = kChars[index]; const char *key = kChars[index];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
/*std::cout << "result:" << result << std::endl; /*std::cout << "result:" << result << std::endl;
std::cout << "maxVal:" << maxVal << std::endl;*/ std::cout << "maxVal:" << maxVal << std::endl;*/
// 将最大值、省份和isChinese作为标签分别设置到对应字符对象的得分、字符串属性和是否为中文字符属性中。
character.setCharacterScore(maxVal); character.setCharacterScore(maxVal);
character.setCharacterStr(province); character.setCharacterStr(province);
character.setIsChinese(isChinese); character.setIsChinese(isChinese);
} }
} }
int CharsIdentify::classify(cv::Mat f, float& maxVal, bool isChinses, bool isAlphabet){ // 对输入的图像数据进行分类
int CharsIdentify::classify(cv::Mat f, float &maxVal, bool isChinses, bool isAlphabet)
{
int result = 0; int result = 0;
// 调用预先训练好的模型ann_进行预测并将预测结果存储在output变量中。
cv::Mat output(1, kCharsTotalNumber, CV_32FC1); cv::Mat output(1, kCharsTotalNumber, CV_32FC1);
ann_->predict(f, output); ann_->predict(f, output);
// 查找最大值及其索引。如果图像数据不是中文,则会检查它是否是字母。
// 如果它是字母那么函数将只查找字母范围内的值从10开始对应于'A')。
// 否则,它将查找所有字符范围内的值。如果图像数据是中文,则函数将查找中文字符范围内的值
maxVal = -2.f; maxVal = -2.f;
if (!isChinses) { if (!isChinses)
if (!isAlphabet) { {
if (!isAlphabet)
{
result = 0; result = 0;
for (int j = 0; j < kCharactersNumber; j++) { for (int j = 0; j < kCharactersNumber; j++)
{
float val = output.at<float>(j); float val = output.at<float>(j);
// std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
} }
else { else
{
result = 0; result = 0;
// begin with 11th char, which is 'A' // begin with 11th char, which is 'A'
for (int j = 10; j < kCharactersNumber; j++) { for (int j = 10; j < kCharactersNumber; j++)
{
float val = output.at<float>(j); float val = output.at<float>(j);
// std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
} }
} }
else { else
{
result = kCharactersNumber; result = kCharactersNumber;
for (int j = kCharactersNumber; j < kCharsTotalNumber; j++) { for (int j = kCharactersNumber; j < kCharsTotalNumber; j++)
{
float val = output.at<float>(j); float val = output.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
} }
//std::cout << "maxVal:" << maxVal << std::endl; // 返回索引值result该值是预测的字符在预先定义的字符集kChars中的索引。
// 同时它也将最大值maxVal和对应的索引result设置到输入的float引用maxVal中以便调用者可以访问这些值。
// std::cout << "maxVal:" << maxVal << std::endl;
return result; return result;
} }
// 根据输入的图像数据判断它是否是一个字符(特别是中文字符)
bool CharsIdentify::isCharacter(cv::Mat input, std::string& label, float& maxVal, bool isChinese) { bool CharsIdentify::isCharacter(cv::Mat input, std::string &label, float &maxVal, bool isChinese)
{
// 调用charFeatures函数提取输入图像的特征并存储在feature变量中。
// 然后它调用classify函数对特征进行分类得到一个索引值index
cv::Mat feature = charFeatures(input, kPredictSize); cv::Mat feature = charFeatures(input, kPredictSize);
auto index = static_cast<int>(classify(feature, maxVal, isChinese)); auto index = static_cast<int>(classify(feature, maxVal, isChinese));
if (isChinese) { if (isChinese)
//std::cout << "maxVal:" << maxVal << std::endl; {
// std::cout << "maxVal:" << maxVal << std::endl;
} }
float chineseMaxThresh = 0.2f; float chineseMaxThresh = 0.2f;
// 检查预测的最大值maxVal是否大于等于0.9或者如果输入的字符是中文且最大值大于等于chineseMaxThresh这个阈值被设置为0.2)。
if (maxVal >= 0.9 || (isChinese && maxVal >= chineseMaxThresh)) { // 如果满足这些条件之一函数将检查索引index是否小于kCharactersNumber这可能是一个预定义的字符集大小
if (index < kCharactersNumber) { // 如果是则将索引对应的字符作为标签否则使用键值对kv_查找索引对应的省份并将该索引对应的字符和省份作为标签。
// 最后函数返回true表示输入的图像是一个字符否则返回false
if (maxVal >= 0.9 || (isChinese && maxVal >= chineseMaxThresh))
{
if (index < kCharactersNumber)
{
label = std::make_pair(kChars[index], kChars[index]).second; label = std::make_pair(kChars[index], kChars[index]).second;
} }
else { else
const char* key = kChars[index]; {
const char *key = kChars[index];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
label = std::make_pair(s, province).second; label = std::make_pair(s, province).second;
@ -337,9 +440,12 @@ bool CharsIdentify::isCharacter(cv::Mat input, std::string& label, float& maxVal
} }
else else
return false; return false;
} }
// 用于识别输入的图像数据是否是一个中文字符。
std::pair<std::string, std::string> CharsIdentify::identifyChinese(cv::Mat input, float& out, bool& isChinese) { std::pair<std::string, std::string> CharsIdentify::identifyChinese(cv::Mat input, float &out, bool &isChinese)
{
// 调用charFeatures函数提取输入图像的特征并存储在feature变量中。
// 然后它调用预先训练好的模型annChinese_进行预测并将预测结果存储在output变量中。
cv::Mat feature = charFeatures(input, kChineseSize); cv::Mat feature = charFeatures(input, kChineseSize);
float maxVal = -2; float maxVal = -2;
int result = 0; int result = 0;
@ -347,87 +453,120 @@ std::pair<std::string, std::string> CharsIdentify::identifyChinese(cv::Mat input
cv::Mat output(1, kChineseNumber, CV_32FC1); cv::Mat output(1, kChineseNumber, CV_32FC1);
annChinese_->predict(feature, output); annChinese_->predict(feature, output);
for (int j = 0; j < kChineseNumber; j++) { // 遍历输出数组,找到最大的值及其索引。
// 如果最大值大于0.9则将isChinese设置为true表示输入的字符可能是中文。
for (int j = 0; j < kChineseNumber; j++)
{
float val = output.at<float>(j); float val = output.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
// no match // no match
if (-1 == result) { // 如果索引值为-1即没有匹配的字符
// 则将result设置为0maxVal设置为0并将isChinese设置为false表示输入的字符不是中文。
if (-1 == result)
{
result = 0; result = 0;
maxVal = 0; maxVal = 0;
isChinese = false; isChinese = false;
} }
else if (maxVal > 0.9){ else if (maxVal > 0.9)
{
isChinese = true; isChinese = true;
} }
// 通过索引值获取字符的标签和省份并将最大值保存到out中。函数返回一个由字符标签和省份组成的pair。
auto index = result + kCharsTotalNumber - kChineseNumber; auto index = result + kCharsTotalNumber - kChineseNumber;
const char* key = kChars[index]; const char *key = kChars[index];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
out = maxVal; out = maxVal;
return std::make_pair(s, province); return std::make_pair(s, province);
} }
// 从输入的图像(可能是一个灰度图像)中识别出可能的中文字符。
std::pair<std::string, std::string> CharsIdentify::identifyChineseGray(cv::Mat input, float& out, bool& isChinese) { std::pair<std::string, std::string> CharsIdentify::identifyChineseGray(cv::Mat input, float &out, bool &isChinese)
{
cv::Mat feature; cv::Mat feature;
// 通过extractFeature函数提取输入图像的特征并将特征保存在feature变量中。
// 然后它使用预先训练好的模型annGray_进行预测并将预测结果存储在output变量中。
extractFeature(input, feature); extractFeature(input, feature);
float maxVal = -2; float maxVal = -2;
int result = 0; int result = 0;
cv::Mat output(1, kChineseNumber, CV_32FC1); cv::Mat output(1, kChineseNumber, CV_32FC1);
annGray_->predict(feature, output); annGray_->predict(feature, output);
// 遍历输出数组,找到最大的值及其索引。
for (int j = 0; j < kChineseNumber; j++) { // 如果最大值大于0.9则将isChinese设置为true表示输入的字符可能是中文。
for (int j = 0; j < kChineseNumber; j++)
{
float val = output.at<float>(j); float val = output.at<float>(j);
//std::cout << "j:" << j << "val:" << val << std::endl; // std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal)
{
maxVal = val; maxVal = val;
result = j; result = j;
} }
} }
// no match // no match
if (-1 == result) { // 如果索引值为-1即没有匹配的字符
// 则将result设置为0maxVal设置为0并将isChinese设置为false表示输入的字符不是中文
if (-1 == result)
{
result = 0; result = 0;
maxVal = 0; maxVal = 0;
isChinese = false; isChinese = false;
} else if (maxVal > 0.9){ }
else if (maxVal > 0.9)
{
isChinese = true; isChinese = true;
} }
// 通过索引值获取字符的标签和省份并将最大值保存到out中。函数返回一个由字符标签和省份组成的pair。
auto index = result + kCharsTotalNumber - kChineseNumber; auto index = result + kCharsTotalNumber - kChineseNumber;
const char* key = kChars[index]; const char *key = kChars[index];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
out = maxVal; out = maxVal;
return std::make_pair(s, province); return std::make_pair(s, province);
} }
std::pair<std::string, std::string> CharsIdentify::identify(cv::Mat input, bool isChinese, bool isAlphabet) { // 用于识别输入的图像数据是否是一个字符。
std::pair<std::string, std::string> CharsIdentify::identify(cv::Mat input, bool isChinese, bool isAlphabet)
{
// 过调用charFeatures函数提取输入图像的特征并存储在feature变量中。
// 然后它调用预先训练好的模型classify进行预测并将预测结果存储在index变量中。
cv::Mat feature = charFeatures(input, kPredictSize); cv::Mat feature = charFeatures(input, kPredictSize);
float maxVal = -2; float maxVal = -2;
auto index = static_cast<int>(classify(feature, maxVal, isChinese, isAlphabet)); auto index = static_cast<int>(classify(feature, maxVal, isChinese, isAlphabet));
if (index < kCharactersNumber) { // 检查索引值index是否小于字符集大小kCharactersNumber。如果是则返回由相同字符组成的pair
// 否则获取索引对应的字符作为键并使用键值对kv_查找对应的省份。
if (index < kCharactersNumber)
{
return std::make_pair(kChars[index], kChars[index]); return std::make_pair(kChars[index], kChars[index]);
} }
else { else
const char* key = kChars[index]; {
const char *key = kChars[index];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
return std::make_pair(s, province); return std::make_pair(s, province);
} }
} }
int CharsIdentify::identify(std::vector<cv::Mat> inputs, std::vector<std::pair<std::string, std::string>>& outputs, // 用于处理一组输入的图像数据并识别出对应的字符和省份。
std::vector<bool> isChineseVec) { // 函数参数包括输入图像数据inputs输出结果outputs以及一个布尔值向量isChineseVec
int CharsIdentify::identify(std::vector<cv::Mat> inputs, std::vector<std::pair<std::string, std::string>> &outputs,
std::vector<bool> isChineseVec)
{
// featureRows创建一个空的Mat对象。它将被用于存储所有输入图像的特征。
Mat featureRows; Mat featureRows;
size_t input_size = inputs.size(); size_t input_size = inputs.size();
for (size_t i = 0; i < input_size; i++) { // 每一张图像提取特征并将这些特征添加到featureRows中。
for (size_t i = 0; i < input_size; i++)
{
Mat input = inputs[i]; Mat input = inputs[i];
cv::Mat feature = charFeatures(input, kPredictSize); cv::Mat feature = charFeatures(input, kPredictSize);
featureRows.push_back(feature); featureRows.push_back(feature);
@ -435,20 +574,28 @@ int CharsIdentify::identify(std::vector<cv::Mat> inputs, std::vector<std::pair<s
std::vector<int> maxIndexs; std::vector<int> maxIndexs;
std::vector<float> maxVals; std::vector<float> maxVals;
// 调用classify函数输入特征矩阵featureRows并返回最大值的索引maxIndexs和最大值maxVals
// 同时根据这些最大值更新isChineseVec中的对应元素。
classify(featureRows, maxIndexs, maxVals, isChineseVec); classify(featureRows, maxIndexs, maxVals, isChineseVec);
// 遍历所有的输入图像对于每一张图像根据其对应的最大值索引构造一个输出对并存储在outputs中。
// 如果索引小于字符集大小kCharactersNumber则输出对由相同字符组成
// 否则获取索引对应的字符作为键并使用键值对kv_查找对应的省份。
for (size_t row_index = 0; row_index < input_size; row_index++) { for (size_t row_index = 0; row_index < input_size; row_index++)
{
int index = maxIndexs[row_index]; int index = maxIndexs[row_index];
if (index < kCharactersNumber) { if (index < kCharactersNumber)
{
outputs[row_index] = std::make_pair(kChars[index], kChars[index]); outputs[row_index] = std::make_pair(kChars[index], kChars[index]);
} }
else { else
const char* key = kChars[index]; {
const char *key = kChars[index];
std::string s = key; std::string s = key;
std::string province = kv_->get(s); std::string province = kv_->get(s);
outputs[row_index] = std::make_pair(s, province); outputs[row_index] = std::make_pair(s, province);
} }
} }
return 0; return 0;
} }
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -6,43 +6,47 @@
#include "easypr/core/params.h" #include "easypr/core/params.h"
namespace easypr { //这部分代码实现了单例模式确保PlateJudge类只有一个实例 namespace easypr { //这部分代码实现了单例模式确保PlateJudge类只有一个实例
//定义了一个静态成员变量instance_它是PlateJudge类的指针初始化为nullptr。这是单例模式的关键所有的PlateJudge实例都将共享这个变量
PlateJudge* PlateJudge::instance_ = nullptr; PlateJudge* PlateJudge::instance_ = nullptr;
PlateJudge* PlateJudge::instance() {
if (!instance_) { //确保PlateJudge类只有一个实例当需要使用PlateJudge类时只需要调用PlateJudge::instance()即可获取到这个唯一的实例
instance_ = new PlateJudge; PlateJudge* PlateJudge::instance() { //定义了一个静态成员函数instance()它返回一个指向PlateJudge实例的指针
if (!instance_) { //检查instance_是否为nullptr
instance_ = new PlateJudge; //如果是那么就创建一个新的PlateJudge实例并将instance_设置为指向这个新创建的实例
} }
return instance_; return instance_; //返回instance_即指向PlateJudge实例的指针
} }
PlateJudge::PlateJudge() { //PlateJudge决定了使用哪种特征提取方法 PlateJudge::PlateJudge() { //PlateJudge决定了使用哪种特征提取方法
bool useLBP = false; bool useLBP = false; //定义一个布尔变量useLBP并初始化为false
if (useLBP) { if (useLBP) { //如果useLBP为true即使用LBP特征提取方法
LOAD_SVM_MODEL(svm_, kLBPSvmPath); LOAD_SVM_MODEL(svm_, kLBPSvmPath); //加载LBP的SVM模型
extractFeature = getLBPFeatures; extractFeature = getLBPFeatures; //设置特征提取函数为getLBPFeatures
} }
else { else { //如果useLBP为false即使用直方图特征提取方法
LOAD_SVM_MODEL(svm_, kHistSvmPath); LOAD_SVM_MODEL(svm_, kHistSvmPath); //加载直方图的SVM模型
extractFeature = getHistomPlusColoFeatures; extractFeature = getHistomPlusColoFeatures; //设置特征提取函数为getHistomPlusColoFeatures
} }
} }
void PlateJudge::LoadModel(std::string path) { //LoadModel函数用于加载SVM模型 void PlateJudge::LoadModel(std::string path) { //LoadModel函数用于加载SVM模型函数接收一个字符串参数path这个参数是SVM模型文件的路径
if (path != std::string(kDefaultSvmPath)) { if (path != std::string(kDefaultSvmPath)) { //检查输入的路径path是否与默认的SVM路径kDefaultSvmPath不同。如果不同那么就需要加载新的SVM模型
if (!svm_->empty()) if (!svm_->empty()) //检查当前的SVM模型是否为空。如果不为空那么在加载新的SVM模型之前需要先清空当前的SVM模型
svm_->clear(); svm_->clear(); //清空当前的SVM模型
LOAD_SVM_MODEL(svm_, path); LOAD_SVM_MODEL(svm_, path); //加载新的SVM模型。LOAD_SVM_MODEL是一个宏它接收两个参数一个是SVM模型的指针另一个是SVM模型文件的路径
} }
} }
// set the score of plate // set the score of plate
// 0 is plate, -1 is not. // 0 is plate, -1 is not.
int PlateJudge::plateSetScore(CPlate& plate) { //plateSetScore函数用于设置车牌的评分 int PlateJudge::plateSetScore(CPlate& plate) { //plateSetScore函数用于设置车牌的评分接收一个CPlate类型的引用作为参数
Mat features; Mat features; //定义一个Mat类型的变量features用于存储特征
extractFeature(plate.getPlateMat(), features); extractFeature(plate.getPlateMat(), features); //调用extractFeature方法提取车牌图像的特征结果存储在features中
float score = svm_->predict(features, noArray(), cv::ml::StatModel::Flags::RAW_OUTPUT); float score = svm_->predict(features, noArray(), cv::ml::StatModel::Flags::RAW_OUTPUT); //使用SVM模型对特征进行预测得到的结果存储在score中
//std::cout << "score:" << score << std::endl; //std::cout << "score:" << score << std::endl;
//这是一个调试用的代码块如果条件为真此处为0所以不会执行则显示车牌图像等待用户按键然后销毁窗口
if (0) { if (0) {
imshow("plate", plate.getPlateMat()); imshow("plate", plate.getPlateMat());
waitKey(0); waitKey(0);
@ -51,14 +55,15 @@ namespace easypr { //这部分代码实现了单例模式确保PlateJudge类
// score is the distance of marginbelow zero is plate, up is not // score is the distance of marginbelow zero is plate, up is not
// when score is below zero, the samll the value, the more possibliy to be a plate. // when score is below zero, the samll the value, the more possibliy to be a plate.
plate.setPlateScore(score); plate.setPlateScore(score);
if (score < 0.5) return 0; if (score < 0.5) return 0; //如果评分小于0.5返回0表示这是一个车牌否则返回-1表示这不是一个车牌
else return -1; else return -1;
} }
//定义了一个名为plateJudge的成员函数它属于PlateJudge类。该函数接收一个Mat类型的常量引用参数plateMat这个参数是需要进行车牌判断的图像
int PlateJudge::plateJudge(const Mat& plateMat) { //plateJudge函数用于判断输入的图像是否为车牌。 int PlateJudge::plateJudge(const Mat& plateMat) { //plateJudge函数用于判断输入的图像是否为车牌。
CPlate plate; CPlate plate; //这行创建了一个CPlate类型的对象plate。CPlate是一个类它可能包含车牌的相关信息如车牌图像、车牌位置等
plate.setPlateMat(plateMat); plate.setPlateMat(plateMat); //调用了CPlate类的setPlateMat成员函数将输入的图像plateMat设置为plate对象的车牌图像
return plateSetScore(plate); return plateSetScore(plate); //调用了PlateJudge类的plateSetScore成员函数对plate对象进行评分然后返回评分结果
} }
int PlateJudge::plateJudge(const std::vector<Mat> &inVec, //inVec是输入的图像向量resultVec是输出的结果向量。 int PlateJudge::plateJudge(const std::vector<Mat> &inVec, //inVec是输入的图像向量resultVec是输出的结果向量。
@ -107,18 +112,25 @@ namespace easypr { //这部分代码实现了单例模式确保PlateJudge类
return 0; //结束循环并返回0表示方法执行成功 return 0; //结束循环并返回0表示方法执行成功
} }
// non-maximum suppression // non-maximum suppression -->非极大值抑制
//函数接收三个参数一个CPlate对象的向量inVec输入的车牌向量一个CPlate对象的向量resultVec输出的车牌向量以及一个double类型的overlap重叠阈值
void NMS(std::vector<CPlate> &inVec, std::vector<CPlate> &resultVec, double overlap) { //NMS函数实现了非极大值抑制用于消除重叠的车牌。 void NMS(std::vector<CPlate> &inVec, std::vector<CPlate> &resultVec, double overlap) { //NMS函数实现了非极大值抑制用于消除重叠的车牌。
std::sort(inVec.begin(), inVec.end()); std::sort(inVec.begin(), inVec.end()); //首先对输入的车牌向量进行排序
//然后遍历输入的车牌向量,对每一个车牌对象,获取其位置的边界矩形
std::vector<CPlate>::iterator it = inVec.begin(); std::vector<CPlate>::iterator it = inVec.begin();
for (; it != inVec.end(); ++it) { for (; it != inVec.end(); ++it) {
CPlate plateSrc = *it; CPlate plateSrc = *it;
//std::cout << "plateScore:" << plateSrc.getPlateScore() << std::endl; //std::cout << "plateScore:" << plateSrc.getPlateScore() << std::endl;
Rect rectSrc = plateSrc.getPlatePos().boundingRect(); Rect rectSrc = plateSrc.getPlatePos().boundingRect();
//在内层循环中,对当前车牌对象之后的每一个车牌对象,也获取其位置的边界矩形
std::vector<CPlate>::iterator itc = it + 1; std::vector<CPlate>::iterator itc = it + 1;
for (; itc != inVec.end();) { for (; itc != inVec.end();) {
CPlate plateComp = *itc; CPlate plateComp = *itc;
Rect rectComp = plateComp.getPlatePos().boundingRect(); Rect rectComp = plateComp.getPlatePos().boundingRect();
//计算两个边界矩形的交并比Intersection over UnionIoU如果IoU大于设定的重叠阈值那么就从输入的车牌向量中删除当前的车牌对象否则继续处理下一个车牌对象
float iou = computeIOU(rectSrc, rectComp); float iou = computeIOU(rectSrc, rectComp);
if (iou > overlap) { if (iou > overlap) {
itc = inVec.erase(itc); itc = inVec.erase(itc);
@ -128,19 +140,23 @@ namespace easypr { //这部分代码实现了单例模式确保PlateJudge类
} }
} }
} }
resultVec = inVec; resultVec = inVec; //最后,将处理后的车牌向量赋值给输出的车牌向量
} }
// judge plate using nms // judge plate using nms --> 使用非极大值抑制进行车牌识别
// 定义了一个名为plateJudgeUsingNMS的成员函数它属于PlateJudge类。该函数使用非极大值抑制进行车牌识别接收一个CPlate对象的向量inVec输入的车牌向量、一个CPlate对象的向量resultVec输出的车牌向量和一个整数maxPlates最大车牌数量作为参数
int PlateJudge::plateJudgeUsingNMS(const std::vector<CPlate> &inVec, std::vector<CPlate> &resultVec, int maxPlates) { //plateJudgeUsingNMS函数使用非极大值抑制进行车牌识别。 int PlateJudge::plateJudgeUsingNMS(const std::vector<CPlate> &inVec, std::vector<CPlate> &resultVec, int maxPlates) { //plateJudgeUsingNMS函数使用非极大值抑制进行车牌识别。
std::vector<CPlate> plateVec; std::vector<CPlate> plateVec; // 创建一个CPlate对象的向量用于存储识别出的车牌
int num = inVec.size(); int num = inVec.size(); // 获取输入向量的大小
bool useCascadeJudge = true; bool useCascadeJudge = true; // 定义一个布尔变量,表示是否使用级联判断
// 遍历输入向量中的每一个元素
for (int j = 0; j < num; j++) { for (int j = 0; j < num; j++) {
CPlate plate = inVec[j]; CPlate plate = inVec[j]; // 获取当前的CPlate对象
Mat inMat = plate.getPlateMat(); Mat inMat = plate.getPlateMat(); // 获取当前CPlate对象的车牌图像
int result = plateSetScore(plate); int result = plateSetScore(plate); // 对当前的CPlate对象进行评分
// 如果评分结果为0表示这是一个车牌
if (0 == result) { if (0 == result) {
if (0) { if (0) {
imshow("inMat", inMat); imshow("inMat", inMat);
@ -148,17 +164,22 @@ namespace easypr { //这部分代码实现了单例模式确保PlateJudge类
destroyWindow("inMat"); destroyWindow("inMat");
} }
if (plate.getPlateLocateType() == CMSER) { if (plate.getPlateLocateType() == CMSER) { // 如果plate的定位类型为CMSER
int w = inMat.cols; int w = inMat.cols; // 获取图像的宽度
int h = inMat.rows; int h = inMat.rows; // 获取图像的高度
// 对图像进行裁剪
Mat tmpmat = inMat(Rect_<double>(w * 0.05, h * 0.1, w * 0.9, h * 0.8)); Mat tmpmat = inMat(Rect_<double>(w * 0.05, h * 0.1, w * 0.9, h * 0.8));
Mat tmpDes = inMat.clone(); Mat tmpDes = inMat.clone(); // 克隆图像
resize(tmpmat, tmpDes, Size(inMat.size())); resize(tmpmat, tmpDes, Size(inMat.size())); // 调整图像大小
plate.setPlateMat(tmpDes); plate.setPlateMat(tmpDes); // 设置plate的车牌图像为调整后的图像
// 如果使用级联判断
if (useCascadeJudge) { if (useCascadeJudge) {
int resultCascade = plateSetScore(plate); int resultCascade = plateSetScore(plate); // 对调整后的图像进行评分
// 如果plate的定位类型不是CMSER将plate的车牌图像设置为原图像
if (plate.getPlateLocateType() != CMSER) if (plate.getPlateLocateType() != CMSER)
plate.setPlateMat(inMat); plate.setPlateMat(inMat);
// 如果级联评分结果为0将plate添加到plateVec中
if (resultCascade == 0) { if (resultCascade == 0) {
if (0) { if (0) {
imshow("tmpDes", tmpDes); imshow("tmpDes", tmpDes);
@ -168,22 +189,24 @@ namespace easypr { //这部分代码实现了单例模式确保PlateJudge类
plateVec.push_back(plate); plateVec.push_back(plate);
} }
} }
else else // 如果不使用级联判断直接将plate添加到plateVec中
plateVec.push_back(plate); plateVec.push_back(plate);
} }
else else // 如果plate的定位类型不是CMSER直接将plate添加到plateVec中
plateVec.push_back(plate); plateVec.push_back(plate);
} }
} }
std::vector<CPlate> reDupPlateVec; std::vector<CPlate> reDupPlateVec; // 创建一个CPlate对象的向量用于存储非极大值抑制后的结果
double overlap = 0.5; double overlap = 0.5; // 定义重叠阈值
// double overlap = CParams::instance()->getParam1f(); // double overlap = CParams::instance()->getParam1f();
// use NMS to get the result plates // use NMS to get the result plates
// 使用非极大值抑制处理plateVec结果存储在reDupPlateVec中
NMS(plateVec, reDupPlateVec, overlap); NMS(plateVec, reDupPlateVec, overlap);
// sort the plates due to their scores // sort the plates due to their scores --> 根据评分对reDupPlateVec进行排序
std::sort(reDupPlateVec.begin(), reDupPlateVec.end()); std::sort(reDupPlateVec.begin(), reDupPlateVec.end());
// output the plate judge plates // output the plate judge plates
// 遍历reDupPlateVec将结果添加到resultVec中直到达到最大车牌数量
std::vector<CPlate>::iterator it = reDupPlateVec.begin(); std::vector<CPlate>::iterator it = reDupPlateVec.begin();
int count = 0; int count = 0;
for (; it != reDupPlateVec.end(); ++it) { for (; it != reDupPlateVec.end(); ++it) {
@ -197,6 +220,6 @@ namespace easypr { //这部分代码实现了单例模式确保PlateJudge类
if (count >= maxPlates) if (count >= maxPlates)
break; break;
} }
return 0; return 0; // 返回0表示函数执行成功
} }
} }

@ -11,14 +11,17 @@ const float DEFAULT_ERROR = 0.9f; // 0.6
const float DEFAULT_ASPECT = 3.75f; // 3.75 const float DEFAULT_ASPECT = 3.75f; // 3.75
CPlateLocate::CPlateLocate() { CPlateLocate::CPlateLocate() {
//CPlateLocate函数用于车牌定位
m_GaussianBlurSize = DEFAULT_GAUSSIANBLUR_SIZE; m_GaussianBlurSize = DEFAULT_GAUSSIANBLUR_SIZE;
m_MorphSizeWidth = DEFAULT_MORPH_SIZE_WIDTH; m_MorphSizeWidth = DEFAULT_MORPH_SIZE_WIDTH;
m_MorphSizeHeight = DEFAULT_MORPH_SIZE_HEIGHT; m_MorphSizeHeight = DEFAULT_MORPH_SIZE_HEIGHT;
//定义了高斯模糊大小、变形宽度、变形高度
m_error = DEFAULT_ERROR; m_error = DEFAULT_ERROR;
m_aspect = DEFAULT_ASPECT; m_aspect = DEFAULT_ASPECT;
//默认错误和方面
m_verifyMin = DEFAULT_VERIFY_MIN; m_verifyMin = DEFAULT_VERIFY_MIN;
m_verifyMax = DEFAULT_VERIFY_MAX; m_verifyMax = DEFAULT_VERIFY_MAX;
//验证最小值与最大值
m_angle = DEFAULT_ANGLE; m_angle = DEFAULT_ANGLE;
@ -26,6 +29,7 @@ CPlateLocate::CPlateLocate() {
} }
void CPlateLocate::setLifemode(bool param) { void CPlateLocate::setLifemode(bool param) {
//若参数param为真设置成员变量为特定值为假则设为初始值
if (param) { if (param) {
setGaussianBlurSize(5); setGaussianBlurSize(5);
setMorphSizeWidth(10); setMorphSizeWidth(10);
@ -46,6 +50,8 @@ void CPlateLocate::setLifemode(bool param) {
} }
bool CPlateLocate::verifySizes(RotatedRect mr) { bool CPlateLocate::verifySizes(RotatedRect mr) {
//验证图像中给定的车牌区域大小是否满足预设的大小限制
//主要是在宽度、高度、面积满足返回true
float error = m_error; float error = m_error;
// Spain car plate size: 52x11 aspect 4,7272 // Spain car plate size: 52x11 aspect 4,7272
// China car plate size: 440mm*140mmaspect 3.142857 // China car plate size: 440mm*140mmaspect 3.142857
@ -64,12 +70,14 @@ bool CPlateLocate::verifySizes(RotatedRect mr) {
float rmax = aspect + aspect * error; float rmax = aspect + aspect * error;
float area = mr.size.height * mr.size.width; float area = mr.size.height * mr.size.width;
//r为宽高比
float r = (float) mr.size.width / (float) mr.size.height; float r = (float) mr.size.width / (float) mr.size.height;
if (r < 1) r = (float) mr.size.height / (float) mr.size.width; if (r < 1) r = (float) mr.size.height / (float) mr.size.width;
// cout << "area:" << area << endl; // cout << "area:" << area << endl;
// cout << "r:" << r << endl; // cout << "r:" << r << endl;
//判断车牌面积是否满足
if ((area < min || area > max) || (r < rmin || r > rmax)) if ((area < min || area > max) || (r < rmin || r > rmax))
return false; return false;
else else
@ -78,29 +86,32 @@ bool CPlateLocate::verifySizes(RotatedRect mr) {
//! mser search method //! mser search method
int CPlateLocate::mserSearch(const Mat &src, vector<Mat> &out, int CPlateLocate::mserSearch(const Mat &src, vector<Mat> &out,
//在输入的图像src中搜索并找到车牌区域
// 并将找到的蓝色和黄色的车牌信息及其旋转矩形框信息和匹配后的灰度图像返回。
vector<vector<CPlate>>& out_plateVec, bool usePlateMser, vector<vector<RotatedRect>>& out_plateRRect, vector<vector<CPlate>>& out_plateVec, bool usePlateMser, vector<vector<RotatedRect>>& out_plateRRect,
int img_index, bool showDebug) { int img_index, bool showDebug) {
vector<Mat> match_grey; vector<Mat> match_grey;
//存储匹配后的灰度图像。
vector<CPlate> plateVec_blue; vector<CPlate> plateVec_blue;
plateVec_blue.reserve(16); plateVec_blue.reserve(16);
vector<RotatedRect> plateRRect_blue; vector<RotatedRect> plateRRect_blue;
plateRRect_blue.reserve(16); plateRRect_blue.reserve(16);
//创建两个向量来存储蓝色的车牌信息和其旋转矩形框信息。
vector<CPlate> plateVec_yellow; vector<CPlate> plateVec_yellow;
plateVec_yellow.reserve(16); plateVec_yellow.reserve(16);
//创建两个向量来存储黄色的车牌信息和其旋转矩形框信息。
vector<RotatedRect> plateRRect_yellow; vector<RotatedRect> plateRRect_yellow;
plateRRect_yellow.reserve(16); plateRRect_yellow.reserve(16);
mserCharMatch(src, match_grey, plateVec_blue, plateVec_yellow, usePlateMser, plateRRect_blue, plateRRect_yellow, img_index, showDebug); mserCharMatch(src, match_grey, plateVec_blue, plateVec_yellow, usePlateMser, plateRRect_blue, plateRRect_yellow, img_index, showDebug);
//调用MSER算法的函数输入源图像和各种参数输出匹配后的灰度图像以及两种颜色的车牌信息和其旋转矩形框信息。
out_plateVec.push_back(plateVec_blue); out_plateVec.push_back(plateVec_blue);
out_plateVec.push_back(plateVec_yellow); out_plateVec.push_back(plateVec_yellow);
//将找到的蓝色和黄色的车牌信息添加到out_plateVec向量中。
out_plateRRect.push_back(plateRRect_blue); out_plateRRect.push_back(plateRRect_blue);
out_plateRRect.push_back(plateRRect_yellow); out_plateRRect.push_back(plateRRect_yellow);
//将找到的蓝色和黄色的车牌的旋转矩形框信息添加到out_plateRRect向量中。
out = match_grey; out = match_grey;
return 0; return 0;
@ -111,21 +122,26 @@ int CPlateLocate::colorSearch(const Mat &src, const Color r, Mat &out,
vector<RotatedRect> &outRects) { vector<RotatedRect> &outRects) {
Mat match_grey; Mat match_grey;
//在输入的图像src中搜索特定颜色r的区域
// 并返回找到的区域RotatedRect的列表
// width is important to the final results; // width is important to the final results;
const int color_morph_width = 10; const int color_morph_width = 10;
const int color_morph_height = 2; const int color_morph_height = 2;
colorMatch(src, match_grey, r, false); colorMatch(src, match_grey, r, false);
//将输入图像·src转换为灰度图像match_grey
SHOW_IMAGE(match_grey, 0); SHOW_IMAGE(match_grey, 0);
Mat src_threshold; Mat src_threshold;
threshold(match_grey, src_threshold, 0, 255, threshold(match_grey, src_threshold, 0, 255,
CV_THRESH_OTSU + CV_THRESH_BINARY); CV_THRESH_OTSU + CV_THRESH_BINARY);
//使用阈值函数threshold对匹配后的图像进行处理
// 将像素值从0到255进行二值化处理
Mat element = getStructuringElement( Mat element = getStructuringElement(
MORPH_RECT, Size(color_morph_width, color_morph_height)); MORPH_RECT, Size(color_morph_width, color_morph_height));
morphologyEx(src_threshold, src_threshold, MORPH_CLOSE, element); morphologyEx(src_threshold, src_threshold, MORPH_CLOSE, element);
//morphologyEx进行形态学闭运算
// 主要用于去除噪声以及填充空洞
//if (m_debug) { //if (m_debug) {
// utils::imwrite("resources/image/tmp/color.jpg", src_threshold); // utils::imwrite("resources/image/tmp/color.jpg", src_threshold);
//} //}
@ -139,10 +155,11 @@ int CPlateLocate::colorSearch(const Mat &src, const Color r, Mat &out,
contours, // a vector of contours contours, // a vector of contours
CV_RETR_EXTERNAL, CV_RETR_EXTERNAL,
CV_CHAIN_APPROX_NONE); // all pixels of each contours CV_CHAIN_APPROX_NONE); // all pixels of each contours
//indContours函数会找到所有外部轮廓即所有的区域都会被找到。
vector<vector<Point>>::iterator itc = contours.begin(); vector<vector<Point>>::iterator itc = contours.begin();
while (itc != contours.end()) { while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc)); RotatedRect mr = minAreaRect(Mat(*itc));
//对找到的每个轮廓执行minAreaRect函数得到该轮廓的最小外接矩形mr
if (!verifySizes(mr)) if (!verifySizes(mr))
itc = contours.erase(itc); itc = contours.erase(itc);
@ -150,6 +167,8 @@ int CPlateLocate::colorSearch(const Mat &src, const Color r, Mat &out,
++itc; ++itc;
outRects.push_back(mr); outRects.push_back(mr);
} }
//最后通过verifySizes函数检查得到的最小外接矩形是否满足预设的条件。
// 如果满足条件则将该矩形添加到outRects列表中如果不满足条件则删除该轮廓
} }
return 0; return 0;
@ -158,11 +177,15 @@ int CPlateLocate::colorSearch(const Mat &src, const Color r, Mat &out,
int CPlateLocate::sobelFrtSearch(const Mat &src, int CPlateLocate::sobelFrtSearch(const Mat &src,
vector<Rect_<float>> &outRects) { vector<Rect_<float>> &outRects) {
//主要功能是在输入的图像src中搜索边缘
// 并返回找到的区域RotatedRect的列表。
Mat src_threshold; Mat src_threshold;
//对输入图像进行边缘检测后的结果。
sobelOper(src, src_threshold, m_GaussianBlurSize, m_MorphSizeWidth, sobelOper(src, src_threshold, m_GaussianBlurSize, m_MorphSizeWidth,
m_MorphSizeHeight); m_MorphSizeHeight);
//调用sobelOper函数对输入图像src进行边缘检测
// 并将结果存储在src_threshold中
//该函数还使用了高斯模糊和形态学操作来增强边缘检测的效果
vector<vector<Point>> contours; vector<vector<Point>> contours;
findContours(src_threshold, findContours(src_threshold,
contours, // a vector of contours contours, // a vector of contours
@ -170,19 +193,22 @@ int CPlateLocate::sobelFrtSearch(const Mat &src,
CV_CHAIN_APPROX_NONE); // all pixels of each contours CV_CHAIN_APPROX_NONE); // all pixels of each contours
vector<vector<Point>>::iterator itc = contours.begin(); vector<vector<Point>>::iterator itc = contours.begin();
//调用findContours函数找到边缘检测后的轮廓。
vector<RotatedRect> first_rects; vector<RotatedRect> first_rects;
while (itc != contours.end()) { while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc)); RotatedRect mr = minAreaRect(Mat(*itc));
//计算其最小外接矩形minAreaRect函数
if (verifySizes(mr)) { if (verifySizes(mr)) {
//检查这个矩形是否满足预设的条件verifySizes函数
// 如果满足条件将这个矩形加入到first_rects列表中
first_rects.push_back(mr); first_rects.push_back(mr);
float area = mr.size.height * mr.size.width; float area = mr.size.height * mr.size.width;
float r = (float) mr.size.width / (float) mr.size.height; float r = (float) mr.size.width / (float) mr.size.height;
if (r < 1) r = (float) mr.size.height / (float) mr.size.width; if (r < 1) r = (float) mr.size.height / (float) mr.size.width;
//计算其面积和宽高比r。如果r小于1则重新计算宽高比。
} }
++itc; ++itc;
@ -193,8 +219,11 @@ int CPlateLocate::sobelFrtSearch(const Mat &src,
Rect_<float> safeBoundRect; Rect_<float> safeBoundRect;
if (!calcSafeRect(roi_rect, src, safeBoundRect)) continue; if (!calcSafeRect(roi_rect, src, safeBoundRect)) continue;
//对于每一个在first_rects中的矩形
// 计算其在原图中的安全边界矩形
//如果计算失败,则跳过当前循环。
outRects.push_back(safeBoundRect); outRects.push_back(safeBoundRect);
//将每个安全边界矩形加入到outRects列表中。
} }
return 0; return 0;
} }
@ -202,20 +231,23 @@ int CPlateLocate::sobelFrtSearch(const Mat &src,
int CPlateLocate::sobelSecSearchPart(Mat &bound, Point2f refpoint, int CPlateLocate::sobelSecSearchPart(Mat &bound, Point2f refpoint,
vector<RotatedRect> &outRects) { vector<RotatedRect> &outRects) {
//功能在输入的图像bound中搜索边缘并返回找到的区域RotatedRect的列表outRects
Mat bound_threshold; Mat bound_threshold;
sobelOperT(bound, bound_threshold, 3, 6, 2); sobelOperT(bound, bound_threshold, 3, 6, 2);
//使用sobelOperT函数进行边缘检测其中3、6、2是sobel算子的大小。
Mat tempBoundThread = bound_threshold.clone(); Mat tempBoundThread = bound_threshold.clone();
clearLiuDingOnly(tempBoundThread); clearLiuDingOnly(tempBoundThread);
int posLeft = 0, posRight = 0; int posLeft = 0, posRight = 0;
if (bFindLeftRightBound(tempBoundThread, posLeft, posRight)) { if (bFindLeftRightBound(tempBoundThread, posLeft, posRight)) {
//使用bFindLeftRightBound函数查找图像的左右边界
// find left and right bounds to repair // find left and right bounds to repair
if (posRight != 0 && posLeft != 0 && posLeft < posRight) { if (posRight != 0 && posLeft != 0 && posLeft < posRight) {
// 如果左边界不为0且右边界不为0且左边界小于右边界
// 则在图像中央位置的左右边界之间填充白色
int posY = int(bound_threshold.rows * 0.5); int posY = int(bound_threshold.rows * 0.5);
for (int i = posLeft + (int) (bound_threshold.rows * 0.1); for (int i = posLeft + (int) (bound_threshold.rows * 0.1);
i < posRight - 4; i++) { i < posRight - 4; i++) {
@ -224,13 +256,16 @@ int CPlateLocate::sobelSecSearchPart(Mat &bound, Point2f refpoint,
} }
utils::imwrite("resources/image/tmp/repaireimg1.jpg", bound_threshold); utils::imwrite("resources/image/tmp/repaireimg1.jpg", bound_threshold);
//保存处理后的图像
// remove the left and right boundaries // remove the left and right boundaries
for (int i = 0; i < bound_threshold.rows; i++) { for (int i = 0; i < bound_threshold.rows; i++)
{
//每个行上将左边界和右边界的像素设置为0。
bound_threshold.data[i * bound_threshold.cols + posLeft] = 0; bound_threshold.data[i * bound_threshold.cols + posLeft] = 0;
bound_threshold.data[i * bound_threshold.cols + posRight] = 0; bound_threshold.data[i * bound_threshold.cols + posRight] = 0;
} }
utils::imwrite("resources/image/tmp/repaireimg2.jpg", bound_threshold); utils::imwrite("resources/image/tmp/repaireimg2.jpg", bound_threshold);
} }
@ -239,23 +274,28 @@ int CPlateLocate::sobelSecSearchPart(Mat &bound, Point2f refpoint,
contours, // a vector of contours contours, // a vector of contours
CV_RETR_EXTERNAL, CV_RETR_EXTERNAL,
CV_CHAIN_APPROX_NONE); // all pixels of each contours CV_CHAIN_APPROX_NONE); // all pixels of each contours
//调用findContours函数找到边缘检测后的轮廓。
vector<vector<Point>>::iterator itc = contours.begin(); vector<vector<Point>>::iterator itc = contours.begin();
vector<RotatedRect> second_rects; vector<RotatedRect> second_rects;
while (itc != contours.end()) { while (itc != contours.end()) {
RotatedRect mr = minAreaRect(Mat(*itc)); RotatedRect mr = minAreaRect(Mat(*itc));
second_rects.push_back(mr); second_rects.push_back(mr);
//对于每个轮廓计算其最小外接矩形minAreaRect函数
//并将结果添加到second_rects列表中。
++itc; ++itc;
} }
for (size_t i = 0; i < second_rects.size(); i++) { for (size_t i = 0; i < second_rects.size(); i++) {
RotatedRect roi = second_rects[i]; RotatedRect roi = second_rects[i];
if (verifySizes(roi)) { if (verifySizes(roi)) {
//对于second_rects中的每个矩形
// 如果满足条件verifySizes函数则计算其中心、大小和角度
Point2f refcenter = roi.center + refpoint; Point2f refcenter = roi.center + refpoint;
Size2f size = roi.size; Size2f size = roi.size;
float angle = roi.angle; float angle = roi.angle;
//创建一个新的RotatedRect对象然后将其添加到outRects列表中。
RotatedRect refroi(refcenter, size, angle); RotatedRect refroi(refcenter, size, angle);
outRects.push_back(refroi); outRects.push_back(refroi);
} }
@ -267,6 +307,8 @@ int CPlateLocate::sobelSecSearchPart(Mat &bound, Point2f refpoint,
int CPlateLocate::sobelSecSearch(Mat &bound, Point2f refpoint, int CPlateLocate::sobelSecSearch(Mat &bound, Point2f refpoint,
vector<RotatedRect> &outRects) { vector<RotatedRect> &outRects) {
//功能在输入的图像bound中搜索边缘并返回找到的区域RotatedRect的列表outRects
//函数内部的函数功能和sobelSecSearch函数差不多
Mat bound_threshold; Mat bound_threshold;
@ -307,19 +349,24 @@ int CPlateLocate::sobelSecSearch(Mat &bound, Point2f refpoint,
int CPlateLocate::sobelOper(const Mat &in, Mat &out, int blurSize, int morphW, int CPlateLocate::sobelOper(const Mat &in, Mat &out, int blurSize, int morphW,
int morphH) { int morphH) {
//功能是对输入图像进行边缘检测,并返回检测到的边缘图像
Mat mat_blur; Mat mat_blur;
mat_blur = in.clone(); mat_blur = in.clone();
GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT); GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT);
//对输入图像in进行高斯模糊处理并将结果存储在mat_blur中
Mat mat_gray; Mat mat_gray;
if (mat_blur.channels() == 3) if (mat_blur.channels() == 3)
cvtColor(mat_blur, mat_gray, CV_RGB2GRAY); cvtColor(mat_blur, mat_gray, CV_RGB2GRAY);
//如果是彩色图,则转换为灰度图像
//否则直接将mat_blur作为灰度图像。
else else
mat_gray = mat_blur; mat_gray = mat_blur;
int scale = SOBEL_SCALE; int scale = SOBEL_SCALE;
int delta = SOBEL_DELTA; int delta = SOBEL_DELTA;
int ddepth = SOBEL_DDEPTH; int ddepth = SOBEL_DDEPTH;
//三个变量分别表示Sobel算子中的尺度、偏差和深度。
Mat grad_x, grad_y; Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y; Mat abs_grad_x, abs_grad_y;
@ -327,30 +374,31 @@ int CPlateLocate::sobelOper(const Mat &in, Mat &out, int blurSize, int morphW,
Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT); Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x); convertScaleAbs(grad_x, abs_grad_x);
//调用Sobel函数对灰度图像进行Sobel算子运算得到梯度图像grad_x。
Mat grad; Mat grad;
addWeighted(abs_grad_x, SOBEL_X_WEIGHT, 0, 0, 0, grad); addWeighted(abs_grad_x, SOBEL_X_WEIGHT, 0, 0, 0, grad);
//将x方向的梯度图像和y方向的梯度图像加权叠加得到最终的梯度图像grad。
Mat mat_threshold; Mat mat_threshold;
double otsu_thresh_val = double otsu_thresh_val =
threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY); threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
//对梯度图像grad进行阈值处理得到二值化图像mat_threshold
Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH)); Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH));
morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element); morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element);
//对二值化图像mat_threshold进行形态学闭运算以填充孔洞和连接断开的边缘
out = mat_threshold; out = mat_threshold;
return 0; return 0;
} }
void deleteNotArea(Mat &inmat, Color color = UNKNOWN) { void deleteNotArea(Mat &inmat, Color color = UNKNOWN) {
//用于删除图像中的非区域部分,并保留特定数据
Mat input_grey; Mat input_grey;
cvtColor(inmat, input_grey, CV_BGR2GRAY); cvtColor(inmat, input_grey, CV_BGR2GRAY);
//将输入图像转换为灰度图像
int w = inmat.cols; int w = inmat.cols;
int h = inmat.rows; int h = inmat.rows;
//从输入图像中截取一个子区域。
Mat tmpMat = inmat(Rect_<double>(w * 0.15, h * 0.1, w * 0.7, h * 0.7)); Mat tmpMat = inmat(Rect_<double>(w * 0.15, h * 0.1, w * 0.7, h * 0.7));
Color plateType; Color plateType;
@ -360,36 +408,42 @@ void deleteNotArea(Mat &inmat, Color color = UNKNOWN) {
else { else {
plateType = color; plateType = color;
} }
//根据输入的颜色参数,确定要保留的颜色类型。
//如果输入颜色为未知UNKNOWN则通过getPlateType函数确定颜色类型。
Mat img_threshold; Mat img_threshold;
if (BLUE == plateType) { if (BLUE == plateType) {
img_threshold = input_grey.clone(); img_threshold = input_grey.clone();
//若车牌是蓝色克隆灰度图像input_grey到img_threshold
Mat tmp = input_grey(Rect_<double>(w * 0.15, h * 0.15, w * 0.7, h * 0.7)); Mat tmp = input_grey(Rect_<double>(w * 0.15, h * 0.15, w * 0.7, h * 0.7));
// 在input_grey中截取中心70%的部分进行阈值分割
int threadHoldV = ThresholdOtsu(tmp); int threadHoldV = ThresholdOtsu(tmp);
threshold(input_grey, img_threshold, threadHoldV, 255, CV_THRESH_BINARY); threshold(input_grey, img_threshold, threadHoldV, 255, CV_THRESH_BINARY);
// threshold(input_grey, img_threshold, 5, 255, CV_THRESH_OTSU + // threshold(input_grey, img_threshold, 5, 255, CV_THRESH_OTSU +
// CV_THRESH_BINARY); // CV_THRESH_BINARY);
// 应用计算出的最佳阈值进行二值化即低于阈值的像素点变为0高于阈值的变为255
utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold); utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold);
//保存二值化处理后的图像
} else if (YELLOW == plateType) {// 如果车牌类型是黄色
} else if (YELLOW == plateType) {
img_threshold = input_grey.clone(); img_threshold = input_grey.clone();
Mat tmp = input_grey(Rect_<double>(w * 0.1, h * 0.1, w * 0.8, h * 0.8)); Mat tmp = input_grey(Rect_<double>(w * 0.1, h * 0.1, w * 0.8, h * 0.8));
// 在input_grey中截取中心80%的部分进行阈值分割
int threadHoldV = ThresholdOtsu(tmp); int threadHoldV = ThresholdOtsu(tmp);
// 使用Otsu方法计算最佳阈值
threshold(input_grey, img_threshold, threadHoldV, 255, threshold(input_grey, img_threshold, threadHoldV, 255,
CV_THRESH_BINARY_INV); CV_THRESH_BINARY_INV);
// 应用计算出的最佳阈值进行反向二值化即高于阈值的像素点变为0低于阈值的变为255
utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold); utils::imwrite("resources/image/tmp/inputgray2.jpg", img_threshold);
// threshold(input_grey, img_threshold, 10, 255, CV_THRESH_OTSU + // threshold(input_grey, img_threshold, 10, 255, CV_THRESH_OTSU +
// CV_THRESH_BINARY_INV); // CV_THRESH_BINARY_INV);
} else } else// 如果既不是蓝色也不是黄色的车牌
threshold(input_grey, img_threshold, 10, 255, threshold(input_grey, img_threshold, 10, 255,
CV_THRESH_OTSU + CV_THRESH_BINARY); CV_THRESH_OTSU + CV_THRESH_BINARY);
// 直接使用固定阈值10进行OTSU二值化处理
//img_threshold = input_grey.clone(); //img_threshold = input_grey.clone();
//spatial_ostu(img_threshold, 8, 2, plateType); //spatial_ostu(img_threshold, 8, 2, plateType);
@ -399,13 +453,13 @@ void deleteNotArea(Mat &inmat, Color color = UNKNOWN) {
int top = 0; int top = 0;
int bottom = img_threshold.rows - 1; int bottom = img_threshold.rows - 1;
clearLiuDing(img_threshold, top, bottom); clearLiuDing(img_threshold, top, bottom);
//清除图像中噪声
if (0) { if (0) { //用于调试使用
imshow("inmat", inmat); imshow("inmat", inmat);
waitKey(0); waitKey(0);
destroyWindow("inmat"); destroyWindow("inmat");
} }
//
if (bFindLeftRightBound1(img_threshold, posLeft, posRight)) { if (bFindLeftRightBound1(img_threshold, posLeft, posRight)) {
inmat = inmat(Rect(posLeft, top, w - posLeft, bottom - top)); inmat = inmat(Rect(posLeft, top, w - posLeft, bottom - top));
if (0) { if (0) {
@ -414,6 +468,7 @@ void deleteNotArea(Mat &inmat, Color color = UNKNOWN) {
destroyWindow("inmat"); destroyWindow("inmat");
} }
} }
// 如果找到了图像的左右边界,则将图像裁剪为这个边界内的部分。
} }
@ -422,20 +477,21 @@ int CPlateLocate::deskew(const Mat &src, const Mat &src_b,
vector<CPlate> &outPlates, bool useDeteleArea, Color color) { vector<CPlate> &outPlates, bool useDeteleArea, Color color) {
Mat mat_debug; Mat mat_debug;
src.copyTo(mat_debug); src.copyTo(mat_debug);
//创建一个新的Mat对象并将源图像复制到这个新对象。
for (size_t i = 0; i < inRects.size(); i++) { for (size_t i = 0; i < inRects.size(); i++) { //遍历输入的旋转句型
RotatedRect roi_rect = inRects[i]; RotatedRect roi_rect = inRects[i];
float r = (float) roi_rect.size.width / (float) roi_rect.size.height; float r = (float) roi_rect.size.width / (float) roi_rect.size.height;
float roi_angle = roi_rect.angle; float roi_angle = roi_rect.angle;//计算旋转矩形的宽高比和角度。
Size roi_rect_size = roi_rect.size; Size roi_rect_size = roi_rect.size;
if (r < 1) { if (r < 1) {
roi_angle = 90 + roi_angle; roi_angle = 90 + roi_angle;
swap(roi_rect_size.width, roi_rect_size.height); swap(roi_rect_size.width, roi_rect_size.height);
} }
//如果宽高比小于1说明矩形是竖直的需要调整角度和宽高。
if (m_debug) { if (m_debug) { //调试模式,绘制旋转矩形的边界
Point2f rect_points[4]; Point2f rect_points[4];
roi_rect.points(rect_points); roi_rect.points(rect_points);
for (int j = 0; j < 4; j++) for (int j = 0; j < 4; j++)
@ -448,14 +504,14 @@ int CPlateLocate::deskew(const Mat &src, const Mat &src_b,
// rotation < m_angel; // rotation < m_angel;
// m_angle=60 // m_angle=60
if (roi_angle - m_angle < 0 && roi_angle + m_angle > 0) { if (roi_angle - m_angle < 0 && roi_angle + m_angle > 0) { //旋转矩形的角度在合理范围时
Rect_<float> safeBoundRect; Rect_<float> safeBoundRect;
bool isFormRect = calcSafeRect(roi_rect, src, safeBoundRect); bool isFormRect = calcSafeRect(roi_rect, src, safeBoundRect); //计算旋转矩形的安全边界。
if (!isFormRect) continue; if (!isFormRect) continue;
Mat bound_mat = src(safeBoundRect); Mat bound_mat = src(safeBoundRect);
Mat bound_mat_b = src_b(safeBoundRect); Mat bound_mat_b = src_b(safeBoundRect);
//根据安全边界,从源图像中截取子图像。
if (0) { if (0) {
imshow("bound_mat_b", bound_mat_b); imshow("bound_mat_b", bound_mat_b);
waitKey(0); waitKey(0);
@ -468,13 +524,16 @@ int CPlateLocate::deskew(const Mat &src, const Mat &src_b,
if ((roi_angle - 5 < 0 && roi_angle + 5 > 0) || 90.0 == roi_angle || if ((roi_angle - 5 < 0 && roi_angle + 5 > 0) || 90.0 == roi_angle ||
-90.0 == roi_angle) { -90.0 == roi_angle) {
deskew_mat = bound_mat; deskew_mat = bound_mat;
} else { //如果矩形角度接近0度或90度直接使用截取的子图像
} else {//倾斜调整
Mat rotated_mat; Mat rotated_mat;
Mat rotated_mat_b; Mat rotated_mat_b;
if (!rotation(bound_mat, rotated_mat, roi_rect_size, roi_ref_center, roi_angle)) if (!rotation(bound_mat, rotated_mat, roi_rect_size, roi_ref_center, roi_angle))
continue; continue;
//对bound_mat应用旋转旋转后存储在rotated_mat中
//若旋转失败,继续下一次循环
if (!rotation(bound_mat_b, rotated_mat_b, roi_rect_size, roi_ref_center, roi_angle)) if (!rotation(bound_mat_b, rotated_mat_b, roi_rect_size, roi_ref_center, roi_angle))
continue; continue;
@ -483,7 +542,9 @@ int CPlateLocate::deskew(const Mat &src, const Mat &src_b,
// imshow("1roated_mat",rotated_mat); // imshow("1roated_mat",rotated_mat);
// imshow("rotated_mat_b",rotated_mat_b); // imshow("rotated_mat_b",rotated_mat_b);
if (isdeflection(rotated_mat_b, roi_angle, roi_slope)) { if (isdeflection(rotated_mat_b, roi_angle, roi_slope)) {
// 检查rotated_mat_b是否需要倾斜调整
affine(rotated_mat, deskew_mat, roi_slope); affine(rotated_mat, deskew_mat, roi_slope);
//应用仿射变换
} else } else
deskew_mat = rotated_mat; deskew_mat = rotated_mat;
} }
@ -494,18 +555,23 @@ int CPlateLocate::deskew(const Mat &src, const Mat &src_b,
// haitungaga addaffect 25% to full recognition. // haitungaga addaffect 25% to full recognition.
if (useDeteleArea) if (useDeteleArea)
deleteNotArea(deskew_mat, color); deleteNotArea(deskew_mat, color);
//用于删除非区域部分
if (deskew_mat.cols * 1.0 / deskew_mat.rows > 2.3 && deskew_mat.cols * 1.0 / deskew_mat.rows < 6) { if (deskew_mat.cols * 1.0 / deskew_mat.rows > 2.3 && deskew_mat.cols * 1.0 / deskew_mat.rows < 6) {
//检查经过校正的图像deskew_mat的长宽比是否在某个范围内
if (deskew_mat.cols >= WIDTH || deskew_mat.rows >= HEIGHT) if (deskew_mat.cols >= WIDTH || deskew_mat.rows >= HEIGHT)
// 如果校正后的图像的宽cols或高rows超出预设的阈值WIDTH或HEIGHT
resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_AREA); resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_AREA);
// 使用INTER_AREA区域插值方法缩小图像保持plate_mat.size()大小
else else
resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_CUBIC); resize(deskew_mat, plate_mat, plate_mat.size(), 0, 0, INTER_CUBIC);
// 如果宽或高没有超出阈值则使用INTER_CUBIC三次插值方法放大图像保持plate_mat.size()大小
CPlate plate; CPlate plate; //存储车牌信息
plate.setPlatePos(roi_rect); plate.setPlatePos(roi_rect);
plate.setPlateMat(plate_mat); plate.setPlateMat(plate_mat);
if (color != UNKNOWN) plate.setPlateColor(color); if (color != UNKNOWN) plate.setPlateColor(color); // 如果车牌颜色已知,则设置车牌颜色
outPlates.push_back(plate); outPlates.push_back(plate); //将包含车牌信息的对象输出
} }
} }
} }
@ -515,7 +581,7 @@ int CPlateLocate::deskew(const Mat &src, const Mat &src_b,
bool CPlateLocate::rotation(Mat &in, Mat &out, const Size rect_size, bool CPlateLocate::rotation(Mat &in, Mat &out, const Size rect_size,
const Point2f center, const double angle) { const Point2f center, const double angle) {
if (0) { if (0) {//通过打印imshow信息调试
imshow("in", in); imshow("in", in);
waitKey(0); waitKey(0);
destroyWindow("in"); destroyWindow("in");
@ -523,33 +589,33 @@ bool CPlateLocate::rotation(Mat &in, Mat &out, const Size rect_size,
Mat in_large; Mat in_large;
in_large.create(int(in.rows * 1.5), int(in.cols * 1.5), in.type()); in_large.create(int(in.rows * 1.5), int(in.cols * 1.5), in.type());
//创建一个1.5倍in图像的行数、1.5倍in图像的列数且同类的图像
float x = in_large.cols / 2 - center.x > 0 ? in_large.cols / 2 - center.x : 0; float x = in_large.cols / 2 - center.x > 0 ? in_large.cols / 2 - center.x : 0;
float y = in_large.rows / 2 - center.y > 0 ? in_large.rows / 2 - center.y : 0; float y = in_large.rows / 2 - center.y > 0 ? in_large.rows / 2 - center.y : 0;
float width = x + in.cols < in_large.cols ? in.cols : in_large.cols - x; float width = x + in.cols < in_large.cols ? in.cols : in_large.cols - x;
float height = y + in.rows < in_large.rows ? in.rows : in_large.rows - y; float height = y + in.rows < in_large.rows ? in.rows : in_large.rows - y;
//计算原始图像 in 在放大图像 in_large 中的位置,确保其居中且不超出 in_large 的边界。
/*assert(width == in.cols); /*assert(width == in.cols);
assert(height == in.rows);*/ assert(height == in.rows);*/
if (width != in.cols || height != in.rows) return false; if (width != in.cols || height != in.rows) return false;
//如果计算得到的宽度和高度与原图 in 不匹配,函数返回 false。
Mat imageRoi = in_large(Rect_<float>(x, y, width, height)); Mat imageRoi = in_large(Rect_<float>(x, y, width, height));//合并原图并放大
addWeighted(imageRoi, 0, in, 1, 0, imageRoi); addWeighted(imageRoi, 0, in, 1, 0, imageRoi);
//选择 in_large 中的一个区域 imageRoi将原图 in 覆盖到这个区域上。
Point2f center_diff(in.cols / 2.f, in.rows / 2.f); Point2f center_diff(in.cols / 2.f, in.rows / 2.f);
Point2f new_center(in_large.cols / 2.f, in_large.rows / 2.f); Point2f new_center(in_large.cols / 2.f, in_large.rows / 2.f);
Mat rot_mat = getRotationMatrix2D(new_center, angle, 1); Mat rot_mat = getRotationMatrix2D(new_center, angle, 1);
//使用 OpenCV 函数 getRotationMatrix2D 生成旋转矩阵 rot_mat。
/*imshow("in_copy", in_large); /*imshow("in_copy", in_large);
waitKey(0);*/ waitKey(0);*/
Mat mat_rotated; Mat mat_rotated;
warpAffine(in_large, mat_rotated, rot_mat, Size(in_large.cols, in_large.rows), warpAffine(in_large, mat_rotated, rot_mat, Size(in_large.cols, in_large.rows),
CV_INTER_CUBIC); CV_INTER_CUBIC);
//使用 warpAffine 函数将旋转矩阵应用于放大后的图像 in_large结果存储在 mat_rotated 中
/*imshow("mat_rotated", mat_rotated); /*imshow("mat_rotated", mat_rotated);
waitKey(0);*/ waitKey(0);*/
@ -558,8 +624,9 @@ bool CPlateLocate::rotation(Mat &in, Mat &out, const Size rect_size,
new_center, img_crop); new_center, img_crop);
out = img_crop; out = img_crop;
//使用 getRectSubPix 函数根据指定的尺寸和中心点从旋转后的图像中裁剪出区域,
if (0) { //结果存储在 img_crop 中,然后赋值给输出参数 out。
if (0) { //调试代码
imshow("out", out); imshow("out", out);
waitKey(0); waitKey(0);
destroyWindow("out"); destroyWindow("out");
@ -574,7 +641,9 @@ bool CPlateLocate::rotation(Mat &in, Mat &out, const Size rect_size,
bool CPlateLocate::isdeflection(const Mat &in, const double angle, bool CPlateLocate::isdeflection(const Mat &in, const double angle,
double &slope) { /*imshow("in",in); double &slope) { /*imshow("in",in);
waitKey(0);*/ waitKey(0);*/
if (0) {
//用于检测输入图像 in 是否有偏转,并计算斜率 slope
if (0) { //用于调试
imshow("in", in); imshow("in", in);
waitKey(0); waitKey(0);
destroyWindow("in"); destroyWindow("in");
@ -584,16 +653,16 @@ bool CPlateLocate::isdeflection(const Mat &in, const double angle,
int nCols = in.cols; int nCols = in.cols;
assert(in.channels() == 1); assert(in.channels() == 1);
//获取图像的行数 nRows 和列数 nCols并确认图像是单通道灰度图
int comp_index[3]; int comp_index[3];
int len[3]; int len[3];
// 分别计算1/4、1/2、3/4高度处的行索引
comp_index[0] = nRows / 4; comp_index[0] = nRows / 4;
comp_index[1] = nRows / 4 * 2; comp_index[1] = nRows / 4 * 2;
comp_index[2] = nRows / 4 * 3; comp_index[2] = nRows / 4 * 3;
const uchar* p; const uchar* p;
// 这个循环会在每个四分位的行上找到第一个非零值的位置
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
int index = comp_index[i]; int index = comp_index[i];
p = in.ptr<uchar>(index); p = in.ptr<uchar>(index);
@ -603,6 +672,7 @@ bool CPlateLocate::isdeflection(const Mat &in, const double angle,
while (0 == value && j < nCols) value = int(p[j++]); while (0 == value && j < nCols) value = int(p[j++]);
len[i] = j; len[i] = j;
} }
// cout << "len[0]:" << len[0] << endl; // cout << "len[0]:" << len[0] << endl;
@ -618,19 +688,15 @@ bool CPlateLocate::isdeflection(const Mat &in, const double angle,
double PI = 3.14159265; double PI = 3.14159265;
double g = tan(angle * PI / 180.0); double g = tan(angle * PI / 180.0);
//检查最长和最短长度是否有显著差异
if (maxlen - len[1] > nCols / 32 || len[1] - minlen > nCols / 32) { if (maxlen - len[1] > nCols / 32 || len[1] - minlen > nCols / 32) {
double slope_can_1 = double slope_can_1 =
double(len[2] - len[0]) / double(comp_index[1]); double(len[2] - len[0]) / double(comp_index[1]);
double slope_can_2 = double(len[1] - len[0]) / double(comp_index[0]); double slope_can_2 = double(len[1] - len[0]) / double(comp_index[0]);
double slope_can_3 = double(len[2] - len[1]) / double(comp_index[0]); double slope_can_3 = double(len[2] - len[1]) / double(comp_index[0]);
// cout<<"angle:"<<angle<<endl;
// cout<<"g:"<<g<<endl; // 选择和输入角度的正切值差异最小的斜率为最终值
// cout << "slope_can_1:" << slope_can_1 << endl;
// cout << "slope_can_2:" << slope_can_2 << endl;
// cout << "slope_can_3:" << slope_can_3 << endl;
// if(g>=0)
slope = abs(slope_can_1 - g) <= abs(slope_can_2 - g) ? slope_can_1 slope = abs(slope_can_1 - g) <= abs(slope_can_2 - g) ? slope_can_1
: slope_can_2; : slope_can_2;
// cout << "slope:" << slope << endl; // cout << "slope:" << slope << endl;
@ -640,21 +706,23 @@ bool CPlateLocate::isdeflection(const Mat &in, const double angle,
} }
return false; return false;
} }
void CPlateLocate::affine(const Mat &in, Mat &out, const double slope) { void CPlateLocate::affine(const Mat &in, Mat &out, const double slope) {
// imshow("in", in);
// waitKey(0);
//对输入图像进行仿射变换,用于矫正车牌图像倾斜
Point2f dstTri[3]; Point2f dstTri[3];
Point2f plTri[3]; Point2f plTri[3];
//输入图像的高度和宽度
float height = (float) in.rows; float height = (float) in.rows;
float width = (float) in.cols; float width = (float) in.cols;
float xiff = (float) abs(slope) * height; float xiff = (float) abs(slope) * height;
if (slope > 0) { if (slope > 0) {
//如果斜率 slope > 0变换将图像向右倾斜。
// right, new position is xiff/2 // right, new position is xiff/2
@ -666,7 +734,7 @@ void CPlateLocate::affine(const Mat &in, Mat &out, const double slope) {
dstTri[1] = Point2f(width - 1 - xiff / 2, 0); dstTri[1] = Point2f(width - 1 - xiff / 2, 0);
dstTri[2] = Point2f(xiff / 2, height - 1); dstTri[2] = Point2f(xiff / 2, height - 1);
} else { } else {
//如果斜率 slope < 0变换将图像向左倾斜。
// left, new position is -xiff/2 // left, new position is -xiff/2
plTri[0] = Point2f(0 + xiff, 0); plTri[0] = Point2f(0 + xiff, 0);
@ -679,15 +747,18 @@ void CPlateLocate::affine(const Mat &in, Mat &out, const double slope) {
} }
Mat warp_mat = getAffineTransform(plTri, dstTri); Mat warp_mat = getAffineTransform(plTri, dstTri);
//使用 OpenCV 的 getAffineTransform 函数,根据源点和目标点计算仿射变换矩阵 warp_mat。
Mat affine_mat; Mat affine_mat;
affine_mat.create((int) height, (int) width, TYPE); affine_mat.create((int) height, (int) width, TYPE);
if (in.rows > HEIGHT || in.cols > WIDTH) if (in.rows > HEIGHT || in.cols > WIDTH)//根据输入图像的大小,选择不同的插值方法:
//如果图像的大小超过预设的 HEIGHT 或 WIDTH使用 CV_INTER_AREA 插值,这个通常用于缩小。
warpAffine(in, affine_mat, warp_mat, affine_mat.size(), warpAffine(in, affine_mat, warp_mat, affine_mat.size(),
CV_INTER_AREA); CV_INTER_AREA);
else else
//否则使用 CV_INTER_CUBIC 插值,这个插值方法在放大时可以提供平滑的边界。
warpAffine(in, affine_mat, warp_mat, affine_mat.size(), CV_INTER_CUBIC); warpAffine(in, affine_mat, warp_mat, affine_mat.size(), CV_INTER_CUBIC);
out = affine_mat; out = affine_mat;
@ -695,18 +766,20 @@ void CPlateLocate::affine(const Mat &in, Mat &out, const double slope) {
int CPlateLocate::plateColorLocate(Mat src, vector<CPlate> &candPlates, int CPlateLocate::plateColorLocate(Mat src, vector<CPlate> &candPlates,
int index) { int index) {
//初始化两个 RotatedRect 类型的向量 rects_color_blue 和 rects_color_yellow以及两个 CPlate 类型的向量 plates_blue 和 plates_yellow
vector<RotatedRect> rects_color_blue; vector<RotatedRect> rects_color_blue;
rects_color_blue.reserve(64); rects_color_blue.reserve(64);
vector<RotatedRect> rects_color_yellow; vector<RotatedRect> rects_color_yellow;
rects_color_yellow.reserve(64); rects_color_yellow.reserve(64);
//这些向量用于存储找到的蓝色和黄色车牌的位置和信息。
vector<CPlate> plates_blue; vector<CPlate> plates_blue;
plates_blue.reserve(64); plates_blue.reserve(64);
vector<CPlate> plates_yellow; vector<CPlate> plates_yellow;
plates_yellow.reserve(64); plates_yellow.reserve(64);
Mat src_clone = src.clone(); Mat src_clone = src.clone();
//使用 OpenMP 并行处理,分别对蓝色和黄色车牌进行搜索和倾斜矫正。
//这是通过调用 colorSearch 和 deskew 函数完成的。
Mat src_b_blue; Mat src_b_blue;
Mat src_b_yellow; Mat src_b_yellow;
#pragma omp parallel sections #pragma omp parallel sections
@ -722,6 +795,7 @@ int CPlateLocate::plateColorLocate(Mat src, vector<CPlate> &candPlates,
deskew(src_clone, src_b_yellow, rects_color_yellow, plates_yellow, true, YELLOW); deskew(src_clone, src_b_yellow, rects_color_yellow, plates_yellow, true, YELLOW);
} }
} }
//将找到的蓝色和黄色车牌信息添加到 candPlates 向量中。
candPlates.insert(candPlates.end(), plates_blue.begin(), plates_blue.end()); candPlates.insert(candPlates.end(), plates_blue.begin(), plates_blue.end());
candPlates.insert(candPlates.end(), plates_yellow.begin(), plates_yellow.end()); candPlates.insert(candPlates.end(), plates_yellow.begin(), plates_yellow.end());
@ -817,10 +891,13 @@ int CPlateLocate::plateMserLocate(Mat src, vector<CPlate> &candPlates, int img_i
int CPlateLocate::sobelOperT(const Mat &in, Mat &out, int blurSize, int morphW, int CPlateLocate::sobelOperT(const Mat &in, Mat &out, int blurSize, int morphW,
int morphH) { int morphH) {
//在输入图像src中使用 MSER最大稳定极值区域方法定位车牌
Mat mat_blur; Mat mat_blur;
mat_blur = in.clone(); mat_blur = in.clone();
GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT); GaussianBlur(in, mat_blur, Size(blurSize, blurSize), 0, 0, BORDER_DEFAULT);
//对输入图像进行高斯模糊,这是为了减少噪声
//将模糊后的图像转换为灰度图像。如果原图像已经是灰度图,则直接使用。
Mat mat_gray; Mat mat_gray;
if (mat_blur.channels() == 3) if (mat_blur.channels() == 3)
cvtColor(mat_blur, mat_gray, CV_BGR2GRAY); cvtColor(mat_blur, mat_gray, CV_BGR2GRAY);
@ -834,24 +911,25 @@ int CPlateLocate::sobelOperT(const Mat &in, Mat &out, int blurSize, int morphW,
int scale = SOBEL_SCALE; int scale = SOBEL_SCALE;
int delta = SOBEL_DELTA; int delta = SOBEL_DELTA;
int ddepth = SOBEL_DDEPTH; int ddepth = SOBEL_DDEPTH;
//对灰度图像应用 Sobel 操作,得到 x 和 y 方向的梯度。
Mat grad_x, grad_y; Mat grad_x, grad_y;
Mat abs_grad_x, abs_grad_y; Mat abs_grad_x, abs_grad_y;
Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT); Sobel(mat_gray, grad_x, ddepth, 1, 0, 3, scale, delta, BORDER_DEFAULT);
convertScaleAbs(grad_x, abs_grad_x); convertScaleAbs(grad_x, abs_grad_x);
//将 x 方向的梯度转换为绝对值,然后与 y 方向的梯度合并(假设 y 方向的梯度为0
Mat grad; Mat grad;
addWeighted(abs_grad_x, 1, 0, 0, 0, grad); addWeighted(abs_grad_x, 1, 0, 0, 0, grad);
utils::imwrite("resources/image/tmp/graygrad.jpg", grad); utils::imwrite("resources/image/tmp/graygrad.jpg", grad);
//使用 Otsu 的阈值法对得到的梯度图像进行二值化
Mat mat_threshold; Mat mat_threshold;
double otsu_thresh_val = double otsu_thresh_val =
threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY); threshold(grad, mat_threshold, 0, 255, CV_THRESH_OTSU + CV_THRESH_BINARY);
utils::imwrite("resources/image/tmp/grayBINARY.jpg", mat_threshold); utils::imwrite("resources/image/tmp/grayBINARY.jpg", mat_threshold);
//对二值化的图像进行形态学闭操作,这有助于连接相邻的区域。
Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH)); Mat element = getStructuringElement(MORPH_RECT, Size(morphW, morphH));
morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element); morphologyEx(mat_threshold, mat_threshold, MORPH_CLOSE, element);
@ -865,6 +943,7 @@ int CPlateLocate::sobelOperT(const Mat &in, Mat &out, int blurSize, int morphW,
int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate> &candPlates, int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate> &candPlates,
int index) { int index) {
vector<RotatedRect> rects_sobel_all; vector<RotatedRect> rects_sobel_all;
//引用传递的 CPlate 类的矢量,用于存储最后识别为候选车牌的结果。
rects_sobel_all.reserve(256); rects_sobel_all.reserve(256);
vector<CPlate> plates; vector<CPlate> plates;
@ -874,11 +953,13 @@ int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate> &candPlates,
bound_rects.reserve(256); bound_rects.reserve(256);
sobelFrtSearch(src, bound_rects); sobelFrtSearch(src, bound_rects);
//使用 Sobel 算子处理输入的图像 src 并返回可能的边界矩形 bound_rects。
vector<Rect_<float>> bound_rects_part; vector<Rect_<float>> bound_rects_part;
bound_rects_part.reserve(256); bound_rects_part.reserve(256);
// enlarge area // enlarge area
//通过扩大每个边界矩形的面积进行进一步处理,这通常是为了使候选区域更大,
//以包含整个车牌。代码通过改变矩形的 x 坐标,宽度,和 y 坐标,高度来实现此目的。
for (size_t i = 0; i < bound_rects.size(); i++) { for (size_t i = 0; i < bound_rects.size(); i++) {
float fRatio = bound_rects[i].width * 1.0f / bound_rects[i].height; float fRatio = bound_rects[i].width * 1.0f / bound_rects[i].height;
if (fRatio < 3.0 && fRatio > 1.0 && bound_rects[i].height < 120) { if (fRatio < 3.0 && fRatio > 1.0 && bound_rects[i].height < 120) {
@ -901,6 +982,8 @@ int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate> &candPlates,
} }
// second processing to split one // second processing to split one
//使用 OpenMP 并行处理进行第二次搜索。pragma omp parallel for 使循环并行执行,
//以加快处理速度。在每次循环中,对于每个边界矩形:
#pragma omp parallel for #pragma omp parallel for
for (int i = 0; i < (int)bound_rects_part.size(); i++) { for (int i = 0; i < (int)bound_rects_part.size(); i++) {
Rect_<float> bound_rect = bound_rects_part[i]; Rect_<float> bound_rect = bound_rects_part[i];
@ -916,12 +999,13 @@ int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate> &candPlates,
Rect_<float> safe_bound_rect(x, y, width, height); Rect_<float> safe_bound_rect(x, y, width, height);
Mat bound_mat = src(safe_bound_rect); Mat bound_mat = src(safe_bound_rect);
//调用 sobelSecSearchPart 函数,它可能进一步处理提取的子图并返回可能的车牌候选区域 rects_sobel
vector<RotatedRect> rects_sobel; vector<RotatedRect> rects_sobel;
rects_sobel.reserve(128); rects_sobel.reserve(128);
sobelSecSearchPart(bound_mat, refpoint, rects_sobel); sobelSecSearchPart(bound_mat, refpoint, rects_sobel);
#pragma omp critical #pragma omp critical
//确保当多个线程尝试将其搜索结果添加到 rects_sobel_all 集合时,不会发生冲突。
{ {
rects_sobel_all.insert(rects_sobel_all.end(), rects_sobel.begin(), rects_sobel.end()); rects_sobel_all.insert(rects_sobel_all.end(), rects_sobel.begin(), rects_sobel.end());
} }
@ -954,13 +1038,15 @@ int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate> &candPlates,
} }
Mat src_b; Mat src_b;
//调用 sobelOper 函数来执行 Sobel 操作。
sobelOper(src, src_b, 3, 10, 3); sobelOper(src, src_b, 3, 10, 3);
//每个可能的矩形区域都发送给 deskew 函数,这个函数可能旨在纠正候选车牌的偏斜。
deskew(src, src_b, rects_sobel_all, plates); deskew(src, src_b, rects_sobel_all, plates);
//for (size_t i = 0; i < plates.size(); i++) //for (size_t i = 0; i < plates.size(); i++)
// candPlates.push_back(plates[i]); // candPlates.push_back(plates[i]);
//得到的车牌从 plates 转移至 candPlates
candPlates.insert(candPlates.end(), plates.begin(), plates.end()); candPlates.insert(candPlates.end(), plates.begin(), plates.end());
return 0; return 0;
@ -968,12 +1054,15 @@ int CPlateLocate::plateSobelLocate(Mat src, vector<CPlate> &candPlates,
int CPlateLocate::plateLocate(Mat src, vector<Mat> &resultVec, int index) { int CPlateLocate::plateLocate(Mat src, vector<Mat> &resultVec, int index) {
//对输入图像src执行车牌定位并将定位到的车牌图像放入resultVec中
vector<CPlate> all_result_Plates; vector<CPlate> all_result_Plates;
//三个函数分别使用颜色定位、Sobel边缘检测和MSER算法来识别车牌
plateColorLocate(src, all_result_Plates, index); plateColorLocate(src, all_result_Plates, index);
plateSobelLocate(src, all_result_Plates, index); plateSobelLocate(src, all_result_Plates, index);
plateMserLocate(src, all_result_Plates, index); plateMserLocate(src, all_result_Plates, index);
//循环通过all_result_Plates对于每个CPlate对象
//调用getPlateMat()获取车牌对应的图像并将其添加到resultVec向量中。
for (size_t i = 0; i < all_result_Plates.size(); i++) { for (size_t i = 0; i < all_result_Plates.size(); i++) {
CPlate plate = all_result_Plates[i]; CPlate plate = all_result_Plates[i];
resultVec.push_back(plate.getPlateMat()); resultVec.push_back(plate.getPlateMat());
@ -983,12 +1072,14 @@ int CPlateLocate::plateLocate(Mat src, vector<Mat> &resultVec, int index) {
} }
int CPlateLocate::plateLocate(Mat src, vector<CPlate> &resultVec, int index) { int CPlateLocate::plateLocate(Mat src, vector<CPlate> &resultVec, int index) {
//对输入图像src执行车牌定位将定位到的车牌对象(CPlate)放入resultVec中
vector<CPlate> all_result_Plates; vector<CPlate> all_result_Plates;
plateColorLocate(src, all_result_Plates, index); plateColorLocate(src, all_result_Plates, index);
plateSobelLocate(src, all_result_Plates, index); plateSobelLocate(src, all_result_Plates, index);
plateMserLocate(src, all_result_Plates, index); plateMserLocate(src, all_result_Plates, index);
//循环通过all_result_Plates将每一个CPlate对象直接添加到resultVec向量中。
for (size_t i = 0; i < all_result_Plates.size(); i++) { for (size_t i = 0; i < all_result_Plates.size(); i++) {
resultVec.push_back(all_result_Plates[i]); resultVec.push_back(all_result_Plates[i]);
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

@ -1,103 +1,129 @@
#include <numeric> #include <numeric>//包含了C++标准库中的<numeric>头文件,提供了数值计算的相关函数和模板。
#include <ctime> #include <ctime>//包含了C++标准库中的<ctime>头文件,提供了关于时间和日期的相关函数和类型。
#include "easypr/train/annCh_train.h" #include "easypr/train/annCh_train.h"//包含了EasyPR库中的annCh_train.h头文件这个头文件可能包含了用于训练ANN人工神经网络字符识别的相关函数和类。
#include "easypr/config.h" #include "easypr/config.h"//包含了EasyPR库的config.h头文件这个头文件可能包含了一些配置EasyPR库的全局变量和宏定义。
#include "easypr/core/chars_identify.h" #include "easypr/core/chars_identify.h"//包含了EasyPR库的chars_identify.h头文件这个头文件可能包含了字符识别的核心功能的声明。
#include "easypr/core/feature.h" #include "easypr/core/feature.h"//包含了EasyPR库的feature.h头文件这个头文件可能包含了特征提取和处理的相关的函数和类。
#include "easypr/core/core_func.h" #include "easypr/core/core_func.h"//包含了EasyPR库的core_func.h头文件这个头文件可能包含了一些核心的函数和类。
#include "easypr/util/util.h" #include "easypr/util/util.h"//包含了EasyPR库的util.h头文件这个头文件可能包含了一些工具函数和类。
#include "easypr/train/create_data.h" #include "easypr/train/create_data.h"//包含了EasyPR库的create_data.h头文件这个头文件可能包含了用于创建训练数据的函数和类。
namespace easypr { namespace easypr { // 定义命名空间easypr
AnnChTrain::AnnChTrain(const char* chars_folder, const char* xml) AnnChTrain::AnnChTrain(const char* chars_folder, const char* xml) // 定义构造函数参数为字符文件夹路径和xml文件路径
: chars_folder_(chars_folder), ann_xml_(xml) : chars_folder_(chars_folder), ann_xml_(xml) // 初始化chars_folder_和ann_xml_成员变量
{ {
ann_ = cv::ml::ANN_MLP::create(); ann_ = cv::ml::ANN_MLP::create(); // 创建一个MLPMultilayer Perceptron多层感知器对象用于字符识别
type = 1; type = 1; // 初始化type为1可能表示某种类型或模式
kv_ = std::shared_ptr<Kv>(new Kv); kv_ = std::shared_ptr<Kv>(new Kv); // 创建一个Kv对象并使用std::shared_ptr管理内存实现共享所有权模型
kv_->load("resources/text/province_mapping"); kv_->load("resources/text/province_mapping"); // 加载kv_对象可能从文件"resources/text/province_mapping"中加载数据
extractFeature = getGrayPlusProject; extractFeature = getGrayPlusProject; // 初始化extractFeature函数指针指向getGrayPlusProject函数用于特征提取
}
void AnnChTrain::train()
{
int classNumber = 0; // 类别数量初始化为0需要在后续代码中赋值
int input_number = 0; // 输入节点数量初始化为0需要在后续代码中赋值
int hidden_number = 0; // 隐藏层节点数量初始化为0需要在后续代码中赋值
int output_number = 0; // 输出节点数量初始化为0需要在后续代码中赋值
bool useLBP = false; // 是否使用LBP特征初始化为false
if (useLBP) // 如果使用LBP特征
input_number = kCharLBPPatterns * kCharLBPGridX * kCharLBPGridY; // 则设置输入节点数量为LBP特征的数量
else
input_number = kGrayCharHeight * kGrayCharWidth; // 否则设置输入节点数量为字符图像的高度和宽度的乘积
input_number += 64; // 在输入节点数量基础上加64可能是为了增加一些额外的输入节点
} }
void AnnChTrain::train() classNumber = kChineseNumber; // 类别数量,这里假设 kChineseNumber 是一个定义好的常量
{ hidden_number = kCharHiddenNeurons; // 隐藏层节点数量,这里假设 kCharHiddenNeurons 是一个定义好的常量
int classNumber = 0; output_number = classNumber; // 输出节点数量,等于类别数量
int input_number = 0; cv::Mat layers; // 声明一个 OpenCV 的 Mat 对象,用于存储网络层的数据,但在这段代码中没有使用
int hidden_number = 0;
int output_number = 0;
bool useLBP = false; int first_hidden_neurons = 48; // 第一隐藏层节点数量硬编码为48
if (useLBP) int second_hidden_neurons = 32; // 第二隐藏层节点数量硬编码为32
input_number = kCharLBPPatterns * kCharLBPGridX * kCharLBPGridY;
else int N = input_number; // 输入节点数量,这里假设 input_number 是一个定义好的变量
input_number = kGrayCharHeight * kGrayCharWidth; int m = output_number; // 输出节点数量,等于类别数量,这里假设 output_number 是一个定义好的变量
input_number += 64; // 在这里注释掉了两行代码,它们原先可能是用于计算第一层和第二层隐藏层的节点数量的公式
//int first_hidden_neurons = int(std::sqrt((m + 2) * N) + 2 * std::sqrt(N / (m + 2)));
//int second_hidden_neurons = int(m * std::sqrt(N / (m + 2)));
classNumber = kChineseNumber; bool useTLFN = false; // 是否使用TLFN初始化为false但在这段代码中没有使用
hidden_number = kCharHiddenNeurans;
output_number = classNumber;
cv::Mat layers;
int first_hidden_neurons = 48; if (!useTLFN) { // 如果不使用两层神经网络TLFN
int second_hidden_neurons = 32; layers.create(1, 3, CV_32SC1); // 创建一个1行3列的OpenCV Mat对象数据类型为32位有符号整数
layers.at<int>(0) = input_number; // 设置输入层节点数量
layers.at<int>(1) = hidden_number; // 设置隐藏层节点数量
layers.at<int>(2) = output_number; // 设置输出层节点数量
}
else { // 如果使用两层神经网络TLFN
fprintf(stdout, ">> Use two-layers neural networks,\n"); // 打印信息到标准输出,表示正在使用两层神经网络
fprintf(stdout, ">> First_hidden_neurons: %d \n", first_hidden_neurons); // 打印第一层隐藏层节点数量到标准输出
fprintf(stdout, ">> Second_hidden_neurons: %d \n", second_hidden_neurons); // 打印第二层隐藏层节点数量到标准输出
layers.create(1, 4, CV_32SC1); // 创建一个1行4列的OpenCV Mat对象数据类型为32位有符号整数
layers.at<int>(0) = input_number; // 设置输入层节点数量
layers.at<int>(1) = first_hidden_neurons; // 设置第一层隐藏层节点数量
layers.at<int>(2) = second_hidden_neurons; // 设置第二层隐藏层节点数量
layers.at<int>(3) = output_number; // 设置输出层节点数量
}
int N = input_number; // 设置神经网络层的大小
int m = output_number; ann_->setLayerSizes(layers);
//int first_hidden_neurons = int(std::sqrt((m + 2) * N) + 2 * std::sqrt(N / (m + 2)));
//int second_hidden_neurons = int(m * std::sqrt(N / (m + 2)));
bool useTLFN = false; // 设置激活函数为Sigmoid函数其对称性取决于第二个参数第三个参数是该函数的斜率
if (!useTLFN) { ann_->setActivationFunction(cv::ml::ANN_MLP::SIGMOID_SYM, 1, 1);
layers.create(1, 3, CV_32SC1);
layers.at<int>(0) = input_number; // 设置训练方法为反向传播法
layers.at<int>(1) = hidden_number; ann_->setTrainMethod(cv::ml::ANN_MLP::TrainingMethods::BACKPROP);
layers.at<int>(2) = output_number;
} // 设置训练终止条件为最大迭代次数30000次或当误差小于0.0001时终止
else { ann_->setTermCriteria(cvTermCriteria(CV_TERMCRIT_ITER, 30000, 0.0001));
fprintf(stdout, ">> Use two-layers neural networks,\n");
fprintf(stdout, ">> First_hidden_neurons: %d \n", first_hidden_neurons);
fprintf(stdout, ">> Second_hidden_neurons: %d \n", second_hidden_neurons);
layers.create(1, 4, CV_32SC1);
layers.at<int>(0) = input_number;
layers.at<int>(1) = first_hidden_neurons;
layers.at<int>(2) = second_hidden_neurons;
layers.at<int>(3) = output_number;
}
ann_->setLayerSizes(layers); // 设置权重的更新比例因子为0.1
ann_->setActivationFunction(cv::ml::ANN_MLP::SIGMOID_SYM, 1, 1); ann_->setBackpropWeightScale(0.1);
ann_->setTrainMethod(cv::ml::ANN_MLP::TrainingMethods::BACKPROP);
ann_->setTermCriteria(cvTermCriteria(CV_TERMCRIT_ITER, 30000, 0.0001));
ann_->setBackpropWeightScale(0.1);
ann_->setBackpropMomentumScale(0.1);
auto files = Utils::getFiles(chars_folder_); // 设置权重的动量更新比例因子为0.1
if (files.size() == 0) { ann_->setBackpropMomentumScale(0.1);
// 获取文件夹中的文件列表,如果文件列表为空,则打印错误信息并给出建议
auto files = Utils::getFiles(chars_folder_);
if (files.size() == 0) {
fprintf(stdout, "No file found in the train folder!\n"); fprintf(stdout, "No file found in the train folder!\n");
fprintf(stdout, "You should create a folder named \"tmp\" in EasyPR main folder.\n"); fprintf(stdout, "You should create a folder named \"tmp\" in EasyPR main folder.\n");
fprintf(stdout, "Copy train data folder(like \"annCh\") under \"tmp\". \n"); fprintf(stdout, "Copy train data folder(like \"annCh\") under \"tmp\". \n");
return; return;
}
// using raw data or raw + synthic data.
trainVal(m_number_for_count);
} }
// 使用原始数据或原始数据 + 合成的数据进行训练和验证,具体数量由 m_number_for_count 决定
trainVal(m_number_for_count);
// 定义一个方法,用于识别汉字
// 参数:输入图像
// 返回值一个由汉字字符串和对应的省份字符串组成的pair
std::pair<std::string, std::string> AnnChTrain::identifyGrayChinese(cv::Mat input) { std::pair<std::string, std::string> AnnChTrain::identifyGrayChinese(cv::Mat input) {
// 定义特征向量
Mat feature; Mat feature;
// 从输入图像中提取特征
extractFeature(input, feature); extractFeature(input, feature);
// 初始化最大值为-2
float maxVal = -2; float maxVal = -2;
// 初始化结果为0
int result = 0; int result = 0;
// 定义输出矩阵大小为1行kChineseNumber列数据类型为CV_32FC132位浮点型
cv::Mat output(1, kChineseNumber, CV_32FC1); cv::Mat output(1, kChineseNumber, CV_32FC1);
// 使用神经网络模型进行预测输入特征向量输出结果到output矩阵中
ann_->predict(feature, output); ann_->predict(feature, output);
// 遍历输出矩阵中的每一个值
for (int j = 0; j < kChineseNumber; j++) { for (int j = 0; j < kChineseNumber; j++) {
// 获取当前位置的值
float val = output.at<float>(j); float val = output.at<float>(j);
// 如果当前值大于maxVal则更新maxVal和result的值
//std::cout << "j:" << j << "val:" << val << std::endl; //std::cout << "j:" << j << "val:" << val << std::endl;
if (val > maxVal) { if (val > maxVal) {
maxVal = val; maxVal = val;
@ -105,83 +131,127 @@ std::pair<std::string, std::string> AnnChTrain::identifyGrayChinese(cv::Mat inpu
} }
} }
// 根据result的值计算索引index注意这里进行了偏移操作可能是因为字符集的索引与输出结果的索引之间存在偏移
auto index = result + kCharsTotalNumber - kChineseNumber; auto index = result + kCharsTotalNumber - kChineseNumber;
// 根据索引获取对应的字符key
const char* key = kChars[index]; const char* key = kChars[index];
// 将字符key转换为字符串s
std::string s = key; std::string s = key;
// 通过kv_应该是某个键值对容器获取与s对应的省份字符串存储到province变量中
std::string province = kv_->get(s); std::string province = kv_->get(s);
// 返回一个由字符s和省份province组成的pair对象
return std::make_pair(s, province); return std::make_pair(s, province);
} }
void AnnChTrain::test() { // 定义一个方法,用于测试模型性能(目前为空)
//TODO void AnnChTrain::test() {
// TODO: 需要实现测试代码,评估模型的性能指标,如准确率、召回率等。
} }
// 定义一个方法,用于训练验证集(目前为空)
void AnnChTrain::trainVal(size_t number_for_count) { void AnnChTrain::trainVal(size_t number_for_count) {
// 断言chars_folder_不为空否则会抛出异常TODO: 需要实现断言失败的处理逻辑)
assert(chars_folder_); assert(chars_folder_);
// 定义训练样本的存储容器train_samplesTODO: 这里需要解释这个变量名和变量的具体含义)
cv::Mat train_samples; cv::Mat train_samples;
// 定义训练图像、验证图像的存储容器TODO: 这里需要解释这些变量名和变量的具体含义)
std::vector<cv::Mat> train_images, val_images; std::vector<cv::Mat> train_images, val_images;
std::vector<int> train_label, val_labels; std::vector<int> train_label, val_labels;
// 设置训练验证集分割比例为0.770%用于训练30%用于验证)
float percentage = 0.7f; float percentage = 0.7f;
int classNumber = kChineseNumber; // 设置类别数为kChineseNumberTODO: 需要解释这个变量的具体含义)直接把代码改成评注形式
for (int i = 0; i < classNumber; ++i) { // 循环遍历每个字符类别
for (int i = 0; i < classNumber; ++i) {
// 从kChars数组中获取当前字符的键
auto char_key = kChars[i + kCharsTotalNumber - classNumber]; auto char_key = kChars[i + kCharsTotalNumber - classNumber];
// 定义一个字符数组sub_folder用于存储子文件夹的路径并初始化为0
char sub_folder[512] = { 0 }; char sub_folder[512] = { 0 };
// 使用sprintf函数将字符键和字符文件夹路径拼接存入sub_folder
sprintf(sub_folder, "%s/%s", chars_folder_, char_key); sprintf(sub_folder, "%s/%s", chars_folder_, char_key);
// 将字符键转化为字符串类型,方便后续操作
std::string test_char(char_key); std::string test_char(char_key);
// 如果test_char不等于"zh_yun",则跳过当前循环
// if (test_char != "zh_yun") continue; // if (test_char != "zh_yun") continue;
fprintf(stdout, ">> Testing characters %s in %s \n", char_key, sub_folder); fprintf(stdout, ">> Testing characters %s in %s \n", char_key, sub_folder);
// 调用utils::getFiles函数获取子文件夹下的所有文件存入chars_files
auto chars_files = utils::getFiles(sub_folder); auto chars_files = utils::getFiles(sub_folder);
// 获取子文件夹下的文件数量
size_t char_size = chars_files.size(); size_t char_size = chars_files.size();
fprintf(stdout, ">> Characters count: %d \n", (int)char_size); fprintf(stdout, ">> Characters count: %d \n", (int)char_size);
// 定义一个向量matVec用于存储处理过的图像
std::vector<cv::Mat> matVec; std::vector<cv::Mat> matVec;
// 为matVec预留空间提高性能
matVec.reserve(number_for_count); matVec.reserve(number_for_count);
// 内层循环,遍历子文件夹下的每一个文件
for (auto file : chars_files) { for (auto file : chars_files) {
std::cout << file << std::endl; std::cout << file << std::endl;
// 使用OpenCV的imread函数读取图像并将其转化为灰度图像
auto img = cv::imread(file, IMREAD_GRAYSCALE); // a grayscale image auto img = cv::imread(file, IMREAD_GRAYSCALE); // a grayscale image
Mat img_resize; Mat img_resize;
// 为img_resize分配空间并设置其大小和数据类型
img_resize.create(kGrayCharHeight, kGrayCharWidth, CV_8UC1); img_resize.create(kGrayCharHeight, kGrayCharWidth, CV_8UC1);
// 使用OpenCV的resize函数调整图像大小
resize(img, img_resize, img_resize.size(), 0, 0, INTER_LINEAR); resize(img, img_resize, img_resize.size(), 0, 0, INTER_LINEAR);
// 将调整大小后的图像存入matVec
matVec.push_back(img_resize); matVec.push_back(img_resize);
} }
// genrate the synthetic images }
for (int t = 0; t < (int)number_for_count - (int)char_size; t++) { // 生成合成图像
// genrate the synthetic images
for (int t = 0; t < (int)number_for_count - (int)char_size; t++) {
// 确定随机数的范围
int rand_range = char_size + t; int rand_range = char_size + t;
// 生成一个随机数
int ran_num = rand() % rand_range; int ran_num = rand() % rand_range;
// 从matVec中获取一个图像
auto img = matVec.at(ran_num); auto img = matVec.at(ran_num);
// 显示该图像
SHOW_IMAGE(img, 0); SHOW_IMAGE(img, 0);
// 生成合成图像
auto simg = generateSyntheticImage(img); auto simg = generateSyntheticImage(img);
// 显示合成图像
SHOW_IMAGE(simg, 0); SHOW_IMAGE(simg, 0);
// 将合成图像添加到matVec中
matVec.push_back(simg); matVec.push_back(simg);
} }
fprintf(stdout, ">> Characters count: %d \n", (int)matVec.size()); // 输出matVec的大小
fprintf(stdout, ">> Characters count: %d \n", (int)matVec.size());
// random sort the mat;
srand(unsigned(time(NULL))); // 对matVec进行随机排序
random_shuffle(matVec.begin(), matVec.end()); // random sort the mat;
srand(unsigned(time(NULL)));
int mat_size = (int)matVec.size(); random_shuffle(matVec.begin(), matVec.end());
int split_index = int((float)mat_size * percentage);
for (int j = mat_size - 1; j >= 0; j--) { // 获取matVec的大小
int mat_size = (int)matVec.size();
// 计算分割索引
int split_index = int((float)mat_size * percentage);
// 从后往前遍历matVec
for (int j = mat_size - 1; j >= 0; j--) {
// 从matVec中获取图像
Mat img = matVec.at(j); Mat img = matVec.at(j);
// 此处代码可能有误,因为该判断语句始终为真,无法起到分割训练集和验证集的作用
// 应该根据split_index来分割训练集和验证集
if (1) { if (1) {
Mat feature; Mat feature;
// 提取图像特征
extractFeature(img, feature); extractFeature(img, feature);
if (j <= split_index) { if (j <= split_index) {
// 将特征和图像添加到训练样本和训练图像中
train_samples.push_back(feature); train_samples.push_back(feature);
train_images.push_back(img); train_images.push_back(img);
train_label.push_back(i); train_label.push_back(i);
} }
else { else {
// 将图像添加到验证图像中,将标签添加到验证标签中
val_images.push_back(img); val_images.push_back(img);
val_labels.push_back(i); val_labels.push_back(i);
} }
} }
} }
}
// generate train data // generate train data
train_samples.convertTo(train_samples, CV_32F); train_samples.convertTo(train_samples, CV_32F);
cv::Mat train_classes = cv::Mat::zeros((int)train_label.size(), classNumber, CV_32F); cv::Mat train_classes = cv::Mat::zeros((int)train_label.size(), classNumber, CV_32F);

@ -18,9 +18,7 @@ SvmTrain::SvmTrain(const char* plates_folder, const char* xml)
extractFeature = getHistomPlusColoFeatures; extractFeature = getHistomPlusColoFeatures;
} }
// 这段代码是SvmTrain类的构造函数接受两个const char*类型的参数plates_folder和xml。
// 在构造函数中使用了assert函数来确保plates_folder和xml不为空。
// 同时将extractFeature设置为getHistomPlusColoFeatures函数。
void SvmTrain::train() { void SvmTrain::train() {
svm_ = cv::ml::SVM::create(); svm_ = cv::ml::SVM::create();
svm_->setType(cv::ml::SVM::C_SVC); svm_->setType(cv::ml::SVM::C_SVC);
@ -33,10 +31,7 @@ void SvmTrain::train() {
svm_->setNu(0.1); svm_->setNu(0.1);
svm_->setP(0.1); svm_->setP(0.1);
svm_->setTermCriteria(cvTermCriteria(CV_TERMCRIT_ITER, 20000, 0.0001)); svm_->setTermCriteria(cvTermCriteria(CV_TERMCRIT_ITER, 20000, 0.0001));
// 这段代码是SvmTrain类的train方法用于训练支持向量机模型。
// 在方法中创建了一个SVM对象并设置了其类型、核函数类型、参数等。
// 最后调用了trainAuto方法进行模型训练并保存了训练好的模型。
// 该方法还包括了一些打印输出和测试方法的调用。
this->prepare(); this->prepare();
if (train_file_list_.size() == 0) { if (train_file_list_.size() == 0) {
@ -46,9 +41,7 @@ void SvmTrain::train() {
return; return;
} }
auto train_data = tdata(); auto train_data = tdata();
// 这段代码是在svm_train.cpp文件中的train方法中的一部分。
// 首先调用了prepare方法然后检查train_file_list_的大小是否为0如果是则输出提示信息并返回。
// 最后调用了tdata方法并将返回值赋给train_data。
fprintf(stdout, ">> Training SVM model, please wait...\n"); fprintf(stdout, ">> Training SVM model, please wait...\n");
long start = utils::getTimestamp(); long start = utils::getTimestamp();
svm_->trainAuto(train_data, 10, SVM::getDefaultGrid(SVM::C), svm_->trainAuto(train_data, 10, SVM::getDefaultGrid(SVM::C),
@ -56,10 +49,7 @@ void SvmTrain::train() {
SVM::getDefaultGrid(SVM::NU), SVM::getDefaultGrid(SVM::COEF), SVM::getDefaultGrid(SVM::NU), SVM::getDefaultGrid(SVM::COEF),
SVM::getDefaultGrid(SVM::DEGREE), true); SVM::getDefaultGrid(SVM::DEGREE), true);
//svm_->train(train_data); //svm_->train(train_data);
// 这段代码是在svm_train.cpp文件中的train方法中的一部分。
// 首先输出训练提示信息,然后获取当前时间戳作为训练开始时间。
// 接着调用svm_->trainAuto方法进行支持向量机模型的自动训练使用了默认的参数网格和并行化。
// 最后注释掉了旧的svm_->train方法的调用。
long end = utils::getTimestamp(); long end = utils::getTimestamp();
fprintf(stdout, ">> Training done. Time elapse: %ldms\n", end - start); fprintf(stdout, ">> Training done. Time elapse: %ldms\n", end - start);
fprintf(stdout, ">> Saving model file...\n"); fprintf(stdout, ">> Saving model file...\n");
@ -71,11 +61,7 @@ void SvmTrain::train() {
this->test(); this->test();
} }
// 这段代码是SvmTrain类中的test方法用于测试支持向量机模型。
// 首先通过utils::getTimestamp()获取当前时间戳作为测试结束时间,并计算训练时间。
// 然后输出训练完成的提示信息并保存训练好的模型到指定的xml文件中。
// 接着输出模型保存的路径,并提示进行测试。
// 最后调用了SvmTrain类中的test方法进行模型测试。
void SvmTrain::test() { void SvmTrain::test() {
// 1.4 bug fix: old 1.4 ver there is no null judge // 1.4 bug fix: old 1.4 ver there is no null judge
// if (NULL == svm_) // if (NULL == svm_)
@ -84,16 +70,13 @@ void SvmTrain::test() {
if (test_file_list_.empty()) { if (test_file_list_.empty()) {
this->prepare(); this->prepare();
} }
// 这段代码是SvmTrain类中的test方法。
// 首先通过LOAD_SVM_MODEL宏加载了svm模型。
// 然后检查test_file_list_是否为空如果为空则调用prepare方法。
double count_all = test_file_list_.size(); double count_all = test_file_list_.size();
double ptrue_rtrue = 0; double ptrue_rtrue = 0;
double ptrue_rfalse = 0; double ptrue_rfalse = 0;
double pfalse_rtrue = 0; double pfalse_rtrue = 0;
double pfalse_rfalse = 0; double pfalse_rfalse = 0;
// 这段代码用于初始化四个double类型的变量分别表示总数、真正例、假反例和假正例。
// 这些变量将在后续的循环中用于统计支持向量机模型的预测结果。
for (auto item : test_file_list_) { for (auto item : test_file_list_) {
auto image = cv::imread(item.file); auto image = cv::imread(item.file);
if (!image.data) { if (!image.data) {
@ -102,10 +85,7 @@ void SvmTrain::test() {
} }
cv::Mat feature; cv::Mat feature;
extractFeature(image, feature); extractFeature(image, feature);
// 这段代码是在SvmTrain类中的test方法中的循环部分。
// 首先遍历test_file_list_中的每个item然后使用OpenCV的imread函数读取图像文件。
// 如果图像数据为空,则输出"no"并继续下一次循环。
// 否则创建一个cv::Mat类型的feature变量并调用extractFeature函数提取图像特征。
auto predict = int(svm_->predict(feature)); auto predict = int(svm_->predict(feature));
//std::cout << "predict: " << predict << std::endl; //std::cout << "predict: " << predict << std::endl;
@ -115,17 +95,13 @@ void SvmTrain::test() {
if (predict == kInverse && real == kForward) pfalse_rtrue++; if (predict == kInverse && real == kForward) pfalse_rtrue++;
if (predict == kInverse && real == kInverse) pfalse_rfalse++; if (predict == kInverse && real == kInverse) pfalse_rfalse++;
} }
// 这段代码用于对图像特征进行预测,并统计预测结果的真正例、假反例、假正例和真反例的数量。
// 首先使用svm_->predict函数对特征进行预测然后根据预测结果和真实标签进行统计。
// 最后根据统计结果计算精确率precise、召回率recall和F分数Fsocre
std::cout << "count_all: " << count_all << std::endl; std::cout << "count_all: " << count_all << std::endl;
std::cout << "ptrue_rtrue: " << ptrue_rtrue << std::endl; std::cout << "ptrue_rtrue: " << ptrue_rtrue << std::endl;
std::cout << "ptrue_rfalse: " << ptrue_rfalse << std::endl; std::cout << "ptrue_rfalse: " << ptrue_rfalse << std::endl;
std::cout << "pfalse_rtrue: " << pfalse_rtrue << std::endl; std::cout << "pfalse_rtrue: " << pfalse_rtrue << std::endl;
std::cout << "pfalse_rfalse: " << pfalse_rfalse << std::endl; std::cout << "pfalse_rfalse: " << pfalse_rfalse << std::endl;
// 评注该代码
// 这段代码用于输出count_all、ptrue_rtrue、ptrue_rfalse、pfalse_rtrue和pfalse_rfalse的值
// 这些值分别表示总数、真正例、假反例、假正例和真反例的数量
double precise = 0; double precise = 0;
if (ptrue_rtrue + ptrue_rfalse != 0) { if (ptrue_rtrue + ptrue_rfalse != 0) {
precise = ptrue_rtrue / (ptrue_rtrue + ptrue_rfalse); precise = ptrue_rtrue / (ptrue_rtrue + ptrue_rfalse);
@ -134,8 +110,7 @@ void SvmTrain::test() {
std::cout << "precise: " std::cout << "precise: "
<< "NA" << std::endl; << "NA" << std::endl;
} }
// 这段代码用于计算精确率precision如果ptrue_rtrue和ptrue_rfalse之和不为0
// 则计算精确率并输出,否则输出"NA"
double recall = 0; double recall = 0;
if (ptrue_rtrue + pfalse_rtrue != 0) { if (ptrue_rtrue + pfalse_rtrue != 0) {
recall = ptrue_rtrue / (ptrue_rtrue + pfalse_rtrue); recall = ptrue_rtrue / (ptrue_rtrue + pfalse_rtrue);
@ -144,8 +119,7 @@ void SvmTrain::test() {
std::cout << "recall: " std::cout << "recall: "
<< "NA" << std::endl; << "NA" << std::endl;
} }
// 这段代码计算并输出召回率recall召回率表示被正确预测为正例的样本数占所有实际正例样本数的比例。
// 如果ptrue_rtrue和pfalse_rtrue之和不为0则计算召回率并输出否则输出"NA"。
double Fsocre = 0; double Fsocre = 0;
if (precise + recall != 0) { if (precise + recall != 0) {
Fsocre = 2 * (precise * recall) / (precise + recall); Fsocre = 2 * (precise * recall) / (precise + recall);
@ -155,9 +129,7 @@ void SvmTrain::test() {
<< "NA" << std::endl; << "NA" << std::endl;
} }
} }
// 评注该代码
// 这段代码用于计算并输出F分数FsocreF分数是精确率precision和召回率recall的调和平均数。
// 首先判断精确率和召回率之和是否为0如果不为0则计算F分数并输出否则输出"NA"。
void SvmTrain::prepare() { void SvmTrain::prepare() {
srand(unsigned(time(NULL))); srand(unsigned(time(NULL)));
@ -178,10 +150,7 @@ void SvmTrain::prepare() {
sprintf(buffer, "%s/no/test", plates_folder_); sprintf(buffer, "%s/no/test", plates_folder_);
auto no_file_test_list = utils::getFiles(buffer); auto no_file_test_list = utils::getFiles(buffer);
std::random_shuffle(no_file_test_list.begin(), no_file_test_list.end()); std::random_shuffle(no_file_test_list.begin(), no_file_test_list.end());
// 该代码是SvmTrain类中的prepare方法用于准备训练和测试数据集。
// 首先使用srand和time函数生成随机种子。
// 然后通过sprintf和utils::getFiles函数获取训练和测试数据集的文件列表并对列表进行随机打乱。
// 最后将获取到的文件列表分别存储到has_file_train_list、has_file_test_list、no_file_train_list和no_file_test_list中。
fprintf(stdout, ">> Collecting train data...\n"); fprintf(stdout, ">> Collecting train data...\n");
for (auto file : has_file_train_list) for (auto file : has_file_train_list)
@ -198,19 +167,11 @@ void SvmTrain::prepare() {
for (auto file : no_file_test_list) for (auto file : no_file_test_list)
test_file_list_.push_back({ file, kInverse }); test_file_list_.push_back({ file, kInverse });
} }
// 该部分代码用于收集训练数据和测试数据。
// 首先输出提示信息"Collecting train data..."然后遍历has_file_train_list和no_file_train_list
// 将文件路径和标签分别添加到train_file_list_中。
// 然后输出提示信息"Collecting test data..."并遍历has_file_test_list和no_file_test_list
// 将文件路径和标签分别添加到test_file_list_中。
cv::Ptr<cv::ml::TrainData> SvmTrain::tdata() { cv::Ptr<cv::ml::TrainData> SvmTrain::tdata() {
cv::Mat samples; cv::Mat samples;
std::vector<int> responses; std::vector<int> responses;
// 这段代码是SvmTrain类中的tdata方法用于准备支持向量机训练数据。
// 首先定义了一个cv::Mat类型的samples和一个std::vector<int>类型的responses。
// 然后遍历train_file_list_中的每个文件使用OpenCV的imread函数读取图像文件提取图像特征并将特征转换为一行的形式。
// 将特征和标签分别添加到samples和responses中。
// 最后将samples和responses转换为CV_32FC1类型的samples_和responses_并使用cv::ml::TrainData::create创建训练数据对象并返回。
for (auto f : train_file_list_) { for (auto f : train_file_list_) {
auto image = cv::imread(f.file); auto image = cv::imread(f.file);
if (!image.data) { if (!image.data) {
@ -224,11 +185,7 @@ cv::Ptr<cv::ml::TrainData> SvmTrain::tdata() {
samples.push_back(feature); samples.push_back(feature);
responses.push_back(int(f.label)); responses.push_back(int(f.label));
} }
// 这段代码是在SvmTrain类中的tdata方法中的循环部分。
// 首先遍历train_file_list_中的每个文件使用OpenCV的imread函数读取图像文件。
// 如果图像数据为空,则输出"Invalid image: 文件路径 ignore."并继续下一次循环。
// 否则创建一个cv::Mat类型的feature变量并调用extractFeature函数提取图像特征。
// 将特征转换为一行的形式然后将特征和标签分别添加到samples和responses中。
cv::Mat samples_, responses_; cv::Mat samples_, responses_;
samples.convertTo(samples_, CV_32FC1); samples.convertTo(samples_, CV_32FC1);
cv::Mat(responses).copyTo(responses_); cv::Mat(responses).copyTo(responses_);
@ -237,6 +194,3 @@ cv::Ptr<cv::ml::TrainData> SvmTrain::tdata() {
} }
} // namespace easypr } // namespace easypr
// 这段代码是在SvmTrain类中的tdata方法中的最后部分。
// 首先将samples转换为CV_32FC1类型的samples_然后将responses复制到responses_中。
// 最后使用cv::ml::TrainData::create创建并返回训练数据对象。

@ -6,4 +6,3 @@ ITrain::ITrain() {}
ITrain::~ITrain() {} ITrain::~ITrain() {}
} }
//这段代码是一个C++文件定义了一个名为ITrain的类包含了一个默认构造函数和一个析构函数。这些函数都位于easypr命名空间中。

@ -1,81 +1,81 @@
#include "easypr/util/kv.h" #include "easypr/util/kv.h" // 引入kv头文件
#include "easypr/util/util.h" #include "easypr/util/util.h" // 引入util头文件
namespace easypr { namespace easypr { // 定义easypr命名空间
Kv::Kv() { } Kv::Kv() { } // Kv类构造函数
void Kv::load(const std::string &file) { void Kv::load(const std::string &file) { // 加载文件
this->clear(); this->clear(); // 清空数据
std::ifstream reader(file); std::ifstream reader(file); // 创建文件读取流
assert(reader); assert(reader); // 断言文件读取流创建成功
if (reader.is_open()) { if (reader.is_open()) { // 如果文件打开成功
while (!reader.eof()) { while (!reader.eof()) { // 当未到达文件末尾时
std::string line; std::string line; // 定义字符串变量line
std::getline(reader, line); std::getline(reader, line); // 读取一行数据到line
if (line.empty()) continue; if (line.empty()) continue; // 如果line为空则跳过本次循环
const auto parse = [](const std::string &str) { const auto parse = [](const std::string &str) { // 定义解析函数
std::string tmp, key, value; std::string tmp, key, value; // 定义临时变量、键、值
for (size_t i = 0, len = str.length(); i < len; ++i) { for (size_t i = 0, len = str.length(); i < len; ++i) { // 遍历字符串
const char ch = str[i]; const char ch = str[i]; // 获取当前字符
if (ch == ' ') { if (ch == ' ') { // 如果当前字符为空格
if (i > 0 && str[i - 1] != ' ' && key.empty()) { if (i > 0 && str[i - 1] != ' ' && key.empty()) { // 如果前一个字符不为空格且键为空
key = tmp; key = tmp; // 将临时变量赋值给键
tmp.clear(); tmp.clear(); // 清空临时变量
} }
} }
else { else {
tmp.push_back(ch); tmp.push_back(ch); // 将当前字符添加到临时变量
} }
if (i == len - 1) { if (i == len - 1) { // 如果当前字符是最后一个字符
value = tmp; value = tmp; // 将临时变量赋值给值
} }
} }
return std::make_pair(key, value); return std::make_pair(key, value); // 返回键值对
}; };
auto kv = parse(line); auto kv = parse(line); // 解析行数据
this->add(kv.first, kv.second); this->add(kv.first, kv.second); // 添加键值对
} }
reader.close(); reader.close(); // 关闭文件读取流
} }
} }
std::string Kv::get(const std::string &key) { std::string Kv::get(const std::string &key) { // 获取键对应的值
if (data_.find(key) == data_.end()) { if (data_.find(key) == data_.end()) { // 如果键不存在
std::cerr << "[Kv] cannot find " << key << std::endl; std::cerr << "[Kv] cannot find " << key << std::endl; // 输出错误信息
return ""; return ""; // 返回空字符串
} }
return data_.at(key); return data_.at(key); // 返回键对应的值
} }
void Kv::add(const std::string &key, const std::string &value) { void Kv::add(const std::string &key, const std::string &value) { // 添加键值对
if (data_.find(key) != data_.end()) { if (data_.find(key) != data_.end()) { // 如果键已存在
fprintf(stderr, fprintf(stderr,
"[Kv] find duplicate: %s = %s , ignore\n", "[Kv] find duplicate: %s = %s , ignore\n",
key.c_str(), key.c_str(),
value.c_str()); value.c_str()); // 输出错误信息
} else { } else {
std::string v(value); std::string v(value);
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
v = utils::utf8_to_gbk(value.c_str()); v = utils::utf8_to_gbk(value.c_str());()); // 如果是Windows系统将值转换为gbk编码
#endif #endif
data_[key] = v; data_[key] = v; // 添加键值对
} }
} }
void Kv::remove(const std::string &key) { void Kv::remove(const std::string &key) { // 删除键值对
if (data_.find(key) == data_.end()) { if (data_.find(key) == data_.end()) { // 如果键不存在
std::cerr << "[Kv] cannot find " << key << std::endl; std::cerr << "[Kv] cannot find " << key << std::endl; // 输出错误信息
return; return; // 返回
} }
data_.erase(key); data_.erase(key); // 删除键值对
} }
void Kv::clear() { void Kv::clear() { // 清空数据
data_.clear(); data_.clear(); // 清空数据
} }
} }

@ -3,423 +3,429 @@
namespace program_options { namespace program_options {
// class ParseError // class ParseError
//定义了一个名为ParseError的类
ParseError::ParseError(const std::string& msg) : _msg(msg) {} //ParseError类是一个用于处理命令行解析错误的异常类。
ParseError::ParseError(const std::string& msg) : _msg(msg) {}//是ParseError类的构造函数
const char* ParseError::what() const throw() { //它接受一个字符串作为参数并将这个字符串赋值给成员变量_msg。
std::string msg; const char* ParseError::what() const throw() {//是一个成员函数,它返回一个描述错误的字符串
msg.append("Command line parse error: ").append(_msg).push_back('.'); std::string msg;//首先创建一个新的字符串
return msg.c_str(); msg.append("Command line parse error: ").append(_msg).push_back('.');//添加一个错误消息前缀接着添加成员变量_msg最后添加一个句点。
return msg.c_str();//返回这个字符串的C风格字符串。
} }
ParseError::~ParseError() throw() {} ParseError::~ParseError() throw() {}// 是ParseError类的析构函数
// class Generator // class Generator
//定义了一个名为Generator的类该类用于生成和管理命令行选项解析器和子程序。
Generator::Generator() : parser_(nullptr) { Generator::Generator() : parser_(nullptr) {//Generator类的构造函数
current_subroutine_ = Subroutine::get_default_name(); current_subroutine_ = Subroutine::get_default_name();//初始化parser_为nullptr设置当前子程序为默认子程序
add_subroutine(current_subroutine_.c_str()); add_subroutine(current_subroutine_.c_str());//添加这个子程序。
} }
Generator::~Generator() { Generator::~Generator() {//Generator类的析构函数
if (parser_) { if (parser_) {
delete parser_; delete parser_;
parser_ = nullptr; parser_ = nullptr;
} }//它删除parser_和所有的子程序
for (auto it = subroutines_.begin(); it != subroutines_.end(); ++it) { for (auto it = subroutines_.begin(); it != subroutines_.end(); ++it) {
if (it->second) { if (it->second) {
delete it->second; delete it->second;//它删除所有的子程序,
it->second = nullptr; it->second = nullptr;//并将parser_和所有的子程序设置为nullptr。
} }
} }
} }
Generator& Generator::make_usage(const char* first_line) { Generator& Generator::make_usage(const char* first_line) {//是一个成员函数
get_subroutine()->set_first_line(first_line); get_subroutine()->set_first_line(first_line);//它设置当前子程序的第一行
return *this; return *this;//并返回this指针。
} }
Parser* Generator::make_parser() { Parser* Generator::make_parser() {//是一个成员函数
if (parser_) delete parser_; if (parser_) delete parser_;
parser_ = new Parser; parser_ = new Parser;//它创建一个新的Parser对象
parser_->set_usage_subroutines(&subroutines_); parser_->set_usage_subroutines(&subroutines_);//设置其使用的子程序
return parser_; return parser_;//并返回这个Parser对象。
} }
Generator& Generator::add_subroutine(const char* name) { Generator& Generator::add_subroutine(const char* name) {//是成员函数
add_subroutine(name, ""); add_subroutine(name, "");//它们添加一个新的子程序。
return *this; return *this;
} }
Generator& Generator::add_subroutine(const char* name, Generator& Generator::add_subroutine(const char* name,
const char* description) { const char* description) {//成员函数
if (subroutines_.find(name) == subroutines_.end()) { if (subroutines_.find(name) == subroutines_.end()) {//如果子程序已经存在,它们不会添加。
// a new subroutine // a new subroutine
current_subroutine_ = name; current_subroutine_ = name;//设立新名字
Subroutine* routine = new Subroutine(name, description); Subroutine* routine = new Subroutine(name, description);//新建一个子程序。
subroutines_.insert({current_subroutine_, routine}); subroutines_.insert({current_subroutine_, routine});//添加一个新的子程序。
} }
return *this; return *this;
} }
std::map<std::string, std::string> Generator::get_subroutine_list() { std::map<std::string, std::string> Generator::get_subroutine_list() {//是一个成员函数,它返回一个包含所有子程序名称和描述的映射。
std::map<std::string, std::string> kv; std::map<std::string, std::string> kv;
for (auto pr : subroutines_) { for (auto pr : subroutines_) {//遍历所有的子程序
Subroutine* subroutine = pr.second; Subroutine* subroutine = pr.second;//遍历所有的子程序
if (subroutine->get_name() != Subroutine::get_default_name()) if (subroutine->get_name() != Subroutine::get_default_name())//如果子程序的名称不是默认名称
kv[subroutine->get_name()] = subroutine->get_description(); kv[subroutine->get_name()] = subroutine->get_description();//将子程序的名称和描述添加到映射中。
} }
return std::move(kv); return std::move(kv);//返回一个包含所有子程序名称和描述的映射
} }
bool Generator::add_usage_line(const char* option, const char* default_value, bool Generator::add_usage_line(const char* option, const char* default_value,
const char* description) { const char* description) {// 是一个成员函数,它添加一个使用行到当前子程序。
std::string option_str(option); std::string option_str(option);
auto delimiter_pos = option_str.find(kDelimiter); auto delimiter_pos = option_str.find(kDelimiter);
//定义新变量,将选项字符串赋给新变量
std::string option_short; std::string option_short;
std::string option_long; std::string option_long;
//将选项字符串分割为短选项和长选项
if (delimiter_pos != std::string::npos) { if (delimiter_pos != std::string::npos) {
option_short.assign(std::move(option_str.substr(0, delimiter_pos))); option_short.assign(std::move(option_str.substr(0, delimiter_pos)));
option_long.assign(std::move(option_str.substr(delimiter_pos + 1))); option_long.assign(std::move(option_str.substr(delimiter_pos + 1)));
Row row; Row row;//创建一个Row对象
row.oshort(option_short); row.oshort(option_short);
row.olong(option_long); row.olong(option_long);
row.value(default_value); row.value(default_value);
row.desc(description); row.desc(description);
////设置其短选项、长选项、默认值和描述
get_subroutine()->add_usage_line(row); get_subroutine()->add_usage_line(row);//将这个Row对象添加到当前子程序的使用行中。
return true; return true;
} }
return false; return false;
} }
std::ostream& operator<<(std::ostream& out, Generator& generator) { std::ostream& operator<<(std::ostream& out, Generator& generator) {// 是一个输出运算符重载函数,它打印所有子程序的名称和描述。
for (auto pr : generator.subroutines_) { for (auto pr : generator.subroutines_) {//遍历所有的子程序
Subroutine* subroutine = pr.second; Subroutine* subroutine = pr.second;
if (subroutine->get_name() != Subroutine::get_default_name()) { if (subroutine->get_name() != Subroutine::get_default_name()) {
out << subroutine->get_name() << "\t"; out << subroutine->get_name() << "\t";
}//如果子程序的名称不是默认名称,就打印子程序的名称
out << subroutine->get_description();//打印子程序的描述
if (!subroutine->get_usage().empty()) {//如果子程序的使用信息不为空,就打印一个换行符
out << std::endl;//打印一个换行符
} }
out << subroutine->get_description(); out << *subroutine;//打印子程序的使用信息。
if (!subroutine->get_usage().empty()) {
out << std::endl;
}
out << *subroutine;
} }
return out; return out;
} }
// class ParseItem // class ParseItem
ParseItem::ParseItem(const std::string& value) : value_(value) {} ParseItem::ParseItem(const std::string& value) : value_(value) {}//ParseItem 类的构造函数
//它接受一个 std::string 类型的参数 value。在构造函数体中将传入的 value 直接赋值给类的成员变量 value_。
//这个构造函数用于创建一个 ParseItem 对象,并初始化其 value_ 成员变量。
// class Parser // class Parser
ParseItem* Parser::get(const std::string& key) { ParseItem* Parser::get(const std::string& key) {//Parser 类的 get 方法,它接受一个 std::string 类型的参数 key。
if (pr_->find(key) != pr_->end()) { if (pr_->find(key) != pr_->end()) {//如果 key 在 pr_ 中存在
return (*pr_)[key]; return (*pr_)[key];//那么返回对应的 ParseItem 指针
} }
return nullptr; return nullptr;//返回 nullptr
} }
Parser::Parser() : subroutines_(nullptr), pr_(nullptr) {} Parser::Parser() : subroutines_(nullptr), pr_(nullptr) {}//
//Parser 类的构造函数,它使用初始化列表将 subroutines_ 和 pr_ 成员变量初始化为 nullptr。
Parser::~Parser() { this->cleanup(); } Parser::~Parser() { this->cleanup(); }
//这是 Parser 类的析构函数,它调用 cleanup 方法来清理资源。
Parser::ParseResult* Parser::parse(const int argc, const char** argv) { Parser::ParseResult* Parser::parse(const int argc, const char** argv) {//Parser 类的 parse 方法,它接受命令行参数的数量 argc 和参数值 argv
if (!this->init(argc, argv)) { if (!this->init(argc, argv)) {//它调用 init 方法来初始化解析过程
return nullptr; return nullptr;//如果初始化失败,那么返回 nullptr
} }
auto ibegin = args_.begin() + 1; // ignore the first cmd name auto ibegin = args_.begin() + 1; // 忽略第一个命令名
auto iend = args_.end(); auto iend = args_.end();
auto it = ibegin; auto it = ibegin;//定义开始变量名
if (argc >= 2 && args_[1][0] != '-') { if (argc >= 2 && args_[1][0] != '-') {
// the second block may be a subroutine name // 第二个块可能是一个子程序名
// e.g., ./exec pull --option // e.g., ./exec pull --option
if (subroutines_ && (subroutines_->find(args_[1]) != subroutines_->end())) { if (subroutines_ && (subroutines_->find(args_[1]) != subroutines_->end())) {
subroutine_name_ = args_[1]; subroutine_name_ = args_[1];
it++; // ignore the subroutine name it++; // 忽略子程序名
} else { } else {
subroutine_name_ = args_[1]; subroutine_name_ = args_[1];
} }
} else { } else {
// there is no options as well as subroutine name // 没有选项以及子程序名
// e.g., ./exec // 例如,./exec
subroutine_name_ = Subroutine::get_default_name(); subroutine_name_ = Subroutine::get_default_name();
} }
std::string block; std::string block;//声明变量
std::string previous(*ibegin); std::string previous(*ibegin);//声明变量
for (; it != iend; ++it) { for (; it != iend; ++it) {// 遍历所有的命令行参数
block.assign(*it); block.assign(*it);// 将当前参数赋值给 block
switch (block.size()) { switch (block.size()) {//// 根据 block 的大小进行不同的处理
case 1: case 1://// 如果 block 的大小为 1
if (block == "-") { if (block == "-") {//// 如果 block 是一个单独的 "-"
throw ParseError("single '-' is not allowed"); throw ParseError("single '-' is not allowed");//// 抛出异常,因为单独的 "-" 是不允许的
} }
break; break;
case 2: case 2:// // 如果 block 的大小为 2
if (block[0] == '-') { if (block[0] == '-') {//// 如果 block 的第一个字符是 "-"
if (block[1] == '-') { if (block[1] == '-') {//// 如果 block 的第二个字符也是 "-"
throw ParseError("option '--' is incomplete"); throw ParseError("option '--' is incomplete");//// 抛出异常,因为 "--" 是不完整的选项
} else if (block[1] == '=') {
throw ParseError("option '-=' is invalid"); } else if (block[1] == '=') {//// 如果 block 的第二个字符是 "="
throw ParseError("option '-=' is invalid");//// 抛出异常,因为 "-=" 是无效的选项
} else { } else {
// single option // 单个选项
// e.g., ./exec -s // e.g., ./exec -s
(*pr_)[block.substr(1)] = nullptr; (*pr_)[block.substr(1)] = nullptr;
} }
} }
break; break;
default: // >=3 default: // >=3
if (block[0] == '-') { if (block[0] == '-') {//// 如果 block 的第一个字符是 "-"
if (block[1] == '-') { if (block[1] == '-') {//// 如果 block 的第二个字符也是 "-"
size_t pos_equal = block.find('='); size_t pos_equal = block.find('=');//// 查找 "=" 在 block 中的位置
if (pos_equal == std::string::npos) { if (pos_equal == std::string::npos) {//// 如果没有找到 "="
// a long format option // 长格式选项
// e.g., ./exec --option // e.g., ./exec --option
(*pr_)[block.substr(2)] = nullptr; (*pr_)[block.substr(2)] = nullptr;//// 将选项添加到 pr_ 中,值为 nullptr
} else { } else {
if (pos_equal > 3) { if (pos_equal > 3) {// 如果 "=" 的位置大于 3
// e.g, ./exec --op[..=]value // e.g, ./exec --op[..=]value
std::string key(block.substr(2, pos_equal - 2)); std::string key(block.substr(2, pos_equal - 2));// 获取选项名
if (block.size() > 5) if (block.size() > 5)//// 如果 block 的大小大于 5
// e.g, ./exec --op=v // e.g, ./exec --op=v
(*pr_)[key] = new ParseItem(block.substr(pos_equal + 1)); (*pr_)[key] = new ParseItem(block.substr(pos_equal + 1));// 将选项和值添加到 pr_ 中
else else
(*pr_)[key] = nullptr; (*pr_)[key] = nullptr;// 将选项添加到 pr_ 中,值为 nullptr
} else { } else {
// a long format option but = is illegal // 长格式选项但 = 是非法的
// e.g., ./exec --o=[...] // e.g., ./exec --o=[...]
(*pr_)[block.substr(2)] = nullptr; (*pr_)[block.substr(2)] = nullptr;//// 将选项添加到 pr_ 中,值为 nullptr
} }
} }
} else if (block[2] == '=') { } else if (block[2] == '=') {// // 如果 block 的第三个字符是 "="
// a single option with = // 单个选项带有 =
// e.g., ./exec -o=[...] // e.g., ./exec -o=[...]
std::string key; std::string key;
key.push_back(block[1]); key.push_back(block[1]);// 获取选项名
if (block.size() > 3) if (block.size() > 3)// 如果 block 的大小大于 3
(*pr_)[key] = new ParseItem(block.substr(3)); (*pr_)[key] = new ParseItem(block.substr(3));//// 将选项和值添加到 pr_ 中
else else
(*pr_)[key] = nullptr; (*pr_)[key] = nullptr;// 将选项添加到 pr_ 中,值为 nullptr
} else { } else {
// a combination options // 组合选项
// e.g., ./exec -ab[...] // e.g., ./exec -ab[...]
auto tbegin = block.begin() + 1; // ignore the first '-' auto tbegin = block.begin() + 1; // 忽略第一个 '-'
auto tend = block.end(); auto tend = block.end();
auto t = tbegin; auto t = tbegin;
for (; t != tend; ++t) { for (; t != tend; ++t) { // 遍历 block 中的每个字符
std::string key; std::string key;
key.push_back(*t); key.push_back(*t);// // 获取选项名
(*pr_)[key] = nullptr; (*pr_)[key] = nullptr; // 将选项添加到 pr_ 中,值为 nullptr
} }
} }
} }
break; break;
} // switch } // switch
if (block[0] != '-' && previous != block // not the first option if (block[0] != '-' && previous != block // 如果 block 不是选项(不以 "-" 开头)并且不是第一个选项
) { ) {
if (previous[0] != '-') { if (previous[0] != '-') {//// 如果 previous 不是选项
// previous is not an option, error occur // previous 不是一个选项,发生错误
// e.g., ./exec abc def // e.g., ./exec abc def
throw ParseError("'" + block + "' is not allowed here"); throw ParseError("'" + block + "' is not allowed here");//抛出异常,因为在这里不允许非选项
} }
std::string key; std::string key;
if (previous[0] == '-' && previous[1] == '-') { if (previous[0] == '-' && previous[1] == '-') {//// 如果 previous 是一个长格式选项
// previous is a long format option. // previous is a long format option.
// e.g., ./exec --option value // e.g., ./exec --option value
key = previous.substr(2); key = previous.substr(2);//// 获取选项名
} else { } else {
// it's the value of previous option. // 它是前一个选项的值。
// e.g., ./exec -o [...] // e.g., ./exec -o [...]
// e.g., ./exec -opq [...] // e.g., ./exec -opq [...]
key.push_back(*(previous.end() - 1)); key.push_back(*(previous.end() - 1));// // 获取选项名
} }
if (pr_->find(key) != pr_->end()) { if (pr_->find(key) != pr_->end()) {//// 如果选项在 pr_ 中存在
(*pr_)[key] = new ParseItem(block); (*pr_)[key] = new ParseItem(block); // 将选项和值添加到 pr_ 中
} }
} }
previous = block; previous = block;//// 更新 previous 为当前的 block
} // for } // for
if (subroutines_) { if (subroutines_) {
this->set_addition(); this->set_addition();// 如果存在子程序,调用 set_addition 方法处理额外的选项
} }
return pr_; return pr_;//返回解析结果 pr_
} }
Parser::ParseResult* Parser::parse(const char* command_line) { Parser::ParseResult* Parser::parse(const char* command_line) {//Parser 类的 parse 方法
int i = 0; int i = 0;//初始化计数器
std::string block; std::string block;//用于存储单个命令行参数
std::vector<std::string> blocks; std::vector<std::string> blocks;//声明用于存储所有命令行参数
char c; char c;//声明用于存储当前字符
while ((c = command_line[i++]) != '\0') { while ((c = command_line[i++]) != '\0') {// 遍历命令行字符串
if (c != ' ') { if (c != ' ') {// 如果当前字符不是空格
block.push_back(c); block.push_back(c);//// 将当前字符添加到 block
} else { } else {
if (!block.empty()) { if (!block.empty()) {// 如果 block 不为空
blocks.push_back(block); blocks.push_back(block);// 将 block 添加到 blocks
} }
block.clear(); block.clear();//清空 block
} }
} }
if (!block.empty()) { if (!block.empty()) {// 如果最后一个 block 不为空
blocks.push_back(block); blocks.push_back(block);// 将 block 添加到 blocks
} }
size_t size = blocks.size(); // argc size_t size = blocks.size(); // argc
char** argv = new char*[size]; char** argv = new char*[size];// 创建一个新的 char* 数组
i = 0; i = 0;
std::for_each(blocks.begin(), blocks.end(), [argv, &i](const std::string& b) { std::for_each(blocks.begin(), blocks.end(), [argv, &i](const std::string& b) {// 遍历 blocks
argv[i++] = const_cast<char*>(b.c_str()); argv[i++] = const_cast<char*>(b.c_str());// 将每个 block 转换为 char* 并存储在 argv 中
}); });
auto pr = auto pr =
this->parse(static_cast<const int>(size), const_cast<const char**>(argv)); this->parse(static_cast<const int>(size), const_cast<const char**>(argv)); // 调用 parse 方法解析命令行参数
delete[] argv; delete[] argv;// 删除 argv
argv = nullptr; argv = nullptr;
return pr; return pr;// 返回解析结果
} }
bool Parser::has(const char* key) { bool Parser::has(const char* key) {//Parser 类的 has 方法,它接受一个 char 指针 key并检查 key 是否在 pr_ 中存在。
std::string skey(key); std::string skey(key);// 将 key 转换为 std::string
if (pr_ && !pr_->empty() && !skey.empty()) { if (pr_ && !pr_->empty() && !skey.empty()) {//判断是否存在
if (skey[0] == '-') { if (skey[0] == '-') {
// check combination options, e.g., Parser::has("-xyz") // 如果 skey 是一个组合选项,例如 "-xyz"
for (size_t i = 1; i < skey.size(); ++i) { for (size_t i = 1; i < skey.size(); ++i) {// 遍历 skey 的每个字符
std::string tkey; std::string tkey;
tkey.push_back(skey[i]); tkey.push_back(skey[i]);// 获取选项名
if (pr_->find(tkey) == pr_->end()) { if (pr_->find(tkey) == pr_->end()) { // 如果选项名在 pr_ 中不存在
return false; return false;
} }
} }
return true; return true;
} else { } else {
// check single option, e.g., Parser::has("x") // 如果 skey 是一个单个选项,例如 "x"
return pr_->find(skey) != pr_->end(); return pr_->find(skey) != pr_->end();// 检查选项是否在 pr_ 中存在
} }
} }
return false; return false;// 如果 pr_ 为空或 skey 为空,返回 false
} }
//parser 类的 has_or 方法,它接受一个初始化列表 options并检查 options 中的任何一个 key 是否在 pr_ 中存在。
bool Parser::has_or(std::initializer_list<const char*> options) { bool Parser::has_or(std::initializer_list<const char*> options) {
if (options.size() == 0) { if (options.size() == 0) {// 如果 options 为空
return false; return false;
}4
for (auto key : options) {// 遍历 options 中的每个选项
if (this->has(key)) return true;// 如果选项在 pr_ 中存在,返回 true
} }
for (auto key : options) { return false;// 如果 options 中的所有选项都不存在,返回 false
if (this->has(key)) return true;
}
return false;
} }
bool Parser::has_and(std::initializer_list<const char*> options) { bool Parser::has_and(std::initializer_list<const char*> options) { // Parser 类的 has_and 方法,接受一个初始化列表 options
if (options.size() == 0) { if (options.size() == 0) {// 如果 options 为空
return false; return false;
} }
for (auto key : options) { for (auto key : options) {// 遍历 options 中的每个选项
if (!this->has(key)) return false; if (!this->has(key)) return false;// 如果选项在 pr_ 中不存在,返回 false
} }
return true; return true;// 如果 options 中的所有选项都存在,返回 true
} }
bool Parser::init(const int argc, const char** argv) { bool Parser::init(const int argc, const char** argv) {
argc_ = argc; argc_ = argc;// 保存参数数量
// argv_ = argv; // argv_ = argv;
// don't save it, point to a local var in parse(const char* command_line). // don't save it, point to a local var in parse(const char* command_line).
// use member var args_ instead. // use member var args_ instead.
if (argc > 0) { if (argc > 0) {// 如果参数数量大于 0
this->cleanup(); this->cleanup(); // 清理之前的解析结果
args_.reserve(static_cast<size_t>(argc_)); args_.reserve(static_cast<size_t>(argc_));// 为 args_ 预留空间
for (int i = 0; i < argc_; ++i) { for (int i = 0; i < argc_; ++i) {// 遍历所有的命令行参数
args_.push_back(argv[i]); args_.push_back(argv[i]);// 将参数添加到 args_
} }
pr_ = new Parser::ParseResult; pr_ = new Parser::ParseResult;// 创建新的解析结果
return true; return true;
} }
return false; return false;// 如果参数数量为 0返回 false
} }
void Parser::cleanup() { void Parser::cleanup() {// Parser 类的 cleanup 方法,用于清理解析结果
args_.clear(); args_.clear();// 清空 args_
if (pr_) { if (pr_) {// 如果 pr_ 不为空
auto ibegin = pr_->begin(); auto ibegin = pr_->begin();
auto iend = pr_->end(); auto iend = pr_->end();
auto it = ibegin; auto it = ibegin;
for (; it != iend; ++it) { for (; it != iend; ++it) {// 遍历 pr_ 中的每个元素
ParseItem* item = it->second; ParseItem* item = it->second;
if (item) delete item; if (item) delete item;// 删除元素
} }
delete pr_; delete pr_;// 删除 pr_
pr_ = nullptr; pr_ = nullptr;
} }
} }
void Parser::set_addition() { void Parser::set_addition() {// Parser 类的 set_addition 方法,用于处理额外的选项
if (subroutines_->find(subroutine_name_) != subroutines_->end()) { if (subroutines_->find(subroutine_name_) != subroutines_->end()) {// 如果子程序名在 subroutines_ 中存在
for (const Row& row : *(subroutines_->at(subroutine_name_))) { for (const Row& row : *(subroutines_->at(subroutine_name_))) {// 遍历子程序中的每一行
// assume both -o and --option are allowed, // assume both -o and --option are allowed,
// but only provide -o, // but only provide -o,
// then set the another --option. // then set the another --option.
// vice versa. // vice versa.
const std::string& def = row.value(); const std::string& def = row.value();// 获取默认值
const std::string& ops = row.oshort(); const std::string& ops = row.oshort();// 获取短选项
const std::string& opl = row.olong(); const std::string& opl = row.olong();// 获取长选项
ParseResult& pr = *pr_; ParseResult& pr = *pr_; // 获取解析结果
bool has_short = this->has(ops.c_str()); bool has_short = this->has(ops.c_str());// 检查短选项是否存在
bool has_long = this->has(opl.c_str()); bool has_long = this->has(opl.c_str());// 检查长选项是否存在
// assume -o [ --option ] arg = 1 // assume -o [ --option ] arg = 1
// but not provide option value, // but not provide option value,
// then set to default 1. // then set to default 1.
// otherwise, both set to user defined value // otherwise, both set to user defined value
if (!ops.empty()) { if (!ops.empty()) {// 如果短选项不为空
if (has_short) { if (has_short) {// 如果短选项存在
if (pr[ops] != nullptr && !opl.empty()) { if (pr[ops] != nullptr && !opl.empty()) {// 如果短选项有值且长选项不为空
pr[opl] = new ParseItem(std::move(pr[ops]->val())); pr[opl] = new ParseItem(std::move(pr[ops]->val()));// 将短选项的值赋给长选项
} else if (pr[ops] == nullptr && !def.empty()) { } else if (pr[ops] == nullptr && !def.empty()) {// 如果短选项没有值且默认值不为空
pr[ops] = new ParseItem(std::move(def)); pr[ops] = new ParseItem(std::move(def));// 将默认值赋给短选项
if (!opl.empty()) pr[opl] = new ParseItem(std::move(def)); if (!opl.empty()) pr[opl] = new ParseItem(std::move(def));// 如果长选项不为空,也将默认值赋给长选项
} else { } else {
pr[opl] = nullptr; pr[opl] = nullptr;// 将长选项的值设为 nullptr
} }
} }
} }
if (!opl.empty()) { if (!opl.empty()) {// 如果长选项不为空
if (has_long) { if (has_long) { // 如果长选项存在
if (pr[opl] != nullptr && !ops.empty()) { if (pr[opl] != nullptr && !ops.empty()) { // 如果长选项有值且短选项不为空
pr[ops] = new ParseItem(std::move(pr[opl]->val())); pr[ops] = new ParseItem(std::move(pr[opl]->val()));// 将长选项的值赋给短选项
} else if (pr[opl] == nullptr && !def.empty()) { } else if (pr[opl] == nullptr && !def.empty()) {// 如果长选项没有值且默认值不为空
if (!ops.empty()) pr[ops] = new ParseItem(std::move(def)); if (!ops.empty()) pr[ops] = new ParseItem(std::move(def));// 如果短选项不为空,将默认值赋给短选项
pr[opl] = new ParseItem(std::move(def)); pr[opl] = new ParseItem(std::move(def));// 将默认值赋给长选项
} else { } else {
pr[ops] = nullptr; pr[ops] = nullptr;// 将短选项的值设为 nullptr
} }
} }
} }
if (!has_long && !has_short && !def.empty()) { if (!has_long && !has_short && !def.empty()) {// 如果长选项和短选项都不存在且默认值不为
if (!opl.empty()) pr[opl] = new ParseItem(std::move(def)); if (!opl.empty()) pr[opl] = new ParseItem(std::move(def));// 如果长选项不为空,将默认值赋给长选项
if (!ops.empty()) pr[ops] = new ParseItem(std::move(def)); if (!ops.empty()) pr[ops] = new ParseItem(std::move(def));// 如果短选项不为空,将默认值赋给短选项
} }
} // for } // for
} // if } // if
@ -427,114 +433,115 @@ void Parser::set_addition() {
// class Row // class Row
Row::Row() : require_value(true) {} Row::Row() : require_value(true) {} // Row 类的构造函数,初始化 require_value 为 true
// class Subroutine // class Subroutine
Subroutine::Subroutine() : first_line_("") {} Subroutine::Subroutine() : first_line_("") {}// Subroutine 类的默认构造函数,初始化 first_line_ 为空字符串
Subroutine::Subroutine(const char* name, const char* description) Subroutine::Subroutine(const char* name, const char* description)
: first_line_(""), description_(description), name_(name) { : first_line_(""), description_(description), name_(name) { // Subroutine 类的构造函数,接受子程序名和描述作为参数
usages_.reserve(5); usages_.reserve(5);// 为 usages_ 预留空间
} }
void Subroutine::print_with_row(std::ostream& out) { void Subroutine::print_with_row(std::ostream& out) {// Subroutine 类的 print_with_row 方法,接受一个输出流作为参数
// print the subroutine name and its description // print the subroutine name and its description
if (strcmp(get_first_line(), "") != 0) { // 打印子程序名和描述
if (strcmp(get_first_line(), "") != 0) {// 如果 first_line_ 不为空
// print the first line // print the first line
out << get_first_line(); out << get_first_line();
if (!usages_.empty()) { if (!usages_.empty()) {// 如果 usages_ 不为空
out << std::endl; out << std::endl;// 打印换行符
} }
} }
auto begin = usages_.begin(); auto begin = usages_.begin(); // 获取 usages_ 的开始迭代器
auto end = usages_.end(); auto end = usages_.end();// 获取 usages_ 的结束迭代器
std::vector<std::string> row_list; std::vector<std::string> row_list;// 创建一个字符串向量用于存储行
row_list.reserve(usages_.size()); row_list.reserve(usages_.size());// 为 row_list 预留空间
// build usage rows without description field, // build usage rows without description field,
// find the max-len row at the same time. // find the max-len row at the same time.
size_t max_len = 0; size_t max_len = 0;
std::for_each(begin, end, [&max_len, &row_list](const Row& row) { std::for_each(begin, end, [&max_len, &row_list](const Row& row) {// 遍历 usages_
std::stringstream ss; std::stringstream ss;// 创建一个字符串流
ss << " "; ss << " ";// 向字符串流中添加两个空格
if (!row.oshort().empty()) { if (!row.oshort().empty()) {// 如果短选项不为空
ss << "-" << row.oshort() << " "; ss << "-" << row.oshort() << " "; // 添加短选项
} }
if (!row.olong().empty()) { if (!row.olong().empty()) {// 如果长选项不为空
if (!row.oshort().empty()) if (!row.oshort().empty())
ss << "[ --" << row.olong() << " ] "; ss << "[ --" << row.olong() << " ] ";// 添加长选项
else else
ss << "--" << row.olong() << " "; ss << "--" << row.olong() << " "; // 添加长选项
} }
if (row.required()) { if (row.required()) {// 如果选项是必需的
ss << "arg "; ss << "arg "; // 添加 "arg "
if (!row.value().empty()) { if (!row.value().empty()) {// 如果选项值不为空
ss << "= " << row.value() << " "; ss << "= " << row.value() << " ";// 添加选项值
} }
} }
max_len = std::max(max_len, ss.str().size()); max_len = std::max(max_len, ss.str().size());// 更新最大长度
row_list.push_back(std::move(ss.str())); row_list.push_back(std::move(ss.str()));// 将字符串流的内容添加到 row_list
}); });
// show all rows and align description field // show all rows and align description field
size_t row_count = usages_.size(); size_t row_count = usages_.size();// 获取 usages_ 的大小
for (size_t i = 0; i < row_count; ++i) { for (size_t i = 0; i < row_count; ++i) {// 遍历 usages_
std::string str_row(std::move(row_list[i])); std::string str_row(std::move(row_list[i]));// 获取当前行
// print row without description // print row without description
out << str_row; out << str_row;// 打印当前行
// print spaces // print spaces
size_t spaces = 0; size_t spaces = 0;// 打印空格
size_t len = str_row.size(); size_t len = str_row.size();// 获取当前行的长度
if (max_len > len) spaces = max_len - len; if (max_len > len) spaces = max_len - len;// 计算需要打印的空格数量
while (spaces--) { while (spaces--) {// 打印空格
out << " "; out << " ";
} }
// print description // print description
out << usages_.at(i).desc() << std::endl; out << usages_.at(i).desc() << std::endl;// 打印描述
} }
} }
void Subroutine::print_with_template(std::ostream& out) { void Subroutine::print_with_template(std::ostream& out) {// Subroutine 类的 print_with_template 方法,接受一个输出流作为参数
for (auto usage : usages_) { for (auto usage : usages_) {// 遍历 usages_
size_t i = 0; size_t i = 0;
for (auto t = template_str_.begin(); t != template_str_.end(); ++t) { for (auto t = template_str_.begin(); t != template_str_.end(); ++t) {// 遍历模板字符串
if (*t == '%') { if (*t == '%') {// 如果当前字符是 '%'
switch (*(order_.begin() + i)) { switch (*(order_.begin() + i)) { // 根据 order_ 中的值决定打印哪个字段
case Row::kShort: case Row::kShort:
out << usage.oshort(); out << usage.oshort();// 打印短选项
break; break;
case Row::kLong: case Row::kLong:
out << usage.olong(); out << usage.olong();// 打印长选项
break; break;
case Row::kDefault: case Row::kDefault:
out << usage.value(); out << usage.value();// 打印默认值
break; break;
case Row::kDescription: case Row::kDescription:
out << usage.desc(); out << usage.desc();// 打印描述
break; break;
default: default:
break; break;
} }
++i; ++i;
} else { } else {
out << *t; out << *t;// 如果当前字符不是 '%',直接打印
} // if % } // if %
} // for template_str_ } // for template_str_
out << std::endl; out << std::endl;// 打印换行符
} // for usages_ } // for usages_
} }
std::ostream& operator<<(std::ostream& out, Subroutine& subroutine) { std::ostream& operator<<(std::ostream& out, Subroutine& subroutine) {// 重载 << 运算符,接受一个输出流和一个 Subroutine 对象作为参数
if (subroutine.template_str_.empty()) { if (subroutine.template_str_.empty()) {// 如果模板字符串为空
subroutine.print_with_row(out); subroutine.print_with_row(out);// 使用 print_with_row 方法打印
} else { } else {
subroutine.print_with_template(out); subroutine.print_with_template(out);// 使用 print_with_template 方法打印
} }
return out; return out;// 返回输出流
} }
} }

@ -1,127 +1,127 @@
#include "easypr/util/util.h" #include "easypr/util/util.h"
#include <string> #include <string>
#ifdef OS_WINDOWS // #ifdef OS_WINDOWS
#include <windows.h> #include <windows.h> // 包含windows.h头文件用于Windows平台的系统调用
#include <direct.h> #include <direct.h> // 包含direct.h头文件用于Windows平台的目录操作
#include <io.h> #include <io.h> // 包含io.h头文件用于Windows平台的IO操作
#define PATH_DELIMITER '\\' #define PATH_DELIMITER '\\' // 定义路径分隔符为'\\'
#ifdef min #ifdef min
#undef min #undef min // 如果已经定义了min取消其定义
#endif #endif
#ifdef max #ifdef max
#undef max #undef max // 如果已经定义了max取消其定义
#endif #endif
#elif defined(OS_LINUX) || defined(OS_UNIX) #elif defined(OS_LINUX) || defined(OS_UNIX)
#include <cstring> #include <cstring> // 包含cstring头文件用于字符串操作
#include <dirent.h> #include <dirent.h> // 包含dirent.h头文件用于目录操作
#include <sys/stat.h> #include <sys/stat.h> // 包含sys/stat.h头文件用于文件状态检查
#include <unistd.h> #include <unistd.h> // 包含unistd.h头文件用于Unix标准的系统调用
#define PATH_DELIMITER '/' #define PATH_DELIMITER '/' // 定义路径分隔符为'/'
#endif #endif
#ifdef OS_UNIX #ifdef OS_UNIX
#include <sys/timeb.h> #include <sys/timeb.h> // 包含sys/timeb.h头文件用于时间操作
#endif #endif
#include <list> #include <list> // 包含list头文件用于list数据结构
#include <opencv2/highgui/highgui.hpp> #include <opencv2/highgui/highgui.hpp> // 包含opencv的highgui模块用于图像IO操作
namespace easypr { namespace easypr { // 定义easypr命名空间
long Utils::getTimestamp() { long Utils::getTimestamp() { // 定义获取时间戳的函数
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
return static_cast<long>(cv::getTickCount()); return static_cast<long>(cv::getTickCount()); // Windows平台下使用opencv的getTickCount函数获取时间戳
#endif #endif
#ifdef OS_LINUX #ifdef OS_LINUX
struct timespec ts; struct timespec ts; // 定义timespec结构体用于获取时间
clock_gettime(CLOCK_MONOTONIC, &ts); clock_gettime(CLOCK_MONOTONIC, &ts); // 获取当前时间
return (ts.tv_sec * 1e3 + ts.tv_nsec / 1e6); return (ts.tv_sec * 1e3 + ts.tv_nsec / 1e6); // 返回毫秒级的时间戳
#endif #endif
#ifdef OS_UNIX #ifdef OS_UNIX
// there is no function provided by osx to get system tick count. // there is no function provided by osx to get system tick count.
// but considering the purpose by using this function, // but considering the purpose by using this function,
// we can simply return a millisecond since 1970/1/1 to calc the time elapse. // we can simply return a millisecond since 1970/1/1 to calc the time elapse.
struct timeb tb; struct timeb tb; // 定义timeb结构体用于获取时间
ftime(&tb); ftime(&tb); // 获取当前时间
return long(tb.time * 1e3 + tb.millitm); return long(tb.time * 1e3 + tb.millitm); // 返回毫秒级的时间戳
#endif #endif
} }
std::string Utils::getFileName(const std::string &path, std::string Utils::getFileName(const std::string &path,
const bool postfix /* = false */) { const bool postfix /* = false */) { // 定义获取文件名的函数
if (!path.empty()) { if (!path.empty()) { // 如果路径不为空
size_t last_slash = utils::get_last_slash(path); size_t last_slash = utils::get_last_slash(path); // 获取路径中最后一个斜杠的位置
size_t last_dot = path.find_last_of('.'); size_t last_dot = path.find_last_of('.'); // 获取路径中最后一个点的位置
if (last_dot < last_slash || last_dot == std::string::npos) { if (last_dot < last_slash || last_dot == std::string::npos) {
// not found the right dot of the postfix, // not found the right dot of the postfix,
// return the file name directly // return the file name directly
return path.substr(last_slash + 1); return path.substr(last_slash + 1); // 如果没有找到正确的后缀点,直接返回文件名
} else { } else {
// the path has a postfix // the path has a postfix
if (postfix) { if (postfix) {
// return the file name including postfix // return the file name including postfix
return path.substr(last_slash + 1); return path.substr(last_slash + 1); // 如果路径有后缀,并且需要返回后缀,返回包含后缀的文件名
} }
// without postfix // without postfix
return path.substr(last_slash + 1, last_dot - last_slash - 1); return path.substr(last_slash + 1, last_dot - last_slash - 1); // 如果路径有后缀,但不需要返回后缀,返回不包含后缀的文件名
} }
} }
return ""; return ""; // 如果路径为空,返回空字符串
} }
std::vector<std::string> Utils::splitString(const std::string &str, std::vector<std::string> Utils::splitString(const std::string &str,
const char delimiter) { const char delimiter) { // 定义字符串分割函数
std::vector<std::string> splited; std::vector<std::string> splited; // 定义存储分割结果的vector
std::string s(str); std::string s(str); // 复制输入的字符串
size_t pos; size_t pos; // 定义分割位置
while ((pos = s.find(delimiter)) != std::string::npos) { while ((pos = s.find(delimiter)) != std::string::npos) { // 当找到分隔符时
std::string sec = s.substr(0, pos); std::string sec = s.substr(0, pos); // 获取分隔符前的子串
if (!sec.empty()) { if (!sec.empty()) { // 如果子串不为空
splited.push_back(s.substr(0, pos)); splited.push_back(s.substr(0, pos)); // 将子串添加到分割结果中
} }
s = s.substr(pos + 1); s = s.substr(pos + 1); // 更新待分割的字符串
} }
splited.push_back(s); splited.push_back(s); // 将最后一个子串添加到分割结果中
return splited; return splited; // 返回分割结果
} }
std::vector<std::string> Utils::getFiles(const std::string &folder, std::vector<std::string> Utils::getFiles(const std::string &folder,
const bool all /* = true */) { const bool all /* = true */) { // 定义获取文件列表的函数
std::vector<std::string> files; std::vector<std::string> files; // 定义存储文件列表的vector
std::list<std::string> subfolders; std::list<std::string> subfolders; // 定义存储子文件夹的list
subfolders.push_back(folder); subfolders.push_back(folder); // 将输入的文件夹添加到子文件夹列表中
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
while (!subfolders.empty()) { while (!subfolders.empty()) { // 当子文件夹列表不为空时
std::string current_folder(subfolders.back()); std::string current_folder(subfolders.back()); // 获取当前处理的文件夹
if (*(current_folder.end() - 1) != '/') { if (*(current_folder.end() - 1) != '/') {
current_folder.append("/*"); current_folder.append("/*"); // 如果当前文件夹的路径不以'/'结尾,添加'/*'
} else { } else {
current_folder.append("*"); current_folder.append("*"); // 如果当前文件夹的路径以'/'结尾,添加'*'
} }
subfolders.pop_back(); subfolders.pop_back(); // 从子文件夹列表中移除当前处理的文件夹
struct _finddata_t file_info; struct _finddata_t file_info; // 定义文件信息结构体
auto file_handler = _findfirst(current_folder.c_str(), &file_info); auto file_handler = _findfirst(current_folder.c_str(), &file_info); // 打开当前文件夹
while (file_handler != -1) { while (file_handler != -1) { // 当文件夹打开成功时
if (all && if (all &&
(!strcmp(file_info.name, ".") || !strcmp(file_info.name, ".."))) { (!strcmp(file_info.name, ".") || !strcmp(file_info.name, ".."))) {
if (_findnext(file_handler, &file_info) != 0) break; if (_findnext(file_handler, &file_info) != 0) break;
@ -136,7 +136,7 @@ std::vector<std::string> Utils::getFiles(const std::string &folder,
folder.pop_back(); folder.pop_back();
folder.append(file_info.name); folder.append(file_info.name);
subfolders.push_back(folder.c_str()); subfolders.push_back(folder.c_str()); // 如果是子文件夹,并且需要搜索子文件夹,将子文件夹添加到子文件夹列表中
} }
} else { } else {
// it's a file // it's a file
@ -145,24 +145,24 @@ std::vector<std::string> Utils::getFiles(const std::string &folder,
file_path.assign(current_folder.c_str()).pop_back(); file_path.assign(current_folder.c_str()).pop_back();
file_path.append(file_info.name); file_path.append(file_info.name);
files.push_back(file_path); files.push_back(file_path); // 如果是文件,将文件路径添加到文件列表中
} }
if (_findnext(file_handler, &file_info) != 0) break; if (_findnext(file_handler, &file_info) != 0) break;
} // while } // while
_findclose(file_handler); _findclose(file_handler); // 关闭文件夹
} }
#elif defined(OS_LINUX) || defined(OS_UNIX) #elif defined(OS_LINUX) || defined(OS_UNIX)
while (!subfolders.empty()) { while (!subfolders.empty()) { // 当子文件夹列表不为空时
std::string current_folder(subfolders.back()); std::string current_folder(subfolders.back()); // 获取当前处理的文件夹
if (*(current_folder.end() - 1) != '/') { if (*(current_folder.end() - 1) != '/') {
current_folder.push_back('/'); current_folder.push_back('/'); // 如果当前文件夹的路径不以'/'结尾,添加'/'
} }
DIR* pdir = opendir(current_folder.c_str()); DIR* pdir = opendir(current_folder.c_str()); // 打开当前文件夹
subfolders.pop_back(); subfolders.pop_back(); // 从子文件夹列表中移除当前处理的文件夹
if (!pdir) { if (!pdir) {
continue; continue;
@ -170,9 +170,9 @@ std::vector<std::string> Utils::getFiles(const std::string &folder,
dirent* dir = NULL; dirent* dir = NULL;
while ((dir = readdir(pdir)) != NULL) { while ((dir = readdir(pdir)) != NULL) { // 当读取到文件或文件夹时
// iterates the current folder, search file & sub folder // iterates the current folder, search file & sub folder
struct stat st; struct stat st; // 定义文件状态结构体
if (all && (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))) { if (all && (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))) {
// must ignore . & .. // must ignore . & ..
@ -201,93 +201,93 @@ std::vector<std::string> Utils::getFiles(const std::string &folder,
std::string subfolder(current_folder); std::string subfolder(current_folder);
subfolder.append(dir->d_name); subfolder.append(dir->d_name);
subfolders.push_back(subfolder.c_str()); subfolders.push_back(subfolder.c_str()); // 如果是子文件夹,并且需要搜索子文件夹,将子文件夹添加到子文件夹列表中
} }
} else { } else {
// it's a file // it's a file
files.push_back(file_path); files.push_back(file_path); // 如果是文件,将文件路径添加到文件列表中
} }
} // while } // while
closedir(pdir); closedir(pdir); // 关闭文件夹
} }
#endif #endif
return files; return files; // 返回文件列表
} }
bool Utils::mkdir(const std::string folder) { bool Utils::mkdir(const std::string folder) { // 定义创建文件夹的函数
std::string folder_builder; std::string folder_builder; // 定义文件夹路径构造器
std::string sub; std::string sub; // 定义子路径
sub.reserve(folder.size()); sub.reserve(folder.size());
for (auto it = folder.begin(); it != folder.end(); ++it) { for (auto it = folder.begin(); it != folder.end(); ++it) { // 遍历输入的文件夹路径
const char c = *it; const char c = *it;
sub.push_back(c); sub.push_back(c);
if (c == PATH_DELIMITER || it == folder.end() - 1) { if (c == PATH_DELIMITER || it == folder.end() - 1) { // 当遇到路径分隔符或路径结束时
folder_builder.append(sub); folder_builder.append(sub); // 将子路径添加到文件夹路径构造器中
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
if (0 != ::_access(folder_builder.c_str(), 0)) { if (0 != ::_access(folder_builder.c_str(), 0)) { // 如果文件夹不存在
#else #else
if (0 != ::access(folder_builder.c_str(), 0)) { if (0 != ::access(folder_builder.c_str(), 0)) { // 如果文件夹不存在
#endif #endif
// this folder not exist // this folder not exist
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
if (0 != ::_mkdir(folder_builder.c_str())) { if (0 != ::_mkdir(folder_builder.c_str())) { // 如果创建文件夹失败
#else #else
if (0 != ::mkdir(folder_builder.c_str(), S_IRWXU)) { if (0 != ::mkdir(folder_builder.c_str(), S_IRWXU)) { // 如果创建文件夹失败
#endif #endif
// create failed // create failed
return false; return false; // 返回失败
} }
} }
sub.clear(); sub.clear(); // 清空子路径
} }
} }
return true; return true; // 返回成功
} }
bool Utils::imwrite(const std::string &file, const cv::Mat &image) { bool Utils::imwrite(const std::string &file, const cv::Mat &image) { // 定义图像写入函数
auto folder = file.substr(0, utils::get_last_slash(file)); auto folder = file.substr(0, utils::get_last_slash(file)); // 获取文件所在的文件夹
Utils::mkdir(folder); Utils::mkdir(folder); // 创建文件所在的文件夹
return cv::imwrite(file, image); return cv::imwrite(file, image); // 写入图像
} }
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
std::string Utils::utf8_to_gbk(const char* utf8) { std::string Utils::utf8_to_gbk(const char* utf8) { // 定义UTF-8到GBK的转换函数
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0); int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0); // 获取转换后的长度
wchar_t* wszGBK = new wchar_t[len + 1]; wchar_t* wszGBK = new wchar_t[len + 1]; // 定义存储转换结果的宽字符数组
memset(wszGBK, 0, len * 2 + 2); memset(wszGBK, 0, len * 2 + 2); // 初始化宽字符数组
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wszGBK, len); MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wszGBK, len); // 将UTF-8字符串转换为宽字符字符串
len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL); // 获取转换后的长度
char* szGBK = new char[len + 1]; char* szGBK = new char[len + 1]; // 定义存储转换结果的字符数组
memset(szGBK, 0, len + 1); memset(szGBK, 0, len + 1); // 初始化字符数组
WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL); WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL); // 将宽字符字符串转换为GBK字符串
std::string strTemp(szGBK); std::string strTemp(szGBK); // 将GBK字符串转换为std::string
if (wszGBK) if (wszGBK)
delete[] wszGBK; delete[] wszGBK; // 删除宽字符数组
if (szGBK) if (szGBK)
delete[] szGBK; delete[] szGBK; // 删除字符数组
return strTemp; return strTemp; // 返回转换结果
} }
#endif #endif
std::size_t Utils::get_last_slash(const std::string &path) { std::size_t Utils::get_last_slash(const std::string &path) { // 定义获取路径中最后一个斜杠的位置的函数
#ifdef OS_WINDOWS #ifdef OS_WINDOWS
size_t last_slash_1 = path.find_last_of("\\"); size_t last_slash_1 = path.find_last_of("\\"); // 获取路径中最后一个'\\'的位置
size_t last_slash_2 = path.find_last_of("/"); size_t last_slash_2 = path.find_last_of("/"); // 获取路径中最后一个'/'的位置
size_t last_slash; size_t last_slash;
if (last_slash_1 != std::string::npos && last_slash_2 != std::string::npos) { if (last_slash_1 != std::string::npos && last_slash_2 != std::string::npos) {
// C:/path\\to/file.postfix // C:/path\\to/file.postfix
last_slash = std::max(last_slash_1, last_slash_2); last_slash = std::max(last_slash_1, last_slash_2); // 如果路径中既有'\\'又有'/',取最后出现的一个
} else { } else {
// C:\\path\\to\\file.postfix // C:\\path\\to\\file.postfix
// C:/path/to/file.postfix // C:/path/to/file.postfix
last_slash = last_slash =
(last_slash_1 == std::string::npos) ? last_slash_2 : last_slash_1; (last_slash_1 == std::string::npos) ? last_slash_2 : last_slash_1; // 如果路径中只有'\\'或只有'/',取出现的那一个
} }
#else #else
size_t last_slash = path.find_last_of('/'); size_t last_slash = path.find_last_of('/'); // 获取路径中最后一个'/'的位置
#endif #endif
return last_slash; return last_slash; // 返回最后一个斜杠的位置
} }
} // namespace easypr } // namespace easypr
Loading…
Cancel
Save