示例#1
0
void* mops_match(void* _imgs) {
    printf("MOPS hello!\n");
    img2_t* imgs = (img2_t*) _imgs;
    int nUpLevels = 0, nDnLevels = 1, nKeyPoints = 30;
    float cRobust = 0.9;
    MOPSFeatures feats(nUpLevels,nDnLevels,nKeyPoints,cRobust);
    cv::FlannBasedMatcher matcher;
    std::vector<cv::KeyPoint> kp1;
    std::vector<cv::KeyPoint> kp2;
    cv::Mat desc1;
    cv::Mat desc2;
    std::vector<cv::DMatch> matches;
    std::vector<cv::DMatch> good_matches;

    // Note: If still too slow, we can thread these.
    // Detect keypoints and get descriptors.
    feats.getFeatures(imgs->img1, kp1, desc1);
    feats.getFeatures(imgs->img2, kp2, desc2);

    // Match descriptors.
    matcher.match(desc1, desc2, matches);
    // Threshold to only good matches.
    for (size_t i = 0; i < desc1.rows; ++i) {
	if (matches[i].distance < MOPS_DISTANCE_THRESH) {
	    good_matches.push_back(matches[i]);
	}
    }
    return NULL;
}
示例#2
0
void mexFunctionTest(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs != 2)
    {
        mexPrintf("Usage: [score] = LDARegTreePredict( model, feats )\n");
        mexPrintf("\tfeats must be of type SINGLE\n");
        mexErrMsgTxt("Incorrect input format.\n");
    }

    if (nlhs != 1)
        mexErrMsgTxt("Two output args expected");

    #define mFeats (prhs[1])
    #define mModel (prhs[0])

    MatlabInputMatrix<FeatsType> pFeats( mFeats, 0, 0, "feats" );

    RegTreeType tree;
    tree.loadFromMatlab( mModel );

    // for now just copy the values
    Eigen::Map< const gFeatArrayType >	feats( pFeats.data(), pFeats.rows(), pFeats.cols() );

    gWeightsArrayType pred( pFeats.rows() );

    tree.predict(   MatrixSampleIndexListType(feats),
                    MatrixFeatureValueObjectType(feats),
                    pred );

    MatlabOutputMatrix<double>   outMatrix( &plhs[0], feats.rows(), 1 );
    for (unsigned i=0; i < feats.rows(); i++)
        outMatrix.data()[i] = pred.coeff(i);
}
示例#3
0
//----------------------------------------------------------------------
//----------------------------------------------------------------------
bool Graph::load_graph() {
	std::string line, token;
	// open file
	std::ifstream graph_file(graph_fname.c_str(), std::ifstream::in);
	if (graph_file.good()) {
		// read first line (nodes and feats)
		read_trimmed_line(graph_file, line);
		std::istringstream iss(line, std::istringstream::in);
		iss >> n_nodes >> n_feats;
		// create space for all feature vectors
		feat_vecs = new DMatrix(n_nodes, n_feats);
		// read all feature vectors
		for (int i = 0 ; i < n_nodes ; i ++) {
			read_trimmed_line(graph_file, line);
			std::istringstream feats(line, std::istringstream::in);
			for (int j = 0 ; j < n_feats ; j ++) {
				feats >> feat_vecs->at(i,j);
			}
		}
		// create space for adjacency matrix
		adj_mat = new DMatrix(n_nodes, n_nodes);
		// read adjacency matrix
		for (int i = 0 ; i < n_nodes ; i ++) {
			read_trimmed_line(graph_file, line);
			std::istringstream weights(line, std::istringstream::in);
			for (int j = 0 ; j < n_nodes ; j ++) {
				weights >> adj_mat->at(i,j);
			}
		}
		// create space for shortest path adjacency matrix
		sp_adj_mat = new DMatrix(n_nodes, n_nodes);
		// transform sp adjacency matrix before applying flod warshall
		for (int i = 0 ; i < n_nodes ; i ++) {
			for (int j = 0 ; j < n_nodes ; j ++) {
				if (i != j) {
					if (adj_mat->at(i,j) == 0) {
						sp_adj_mat->set(i, j, std::numeric_limits<double>::infinity());
					} else {
						sp_adj_mat->set(i, j, adj_mat->at(i, j));
					}
				}
				// else ignore self-loops (already 0)
			}
		}
		// apply floyd warshal to the adj matrix
		for (int k = 0 ; k < n_nodes ; k ++) {
			for (int i =  0 ; i < n_nodes ; i ++) {
				for (int j = 0 ; j < n_nodes ; j ++) {
					sp_adj_mat->set(i, j, std::min(sp_adj_mat->at(i,j), sp_adj_mat->at(i,k)+sp_adj_mat->at(k,j)));
				}
			}
		}
		// close file
		graph_file.close();
		std::cout << "Log: " << n_nodes << " nodes read from " << graph_fname << std::endl;
		return true;
	}
示例#4
0
void mexFunctionTrain(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs != 4)
    {
        mexPrintf("Usage: model = LDARegStump(feats, responses, weights, numLevels)\n");
        mexErrMsgTxt("Incorrect input format\n");
    }

    if (nlhs != 1)
        mexErrMsgTxt("One output args expected");

    #define mFeats (prhs[0])
    #define mResponses (prhs[1])
    #define mWeights (prhs[2])
    #define mNumLevels (prhs[3])

    MatlabInputMatrix<FeatsType> pFeats( mFeats, 0, 0, "feats" );
    MatlabInputMatrix<WeightsType> pResponses( mResponses, pFeats.rows(), 1, "labels" );
    MatlabInputMatrix<WeightsType> pWeights( mWeights, pFeats.rows(), 1, "labels" );

    if ( mxGetClassID(mNumLevels) != mxUINT32_CLASS )
        mexErrMsgTxt("numLevels must be UINT32");
    if ( mxGetNumberOfElements(mNumLevels) != 1 )
        mexErrMsgTxt("numLevels must be a scalar");

    const unsigned maxDepth = ((unsigned int *)mxGetData(mNumLevels))[0];

    RegTreeType tree;

    {           
        // for now just copy the values
        Eigen::Map< const gFeatArrayType >	feats( pFeats.data(), pFeats.rows(), pFeats.cols() );
        Eigen::Map< const gResponseArrayType > responses( pResponses.data(), pResponses.rows() );
        Eigen::Map< const gWeightsArrayType >	weights( pWeights.data(), pWeights.rows() );

        tree.learn( MatrixSampleIndexListType(feats),
                    MatrixFeatureIndexListType(feats),
                    MatrixFeatureValueObjectType(feats),
                    MatrixResponseAndWeightsValueObject( responses, weights ),
                    maxDepth);
    }

    plhs[0] = tree.saveToMatlab();

#undef mFeats
#undef mResponses
#undef mWeights
}
  ///
  /// Train a A* Search Tree using kmeans
  ///
  SearchTree train_search_kmeans(map<string,NNTemplateType>&allTemplates,int depth)
  {    
    static constexpr int K = 2;      
    // base case
    assert(allTemplates.size() > 0);
    if(allTemplates.size() == 1)
    {
      SearchTree merged;
      merged.Templ = allTemplates.begin()->second;
      merged.children = vector<shared_ptr<SearchTree> >{};
      merged.id = seq_id++;      
      merged.pose_uuid = allTemplates.begin()->first;
      return merged;
    }
    // recursive case
    else
    {
      // invoke kmeans
      cv::Mat feats(allTemplates.size(),allTemplates.begin()->second.getTIm().size().area(),
		    DataType<float>::type,Scalar::all(0));
      int iter = 0;
      for(auto && templ : allTemplates)
	templ.second.getTIm().reshape(0,1).copyTo(feats.row(iter++));
      //cout << feats << endl;
      Mat bestLabels;
      cv::TermCriteria term_crit(cv::TermCriteria::MAX_ITER,1000,1000);
      int attempts = 20;
      cv::kmeans(feats,K,bestLabels,term_crit,attempts,KMEANS_PP_CENTERS);

      // generate the partitons
      map<int,map<string,NNTemplateType> > partitions;
      iter = 0;
      for(auto && templ : allTemplates)
      {
	int id = bestLabels.at<int>(iter++);
	for(int iter = 0; iter < depth; ++iter)
	  log_file << "\t";
	log_file << id << "  " << templ.first << endl;
	partitions[id][templ.first] = templ.second;	
      }      

      // generate the child nodes
      vector<SearchTree> child_trees;
      TaskBlock kmeans_recurse("kmeans_recurse");
      for(int k = 0; k < K; ++k)
      {
	kmeans_recurse.add_callee([&,k]()
				  {
				    auto sub_tree = train_search_kmeans(partitions[k],depth+1);
				    static mutex m; lock_guard<mutex> l(m);
				    child_trees.push_back(sub_tree);
				  });
      }
      kmeans_recurse.execute();
      
      // generate the split node
      SearchTree split;
      split.Templ = child_trees[0].Templ;
      split.children = vector<shared_ptr<SearchTree > >{make_shared<SearchTree>(child_trees[0])};
      for(int k = 1; k < K; ++k)
      {
	split.Templ = split.Templ.merge(child_trees[k].Templ);
	split.children.push_back(make_shared<SearchTree>(child_trees[k]));
      }
      split.id = seq_id++;      

      if(depth == 0)
      {
	log_search_tree(split);
	//save_search_tree(split);
      }

      return split;      
    }
  }
