⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nnshaperecognizer.cpp

📁 An open source handwriting recongnition package!!!
💻 CPP
📖 第 1 页 / 共 5 页
字号:
 * CHANGE HISTROY
 * Author			Date				Description
 *************************************************************************************/
int NNShapeRecognizer::computeDTWDistance(
        const LTKShapeSample& inFirstShapeSampleFeatures,
        const LTKShapeSample& inSecondShapeSampleFeatures,
        float& outDTWDistance)

{
    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
        "NNShapeRecognizer::computeDTWDistance()" << endl;

    const vector<LTKShapeFeaturePtr>& firstFeatureVec = inFirstShapeSampleFeatures.getFeatureVector();
    const vector<LTKShapeFeaturePtr>& secondFeatureVec = inSecondShapeSampleFeatures.getFeatureVector();

    int errorCode = m_dtwObj.computeDTW(firstFeatureVec, secondFeatureVec, getDistance,outDTWDistance,
            m_dtwBanding, FLT_MAX, FLT_MAX);

    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "DTWDistance: " <<
        outDTWDistance << endl;

    if (errorCode != SUCCESS )
    {
        LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Error: "<<
            getErrorMessage(errorCode) <<
            " NNShapeRecognizer::computeDTWDistance()" << endl;
        LTKReturnError(errorCode);
    }

    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
        "NNShapeRecognizer::computeDTWDistance()" << endl;

    return SUCCESS;
}


/**********************************************************************************
 * AUTHOR		: Sridhar Krishna
 * DATE			: 24-04-2006
 * NAME			: computeEuclideanDistance
 * DESCRIPTION	: computes euclidean distance between two characters
 * ARGUMENTS		: LTKShapeFeaturePtrtor - 2
 * RETURNS		: euclidean distance
 * NOTES			:
 * CHANGE HISTROY
 * Author			Date				Description
 *************************************************************************************/
int NNShapeRecognizer::computeEuclideanDistance(
        const LTKShapeSample& inFirstShapeSampleFeatures,
        const LTKShapeSample& inSecondShapeSampleFeatures,
        float& outEuclideanDistance)
{
    const vector<LTKShapeFeaturePtr>& firstFeatureVec = inFirstShapeSampleFeatures.getFeatureVector();
    const vector<LTKShapeFeaturePtr>& secondFeatureVec = inSecondShapeSampleFeatures.getFeatureVector();

    int firstFeatureVectorSize = firstFeatureVec.size();
    int secondFeatureVectorSize = secondFeatureVec.size();

    if(firstFeatureVectorSize != secondFeatureVectorSize)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EUNEQUAL_LENGTH_VECTORS << " " <<
            getErrorMessage(EUNEQUAL_LENGTH_VECTORS) <<
            " NNShapeRecognizer::computeEuclideanDistance()" << endl;

        LTKReturnError(EUNEQUAL_LENGTH_VECTORS);
    }

    for(int i = 0; i < firstFeatureVectorSize; ++i)
    {
        float tempDistance = 0.0f;
        int errorCode = getDistance(firstFeatureVec[i],
                secondFeatureVec[i],
                tempDistance);

        if (errorCode != SUCCESS )
        {
            LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<  errorCode << " " <<
                " NNShapeRecognizer::computeEuclideanDistance()" << endl;
            LTKReturnError(errorCode);
        }
        else
        {
            outEuclideanDistance += tempDistance;
        }
    }

    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
        "NNShapeRecognizer::computeEuclideanDistance()" << endl;
    return SUCCESS;
}


/**********************************************************************************
 * AUTHOR		: Saravanan. R
 * DATE			: 23-01-2007
 * NAME			: loadModelData
 * DESCRIPTION	: loads the reference model file into memory
 * ARGUMENTS		:
 * RETURNS		: SUCCESS on successful loading of the reference model file
 * NOTES			:
 * CHANGE HISTROY
 * Author			Date				Description
 *************************************************************************************/
