typename softmax<T>::EigenMat softmax<T>::
get_ground_truth(int NumClass, int samples_size,
                 std::map<int, int> const &unique_labels,
                 std::vector<int> const &labels) const
{
    EigenMat ground_truth = EigenMat::Zero(NumClass, samples_size);
    for(size_t i = 0; i != ground_truth.cols(); ++i){
        auto it = unique_labels.find(labels[i]);
        if(it != std::end(unique_labels)){
            ground_truth(it->second, i) = 1;
        }
    }

    return ground_truth;
}
int main(int argc, char** argv) {
  int total_test_number = 10, successes = 0;
  float values_thresholds[10] = { 1, 2, 0, 4, -3, 4, 2, 3, 1, 100 };
  char buffer[1024];
  int i;
  for(i = 0; i < total_test_number; ++i) {
    printf("Test number %d out of %d\n", i + 1, total_test_number);

    sprintf(buffer, "data/source_mat_%d.txt", i);
    Mat* source_mat = Mat_load(buffer);
    printf("src ");
    Mat_print(source_mat);

    printf("Create a list containing matrix values lower than %f\n",
	   values_thresholds[i]);

    TipoSCL expected_list = ground_truth(source_mat, values_thresholds[i]);
    printf("expected ");
    TipoSCL_print(expected_list);

    TipoSCL output_list = lowerValues(source_mat, values_thresholds[i]);
    printf("output   ");
    TipoSCL_print(output_list);

    int cmp = TipoSCL_compare(expected_list, output_list);
    if(cmp > 0) {
      printf("SUCCESS\n");
      successes++;
    }
    else {
      printf("FAILURE\n");
    }
    printf("Current success rate: %0.02f%%\n",
	   (float)(successes) * 100.0f/ (float)(total_test_number));
    printf("\n*************************************************\n\n");

    Mat_free(source_mat);
    TipoSCL_free(expected_list);
    TipoSCL_free(output_list);
  }

  printf("FINAL SUCCESS RATE: %0.02f%%\n",
	 (float)(successes) * 100.0f / (float)(total_test_number));

  return 0;
}
Exemple #3
0
int main (int argc, char* argv[])
{
    ApplicationsLib::LogogSetup logog_setup;

    std::vector<std::string> keywords;
    keywords.push_back("-ALL");
    keywords.push_back("-MESH");
    keywords.push_back("-LOWPASS");

    if (argc < 3)
    {
        INFO(
            "Moves mesh nodes and connected elements either by a given value "
            "or based on a list.\n");
        INFO("Usage: %s <msh-file.msh> <keyword> [<value1>] [<value2>]",
             argv[0]);
        INFO("Available keywords:");
        INFO(
            "\t-ALL <value1> <value2> : changes the elevation of all mesh "
            "nodes by <value2> in direction <value1> [x,y,z].");
        INFO(
            "\t-MESH <value1> <value2> : changes the elevation of mesh nodes "
            "based on a second mesh <value1> with a search range of <value2>.");
        INFO(
            "\t-LOWPASS : applies a lowpass filter over node elevation using "
            "directly connected nodes.");
        return EXIT_FAILURE;
    }

    const std::string msh_name(argv[1]);
    const std::string current_key(argv[2]);
    std::string const ext (BaseLib::getFileExtension(msh_name));
    if (!(ext == "msh" || ext == "vtu"))
    {
        ERR("Error: Parameter 1 must be a mesh-file (*.msh / *.vtu).");
        INFO("Usage: %s <msh-file.gml> <keyword> <value>", argv[0]);
        return EXIT_FAILURE;
    }

    bool is_keyword(false);
    for (auto & keyword : keywords)
        if (current_key.compare(keyword)==0)
        {
            is_keyword = true;
            break;
        }

    if (!is_keyword)
    {
        ERR("Keyword not recognised. Available keywords:");
        for (auto const& keyword : keywords)
            INFO("\t%s", keyword.c_str());
        return EXIT_FAILURE;
    }

    std::unique_ptr<MeshLib::Mesh> mesh (MeshLib::IO::readMeshFromFile(msh_name));
    if (mesh == nullptr)
    {
        ERR ("Error reading mesh file.");
        return 1;
    }

    // Start keyword-specific selection of nodes

    // moves the elevation of all nodes by value
    if (current_key.compare("-ALL")==0)
    {
        if (argc < 5)
        {
            ERR("Missing parameter...");
            return EXIT_FAILURE;
        }
        const std::string dir(argv[3]);
        unsigned idx = (dir.compare("x") == 0) ? 0 : (dir.compare("y") == 0) ? 1 : 2;
        const double value(strtod(argv[4],0));
        INFO("Moving all mesh nodes by %g in direction %d (%s)...", value, idx,
             dir.c_str());
        //double value(-10);
        const std::size_t nNodes(mesh->getNumberOfNodes());
        std::vector<MeshLib::Node*> nodes (mesh->getNodes());
        for (std::size_t i=0; i<nNodes; i++)
        {
            (*nodes[i])[idx] += value;
        }
    }

    // maps the elevation of mesh nodes according to a ground truth mesh whenever nodes exist within max_dist
    if (current_key.compare("-MESH")==0)
    {
        if (argc < 5)
        {
            ERR("Missing parameter...");
            return EXIT_FAILURE;
        }
        const std::string value (argv[3]);
        double max_dist(pow(strtod(argv[4],0), 2));
        double offset (0.0); // additional offset for elevation (should be 0)
        std::unique_ptr<MeshLib::Mesh> ground_truth (MeshLib::IO::readMeshFromFile(value));
        if (ground_truth == nullptr)
        {
            ERR ("Error reading mesh file.");
            return EXIT_FAILURE;
        }

        const std::vector<MeshLib::Node*>& ground_truth_nodes (ground_truth->getNodes());
        GeoLib::AABB bounding_box(ground_truth_nodes.begin(), ground_truth_nodes.end());
        MathLib::Point3d const& min(bounding_box.getMinPoint());
        MathLib::Point3d const& max(bounding_box.getMaxPoint());

        const std::size_t nNodes(mesh->getNumberOfNodes());
        std::vector<MeshLib::Node*> nodes (mesh->getNodes());

        for (std::size_t i=0; i<nNodes; i++)
        {
            bool is_inside (containsPoint(*nodes[i], min, max));
            if (is_inside)
            {
                int idx = find_closest_point(nodes[i], ground_truth_nodes, max_dist);
                if (idx>=0)
                    (*nodes[i])[2] = (*(ground_truth_nodes[idx]))[2]-offset;
            }
        }
    }

    // a simple lowpass filter for the elevation of mesh nodes using the elevation of each node
    // weighted by 2 and the elevation of each connected node weighted by 1
    if (current_key.compare("-LOWPASS")==0)
    {
        const std::size_t nNodes(mesh->getNumberOfNodes());
        std::vector<MeshLib::Node*> nodes (mesh->getNodes());

        std::vector<double> elevation(nNodes);
        for (std::size_t i=0; i<nNodes; i++)
            elevation[i] = (*nodes[i])[2];

        for (std::size_t i=0; i<nNodes; i++)
        {
            const std::vector<MeshLib::Node*> conn_nodes (nodes[i]->getConnectedNodes());
            const unsigned nConnNodes (conn_nodes.size());
            elevation[i] = (2*(*nodes[i])[2]);
            for (std::size_t j=0; j<nConnNodes; ++j)
                elevation[i] += (*conn_nodes[j])[2];
            elevation[i] /= (nConnNodes+2);
        }

        for (std::size_t i=0; i<nNodes; i++)
            (*nodes[i])[2] = elevation[i];
    }
    /**** add other keywords here ****/

    std::string const new_mesh_name (msh_name.substr(0, msh_name.length() - 4) + "_new.vtu");
    if (MeshLib::IO::writeMeshToFile(*mesh, new_mesh_name) != 0)
        return EXIT_FAILURE;

    INFO ("Result successfully written.")
    return EXIT_SUCCESS;
}
Exemple #4
0
//Main function
int main ( int argc, char *argv[] )
{
	
	//---  VARIABLES ---//
	//saving database descriptors
	cv::Mat training_descriptors;
	//for measuring processing time
	clock_t t;	
	// --- ---//
	std::cout << std::endl;
	std::cout << "+++ BOW FOR DATA SET +++" << std::endl;
	std::cout << TRAIN_PATH << std::endl;

	//--- DESCRIPTORS EXTRACTION ---//
	std::string train_path = TRAIN_PATH;
	//read descriptors from file
	std::cout << "*** TRAIN DESCRIPTORS INFO ***" << std::endl;
	cv::FileStorage fstore_descrip(DESCRIP_MAT_NAME, cv::FileStorage::READ);
	std::cout << "No Documents: " << (int)fstore_descrip["noDocuments"] << std::endl;
	std::cout << "No Classes: " << (int)fstore_descrip["noClasses"] << std::endl;
	std::cout << "No total descriptors: " << (int)fstore_descrip["totalDescriptors"] << std::endl;
	std::cout << "No max desrcriptors in an image: " << (int)fstore_descrip["maxDescriptors"] << std::endl;
	std::cout << "Descriptors processing time: " << (float)fstore_descrip["procTime"] << std::endl;
	std::cout << std::endl;
	fstore_descrip["matDescriptors"] >> training_descriptors;
	fstore_descrip.release();
	

	//--- BUILD A DICTIONARY ---//
	cv::TermCriteria tc(CV_TERMCRIT_ITER,100,0.001);
	int cluster_attempts = 1;
	int dictionary_size = atoi(argv[1]);
	std::cout << "*** BOW DICTIONARY INFO ***" << std::endl;
	std::cout << "Dictionary size: " << dictionary_size << std::endl; 
	cv::BOWKMeansTrainer bowTrainer(dictionary_size,tc,cluster_attempts, cv::KMEANS_PP_CENTERS);

	bowTrainer.add(training_descriptors);
	t = clock();
	cv::Mat my_dictionary = bowTrainer.cluster();
	t = clock()-t;
	std::cout << "Dictionary processing time:" << std::endl;
	std::cout << t << " clicks " << ((float)t)/CLOCKS_PER_SEC << " seconds" << std::endl;
	std::cout << std::endl;
	//--- ---//

	//--- NAIVE BAYES FOR CLASSIFICATION ---//
	cv::NormalBayesClassifier nb_classifier;
	cv::Mat training_data(0,dictionary_size,CV_32FC1);
	cv::Mat labels(0,1,CV_32FC1);

	//set the dictionary to bow descriptor extractor
	bowDE.setVocabulary(my_dictionary);

	std::cout << "*** CLASSIFIER TRAINING ***" << std::endl;
	bow_encode(fs::path(train_path),training_data,labels);
	// +++ for debugging - can  be commented +++//
	std::cout << training_data.size() << " * " << labels.size() << std::endl;
	if(training_data.type() == CV_32FC1)
	{std::cout << "training data matrix accepted" << std::endl;}
	if(labels.type() == CV_32FC1)
	{std::cout << "labels matrix accepted" << std::endl;}
	// +++ +++ //

	t = clock();
	nb_classifier.train(training_data,labels,cv::Mat(),cv::Mat(),false);
	t = clock() - t;
	nb_classifier.save("nbModel_flavia_leaves_a.yml","nbModel_flavia_leaves_a");
	std::cout << " Training processing time:" << std::endl;
	std::cout << t << " clicks " << ((float)t)/CLOCKS_PER_SEC << " seconds" << std::endl;
	std::cout << std::endl;
	
	//if you already have a classifier uncomment the next line and comment the all the
	//Classifier Training section
	//nb_classifier.load("nbModel_flavia_leaves_b.yml","nbModel_flavia_leaves_b");
	//std::cout << "Classfier model loaded"<< std::endl;

	//--- ---//

	//--- BOW ENCODING OF TEST SET AND EVALUATION ---//
	cv::Mat ground_truth(0,1,CV_32FC1);
	cv::Mat eval_data(0,dictionary_size,CV_32FC1);
	cv::Mat results;
	std::string test_path = TEST_PATH;
	double accuRate = 0.;

	std::cout << "*** CLASSIFIER EVALUATION ***" << std::endl;
	bow_encode(fs::path(test_path),eval_data,ground_truth);
	t = clock();
	nb_classifier.predict(eval_data,&results);	
	t = clock()-t;
	std::cout << " Classifier evaluation time:" << std::endl;
	std::cout << t << " clicks " << ((float)t)/CLOCKS_PER_SEC << " seconds" << std::endl;

	accuRate = 1. -( (double) cv::countNonZero(ground_truth - results) / eval_data.rows);
	std::cout << "Accuracy rate: " << accuRate << std::endl;
	std::cout << "Classifier Results" << std::endl;
	std::cout << results << std::endl << std::endl;
	
	

	return 0;
}				/* ----------  end of function main  ---------- */
Exemple #5
0
ground_truth CbirGVT::GetGvtImagesManyNew(const vector<size_t>& idxv,
					  const vector<size_t>& nnv,
					  size_t nobj,
					  const ground_truth& allowed) {
  string msg = "CbirGVT::GetGvtImagesMany() : ";

  if (!idxv.size())
    return ground_truth();

  if (idxv.size()!=nnv.size()) {
    ShowError(msg+"vector dimensions differ");
    return ground_truth();
  }

  GetDataBase()->WriteLog(msg+"starting with "+ToStr(idxv.size())+" samples");

  vector<size_t> idxvres;
  vector<int>    nnvres;
  vector<string> image_url_vec;
  map<size_t,size_t> idx2nn;

  multimap<size_t,size_t> retmap;

  size_t nallow = 0;
  for (size_t a=0; a<idxv.size(); a++) {
    bool hit = false;
    vector<size_t> cres = FindCache(idxv[a], nnv[a], hit);
    if (hit) {
      cout << msg << "a=" << a << " idx=" << idxv[a] << " nn=" << nnv[a]
	   << " cache hit, returning " << ToStr(cres.size()) << " images"
	   << endl;

      for (size_t i=0; i<cres.size(); i++) {
	size_t idx = cres[i];
	bool allow = allowed[idx];
	nallow += allow;
	if (debug>2)
	  cout << " i=" << i << " index=" << idx << " allow=" << allow << endl;
	if (allow)
	  retmap.insert(make_pair(i, idx));
      }

      continue;
    }
    idxvres.push_back(idxv[a]);
    nnvres.push_back(nnv[a]);
    idx2nn[idxv[a]] = nnv[a];

    map<string,string> oi = GetDataBase()->ReadOriginsInfo(idxv[a],
							   false, false);
    string image_url = oi["url"];

    if (image_url=="")
      ShowError(msg+"image URL not resolved for image #"+ToStr(idxv[a]));

    image_url_vec.push_back(image_url);
  }

  GetDataBase()->WriteLog(msg+"found "+ToStr(nallow)+" images in the cache,"
			  " continuing with "+ToStr(nnvres.size())+" samples");

  if (nnvres.size()) {
    string access_token;
    ImageCollectionServiceSoapBindingProxy *imageCollection =
      (ImageCollectionServiceSoapBindingProxy*)GetGvtImagesCommon(access_token);
    if (!imageCollection)
      return ground_truth();  

    string collection_name = "b12n";

    gvt__imageSimilarityUrls imageSimilarity_payloads;
    imageSimilarity_payloads.CollectionId = &collection_name;
    imageSimilarity_payloads.maxResults = nnvres;
    imageSimilarity_payloads.imageUrl = image_url_vec;
    gvt__imageSimilarityUrlsResponse imageSimilarity_responses;

    // imageSimilarityUrls(collectionId, string[] imageUrls, int[] numResults);
    if (imageCollection->imageSimilarityUrls(&imageSimilarity_payloads,
					     &imageSimilarity_responses)
	== SOAP_OK) {
      GetDataBase()->WriteLog(msg+"ending");

      gvt__imageSimilarityResult *imageSimilarity_result
	= imageSimilarity_responses.return_;
      if (debug>1)
	cout << *(imageSimilarity_result->message) << endl;
      vector<gvt__imageSimilarityId*> &similar_images
	= imageSimilarity_result->results;
      vector<gvt__imageSimilarityId*>::iterator it = similar_images.begin();

      float prevsim = 0.0;
      size_t idxx = 0, nnx = 0;

      size_t j = 0;
      for (;it < similar_images.end(); it++) {
	gvt__imageSimilarityId *imageSimilarityId = *it;

	bool set_idxx = false;
	if (imageSimilarityId->similarity>prevsim)
	  set_idxx = true;
	prevsim = imageSimilarityId->similarity;

	if (debug>2)
	  cout << *(imageSimilarityId->imageId) << "\t"
	       << imageSimilarityId->similarity;
	bool ok = false;
	string uin = *imageSimilarityId->imageId, u = uin;
	size_t p = u.find("static.flickr.com");
	if (p!=string::npos) {
	  p = u.find('/', p);
	  if (p!=string::npos) {
	    p = u.find('/', p+1);
	    u.erase(0, p+1);
	    p = u.find('_');
	    if (p!=string::npos) {
	      u.erase(p);
	      u = string(10-u.size(), '0')+u;
	      int idxr = GetDataBase()->ToIndex(u);
	      if (idxr>=0) {
		if (set_idxx) {
		  idxx = idxr;
		  nnx  = idx2nn[idxx];
		  j = 0;
		}

		bool allow = allowed[idxr];
		nallow  += allow;
		if (debug>2)
		  cout << " j=" << j << " index=" << idxr
		       << " allow=" << allow << endl;
		if (allow)
		  retmap.insert(make_pair(j, idxr));

		ok = true;
		AddCache(idxx, nnx, idxr);

		j++;
	      }
	    }
	  }
	}
	if (debug>2)
	  cout << endl;

	if (!ok && debug) {
	  if (false)
	    ShowError(msg+"failed with <"+uin+"> -> <"+u+">");
	  else
	    cerr << msg+"failed with <"+uin+"> -> <"+u+">" << endl;
	}
      }
    }
    else {
      soap_print_fault(imageCollection, stderr);
    }

    delete imageCollection;
  }

  ground_truth ret(GetDataBase()->Size());

  size_t nretpos = 0;
  for (multimap<size_t,size_t>::const_iterator mi=retmap.begin();
       mi!=retmap.end() && nretpos<nobj; mi++) {
    if (debug>2)
      cout << " checking " << mi->first << " " << mi->second << " "
	   << (int)ret[mi->second] << " " << nretpos << endl;
    nretpos += ret[mi->second]!=1;
    ret[mi->second] = 1;
  }

  if (debug)
    cout << msg << "returning " << nretpos << " images from total of "
	 << nallow << " found" << endl;

  return ret;
}
Exemple #6
0
ground_truth CbirGVT::GetGvtImagesOneByOne(size_t idx, size_t nn) {
  string msg = "CbirGVT::GetGvtImagesOneByOne("+ToStr(idx)+","+ToStr(nn)+") : ";

  ground_truth ret(GetDataBase()->Size());

  bool hit = false;
  vector<size_t> cres = FindCache(idx, nn, hit);
  if (hit) {
    cout << msg << "cache hit, returning " << ToStr(cres.size()) << " images"
	 << endl;

    for (size_t i=0; i<cres.size(); i++)
      ret[i] = 1;

    return ret;
  }

  string access_token;

  ImageCollectionServiceSoapBindingProxy *imageCollection =
    (ImageCollectionServiceSoapBindingProxy*)GetGvtImagesCommon(access_token);
  if (!imageCollection)
    return ground_truth();  

  string collection_name = "b12n";

  GetDataBase()->WriteLog(msg+"starting");

  size_t nretpos = 0;
  map<string,string> oi = GetDataBase()->ReadOriginsInfo(idx, false, false);
  string image_url = oi["url"];

  gvt__imageSimilarityUrl imageSimilarity_payload;
  imageSimilarity_payload.CollectionId = &collection_name;
  imageSimilarity_payload.maxResults = nn;
  imageSimilarity_payload.imageUrl = &image_url;
  gvt__imageSimilarityUrlResponse imageSimilarity_response;

  if (imageCollection->imageSimilarityUrl(&imageSimilarity_payload,
					  &imageSimilarity_response)
      == SOAP_OK) {
    GetDataBase()->WriteLog(msg+"ending");

    gvt__imageSimilarityResult *imageSimilarity_result
      = imageSimilarity_response.return_;
    if (debug>1)
      cout << *(imageSimilarity_result->message) << endl;
    vector<gvt__imageSimilarityId*> &similar_images
      = imageSimilarity_result->results;
    vector<gvt__imageSimilarityId*>::iterator it = similar_images.begin();

    for (;it < similar_images.end(); it++) {
      gvt__imageSimilarityId *imageSimilarityId = *it;
      if (debug>2)
	cout << *(imageSimilarityId->imageId) << "\t"
	     << imageSimilarityId->similarity << endl;
      bool ok = false;
      string uin = *imageSimilarityId->imageId, u = uin;
      size_t p = u.find("static.flickr.com");
      if (p!=string::npos) {
	p = u.find('/', p);
	if (p!=string::npos) {
	  p = u.find('/', p+1);
	  u.erase(0, p+1);
	  p = u.find('_');
	  if (p!=string::npos) {
	    u.erase(p);
	    u = string(10-u.size(), '0')+u;
	    int idxr = GetDataBase()->ToIndex(u);
	    if (idxr>=0) {
	      nretpos++;
	      ret[idxr] = 1;
	      ok = true;
	      AddCache(idx, nn, idxr);
	    }
	  }
	}
      }
      if (!ok && debug) {
	if (false)
	  ShowError(msg+"failed with <"+uin+"> -> <"+u+">");
	else
	  cerr << msg+"failed with <"+uin+"> -> <"+u+">" << endl;
      }
    }
  }
  else {
    soap_print_fault(imageCollection, stderr);
  }

  delete imageCollection;

  if (debug)
    cout << msg << "returning " << nretpos << " images" << endl;

  return ret;
}