示例#6
0
文件: ddicrawler.cpp 项目: mtassin/4e
static T_Status Crawl_Data(bool use_cache, T_Glyph_Ptr email, T_Glyph_Ptr password,
                            T_Filename output_folder, bool is_clear)
{
    T_Status                status;
    T_WWW                   internet = NULL;
    bool                    is_exists;
    T_Glyph_Ptr             path_ptr;
    T_Filename              folder;
    T_XML_Document          doc_languages = NULL;
    T_XML_Document          doc_wepprops = NULL;
    T_XML_Document          doc_sources = NULL;
    C_Pool                  pool(10000000,10000000);
    C_DDI_Deities           deities(&pool);
    C_DDI_Skills            skills(&pool);
    C_DDI_Rituals           rituals(&pool);
    C_DDI_Items             items(&pool);
    C_DDI_Classes           classes(&pool);
    C_DDI_Races             races(&pool);
    C_DDI_Paragons          paragons(&pool);
    C_DDI_Epics             epics(&pool);
    C_DDI_Feats             feats(&pool);
    C_DDI_Powers            powers(&pool);
    C_DDI_Monsters          monsters(&pool);
    C_DDI_Backgrounds       backgrounds(&pool);
    vector<C_DDI_Common *>  list;
    vector<C_DDI_Single_Common *>   singles;

    /* Add all of our downloader classes to the list
    */
    list.push_back(&deities);
    list.push_back(&skills);
    list.push_back(&rituals);
    list.push_back(&items);
    list.push_back(&classes);
    list.push_back(&races);
    list.push_back(&paragons);
    list.push_back(&epics);
    list.push_back(&feats);
    list.push_back(&powers);
//Monsters aren't supported yet...
#ifdef NOTYET
    list.push_back(&monsters);
#endif
    list.push_back(&backgrounds);

    /* Find a temporary folder to use
    */
    Get_Temporary_Folder(folder);
    path_ptr = folder + strlen(folder);

    /* Search for the folder and create it if it doesn't exist
    */
    is_exists = FileSys_Does_Folder_Exist(folder);
    if (!is_exists) {
        status = FileSys_Create_Directory(folder);
        if (x_Trap_Opt(!x_Is_Success(status))) {
            Log_Message("Couldn't create temporary folder.");
            x_Status_Return(LWD_ERROR);
            }
        }

    /* If we're not using cached copies, log in to D&D insider (if we don't
        have a username and password, this just establishes the connection)
    */
    if (!use_cache) {
        Log_Message("Connecting to server...\n", true);

        /* Open a connection to the server first
        */
        status = WWW_HTTP_Open(&internet,LOGIN_URL,NULL,NULL,NULL);
        if (x_Trap_Opt(!x_Is_Success(status))) {
            Log_Message("Couldn't open connection to login server!\n", true);
            goto cleanup_exit;
            }

        status = Login(internet, email, password, true);
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }

    /* If we're not using the cache, we want to make sure we have fresh copies
        of everything, so delete the files in our temporary folder
    */
    if (!use_cache) {
        strcpy(path_ptr,"*.*");
        FileSys_Delete_Files(folder);
        *path_ptr = '\0';
        }

    /* Create XML documents for deities languages - the crawlers can add their
        own entries for these during processing
    */
    status = Create_Document(&doc_languages, &l_language_root, "language",
                                DTD_Get_Data());
    if (!x_Is_Success(status))
        goto cleanup_exit;
    status = Create_Document(&doc_wepprops, &l_wepprop_root, "weapon property",
                                DTD_Get_Augmentation());
    if (!x_Is_Success(status))
        goto cleanup_exit;
    status = Create_Document(&doc_sources, &l_source_root, "source",
                                DTD_Get_Augmentation());
    if (!x_Is_Success(status))
        goto cleanup_exit;

    /* First, download all the index pages if we need to
    */
    if (!use_cache) {
        for (ddi_iter it = list.begin(); it != list.end(); ++it) {
            status = (*it)->Download_Index(folder, internet);
            if (x_Trap_Opt(!x_Is_Success(status)))
                goto cleanup_exit;
            }
        for (single_iter it = singles.begin(); it != singles.end(); ++it) {
            status = (*it)->Download(folder, internet);
            if (x_Trap_Opt(!x_Is_Success(status)))
                goto cleanup_exit;
            }
        }

    /* Read them in
    */
    for (ddi_iter it = list.begin(); it != list.end(); ++it) {
        status = (*it)->Read_Index(folder);
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }
    for (single_iter it = singles.begin(); it != singles.end(); ++it) {
        status = (*it)->Read(folder);
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }

    /* Now download the rest of the content all at once
        NOTE: As of March 2011, there's no further content for download unless
            you have a password.
    */
    if (!use_cache && l_is_password) {
        for (ddi_iter it = list.begin(); it != list.end(); ++it) {
            status = (*it)->Download_Content(folder, internet);
            if (x_Trap_Opt(!x_Is_Success(status)))
                goto cleanup_exit;
            }

        /* It's possible that some downloads were screwed up due to the
            servers acting weirdly. If so, they were added to a failed list,
            so try them again
        */
        Retry_Failed_Downloads(internet);
        }

    /* Read it in and process it
    */
    for (ddi_iter it = list.begin(); it != list.end(); ++it) {
        status = (*it)->Read_Content(folder);
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }

    /* Process all our stuff
    */
    for (ddi_iter it = list.begin(); it != list.end(); ++it) {
        status = (*it)->Process();
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }
    for (single_iter it = singles.begin(); it != singles.end(); ++it) {
        status = (*it)->Process();
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }

    /* Post-process all our stuff - this requires it to have been output first,
        and puts finishing touches on everything
    */
    for (ddi_iter it = list.begin(); it != list.end(); ++it) {
        status = (*it)->Post_Process(folder);
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }
    for (single_iter it = singles.begin(); it != singles.end(); ++it) {
        status = (*it)->Post_Process(folder);
        if (x_Trap_Opt(!x_Is_Success(status)))
            goto cleanup_exit;
        }

    /* Output our languages to the temporary folder, so we can append
        extensions to them later
    */
    status = Finish_Document(doc_languages, folder, LANGUAGE_FILENAME);
    if (!x_Is_Success(status))
        goto cleanup_exit;

    /* Now append any fixup extensions that are needed to compensate for the
        data being terrible
    */
    Append_Extensions(folder, output_folder);

    /* Load the old "powers" XML document and try and copy any wizard powers
        out of it
    */
//We don't need to do this any more, but keep the code around just in case...
//    Fixup_Wizard_Powers(output_folder);

    /* Sources and weapon properties don't need any extensions, so they can go
        directly into the output folder - plus they're augmentation files,
        which aren't messed with anyway
    */
    status = Finish_Document(doc_sources, output_folder, SOURCE_FILENAME);
    if (!x_Is_Success(status))
        goto cleanup_exit;
    status = Finish_Document(doc_wepprops, output_folder, WEPPROP_FILENAME);
    if (!x_Is_Success(status))
        goto cleanup_exit;

    /* wrapup everything
    */
cleanup_exit:
    l_language_root = NULL;
    if (doc_languages != NULL)
        XML_Destroy_Document(doc_languages);
    l_wepprop_root = NULL;
    if (doc_wepprops != NULL)
        XML_Destroy_Document(doc_wepprops);
    l_source_root = NULL;
    if (doc_sources != NULL)
        XML_Destroy_Document(doc_sources);
    if (internet != NULL)
        WWW_Close_Server(internet);

    /* Delete everything in our folder if required
    */
    if (is_clear) {
        strcpy(path_ptr,"*.*");
        FileSys_Delete_Files(folder);
        *path_ptr = '\0';
        }

    x_Status_Return(status);
}