int NNShapeRecognizer::loadModelData()
{
    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Entering " <<
        "NNShapeRecognizer::loadModelData()" << endl;

    int numofShapes = 0;

    // variable for shape Id
    int classId = -1;

    //Algorithm version
    string algoVersionReadFromMDT = "";

//    int iMajor, iMinor, iBugfix = 0;

    stringStringMap headerSequence;
    LTKCheckSumGenerate cheSumGen;

    if(errorCode = cheSumGen.readMDTHeader(m_nnMDTFilePath,headerSequence))
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< errorCode << " " <<
            " NNShapeRecognizer::loadModelData()" << endl;
        LTKReturnError(errorCode);
    }

	// printing the headerseqn
	stringStringMap::const_iterator iter = headerSequence.begin();
	stringStringMap::const_iterator endIter = headerSequence.end();

	for(; iter != endIter; iter++)
	{
		LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Debug: header seqn"<<
            iter->first << " : " <<
            iter->second << endl;
	}

    string featureExtractor = headerSequence[FE_NAME];

    if(LTKSTRCMP(m_featureExtractorName.c_str(), featureExtractor.c_str()) != 0)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<  ECONFIG_MDT_MISMATCH << " " <<
            "Value of FeatureExtractor parameter in config file ("<<
            m_featureExtractorName<<") does not match with the value in MDT file ("<<
            featureExtractor<<")"<<
            " NNShapeRecognizer::loadModelData()" << endl;
        LTKReturnError(ECONFIG_MDT_MISMATCH);
    }

    string feVersion = headerSequence[FE_VER];

    // comparing the mdt open mode read from cfg file with value in the mdt header
    string mdtOpenMode = headerSequence[MDT_FOPEN_MODE];

    if (LTKSTRCMP(m_MDTFileOpenMode.c_str(), mdtOpenMode.c_str()) != 0)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<  ECONFIG_MDT_MISMATCH << " " <<
            "Value of NNMDTFileOpenMode parameter in config file ("<<
            m_MDTFileOpenMode <<") does not match with the value in MDT file ("<<
            mdtOpenMode<<")"<<
            " NNShapeRecognizer::loadModelData()" << endl;
        LTKReturnError(ECONFIG_MDT_MISMATCH);
    }


    // validating preproc parameters
    int iErrorCode = validatePreprocParameters(headerSequence);
    if (iErrorCode != SUCCESS )
    {
    	LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<  ECONFIG_MDT_MISMATCH << " " <<
            "Values of NNMDTFileOpenMode parameter in config file does not match with "
            <<"the values in MDT file " << "NNShapeRecognizer::loadModelData()" << endl;

        LTKReturnError(ECONFIG_MDT_MISMATCH);
    }

    // Version comparison START
    algoVersionReadFromMDT = headerSequence[RECVERSION].c_str();

    LTKVersionCompatibilityCheck verTempObj;
    string supportedMinVersion(SUPPORTED_MIN_VERSION);
    string currentVersionStr(m_currentVersion);

    bool compatibilityResults = verTempObj.checkCompatibility(supportedMinVersion,
            currentVersionStr,
            algoVersionReadFromMDT);

    if(compatibilityResults == false)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINCOMPATIBLE_VERSION << " " <<
            " Incompatible version"<<
            " NNShapeRecognizer::loadModelData()" << endl;
        LTKReturnError(EINCOMPATIBLE_VERSION);
    }
    // Version comparison END

    //Input Stream for Model Data file
    ifstream mdtFileHandle;

    if (m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
    {
        mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::in);
    }
    else
    {
        mdtFileHandle.open(m_nnMDTFilePath.c_str(), ios::in | ios::binary);
    }

    //If error while opening, return an error
    if(!mdtFileHandle)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EMODEL_DATA_FILE_OPEN << " " <<
            " Unable to open model data file : " <<m_nnMDTFilePath<<
            " NNShapeRecognizer::loadModelData()" << endl;
        LTKReturnError(EMODEL_DATA_FILE_OPEN);
    }

    mdtFileHandle.seekg(atoi(headerSequence[HEADERLEN].c_str()),ios::beg);

    //Read the number of shapes
    if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
    {
        mdtFileHandle >> numofShapes;
    }
    else
    {
        mdtFileHandle.read((char*) &numofShapes,
                            atoi(headerSequence[SIZEOFSHORTINT].c_str()));
    }

    if(!m_projectTypeDynamic && m_numShapes != numofShapes)
    {
        LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< ECONFIG_MDT_MISMATCH << " " <<
            " Value of NumShapes parameter in config file ("<<m_numShapes<<
            ") does not match with the value in MDT file ("<<numofShapes<<")"<<
            " NNShapeRecognizer::loadModelData()" << endl;
        LTKReturnError(ECONFIG_MDT_MISMATCH);
    }

    if(m_projectTypeDynamic)
    {
        m_numShapes = numofShapes;
    }

    // validating the header values

    stringVector tokens;

    string strFeatureVector = "";

    LTKShapeSample shapeSampleFeatures;

    int floatSize = atoi(headerSequence[SIZEOFFLOAT].c_str());

	int intSize = atoi(headerSequence[SIZEOFINT].c_str());

    while(!mdtFileHandle.eof())
    {

        if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
        {
            mdtFileHandle >> classId;
        }
        else
        {
            mdtFileHandle.read((char*) &classId, intSize);

            if ( mdtFileHandle.fail() )
            {
                break;
            }
        }

        vector<LTKShapeFeaturePtr> shapeFeatureVector;
        LTKShapeFeaturePtr shapeFeature;

        if ( m_MDTFileOpenMode == NN_MDT_OPEN_MODE_ASCII )
        {
            mdtFileHandle >> strFeatureVector;

            LTKStringUtil::tokenizeString(strFeatureVector,  FEATURE_EXTRACTOR_DELIMITER,  tokens);

            if(classId == -1)
                continue;

            for(int i = 0; i < tokens.size(); ++i)
            {
                shapeFeature = m_ptrFeatureExtractor->getShapeFeatureInstance();

                if (shapeFeature->initialize(tokens[i]) != SUCCESS)
                {
                    LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<< EINVALID_INPUT_FORMAT << " " <<
                        "Number of features extracted from a trace is not correct"<<
                        " NNShapeRecognizer::loadModelData()" << endl;

                    LTKReturnError(EINVALID_INPUT_FORMAT);
                }

                shapeFeatureVector.push_back(shapeFeature);
            }
        }
        else
        {
            int numberOfFeatures;
            int featureDimension;

            mdtFileHandle.read((char*) &numberOfFeatures, intSize);
            mdtFileHandle.read((char*) &featureDimension, intSize);

            int featureIndex = 0;

            for ( ; featureIndex < numberOfFeatures ; featureIndex++)
            {
                floatVector floatFeatureVector;
                int featureValueIndex = 0;

                shapeFeature = m_ptrFeatureExtractor->getShapeFeatureInstance();

                for(; featureValueIndex < featureDimension ; featureValueIndex++)
                {
                    float featureValue = 0.0f;

                    mdtFileHandle.read((char*) &featureValue, floatSize);

                    floatFeatureVector.push_back(featureValue);

                    if ( mdtFileHandle.fail() )
                    {
                        break;
                    }
                }

                if (shapeFeature->initialize(floatFeatureVector) != SUCCESS)
                {
                    LOG(LTKLogger::LTK_LOGLEVEL_ERR)<<"Error: "<<
                        EINVALID_INPUT_FORMAT << " " <<
                        "Number of features extracted from a trace is not correct"<<
                        " NNShapeRecognizer::loadModelData()" << endl;

                    LTKReturnError(EINVALID_INPUT_FORMAT);
                }

                shapeFeatureVector.push_back(shapeFeature);

            }

            //cout << endl;
        }

        //Set the feature vector and class id to the shape sample features
        shapeSampleFeatures.setFeatureVector(shapeFeatureVector);
        shapeSampleFeatures.setClassID(classId);

        //Adding all shape sample feature to the prototypeset
        m_prototypeSet.push_back(shapeSampleFeatures);
        //Add to Map
        if(	m_shapeIDNumPrototypesMap.find(classId)==m_shapeIDNumPrototypesMap.end())
        {
            m_shapeIDNumPrototypesMap[classId] = 1;
        }
        else
        {
            ++(m_shapeIDNumPrototypesMap[classId]);
        }


        //Clearing the vectors
        shapeFeatureVector.clear();
        tokens.clear();
        classId = -1;
        strFeatureVector = "";

    }


    mdtFileHandle.close();

    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG) << "Exiting " <<
        "NNShapeRecognizer::loadModelData()" << endl;

    return SUCCESS;
}

/*******************************************************************************

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -