Esempio n. 1
0
int main(int argc, char** argv){
  int wordVecDim = 50;
  int paragraphVecDim = 50;
  int contextSize = 5;
  double learningRate = 0.025;
  int numNegative = 5;
  int minFreq = 10;
  int iteration = 1;
  int numThreads = 1;
  double shrink = 0.0;
  std::string input = "INPUT.txt";
  std::string output = "OUTPUT";

  Utils::procArg(argc, argv,
		 wordVecDim, paragraphVecDim, contextSize, learningRate, numNegative, minFreq, iteration, numThreads,
		 input, output);

  Vocabulary voc(wordVecDim, contextSize, paragraphVecDim);

  voc.read(input, minFreq);
  shrink = learningRate/iteration;

  for (int i = 0; i < iteration; ++i){
    printf("Iteration %2d (current learning rate: %f)\n", i+1, learningRate);
    voc.train(input, learningRate, shrink, numNegative, numThreads);
    learningRate -= shrink;
  }

  voc.save(output+".bin");
  //voc.wordKnn(10);
  voc.outputParagraphVector(output+".pv");
  voc.outputWordVector(output+".wv");

  return 0;
}
Esempio n. 2
0
void RunObjectness(CStr &resName, double base, int W, int NSS, int numPerSz)
{
	srand((unsigned int)time(NULL));
	DataSetVOC voc("../VOC2007/");
	voc.loadAnnotations();
	//voc2007.loadDataGenericOverCls();

	printf("Dataset:`%s' with %d training and %d testing\n", _S(voc.wkDir), voc.trainNum, voc.testNum);
	printf("%s Base = %g, W = %d, NSS = %d, perSz = %d\n", _S(resName), base, W, NSS, numPerSz);
	
	Objectness objNess(voc, base, W, NSS);

	vector<vector<Vec4i> > boxesTests;
	//objNess.getObjBndBoxesForTests(boxesTests, 250);

	//If running this for the first time, set preloadModel to false.
	//Although it is not tested, ensure that the model is generated by
	//the getObjBndBoxesForTestsFast function and not
	//the getObjBndBoxesForTests function which uses colour information too.

	//To avoid running out of memory, you can load images only during
	//prediction by setting preloadImages to false.

	bool preloadModel = true, preloadImages = false;
	objNess.getObjBndBoxesForTestsFast(boxesTests, numPerSz, preloadModel, preloadImages);
	objNess.getRandomBoxes(boxesTests);

	objNess.evaluatePerClassRecall(boxesTests, resName, numPerSz);
	objNess.illuTestReults(boxesTests);
}
Esempio n. 3
0
SuperSample::SuperSample():width(2),height(2)
{
	scanline=false;
	alpha_aware=true;
	Layer::Vocab voc(get_param_vocab());
	Layer::fill_static(voc);
}
void
OrbLocationRecognition::setup(const std::string& vocFilename)
{
    m_frameTags.clear();
    m_frames.clear();

    OrbVocabulary voc(vocFilename);
    m_db.setVocabulary(voc);
}
BofSearchManager::BofSearchManager(QString folderPath) : folderPath(folderPath)
{
    std::cout << "Building / loading vocabulary..\n";

    // Read vocabulary from desk
    imdb::vocabulary voc(folderPath, 3000);
	vocab = voc.centers;

    std::cout << "Building / loading index..\n";

    // Indexing
    std::string tf = "video_google", idf = "video_google";
    _tf  = imdb::make_tf(tf);
    _idf = imdb::make_idf(idf);
	index.prepare(folderPath, voc);
}
Esempio n. 6
0
  void SearchUtil::load_vocabulary() {
    Configs* config = Configs::createInstance();
    Inverted inv;
    stringstream filename;
    filename << config->VOCABULARY_DIRECTORY << config->VOCABULARY_FILENAME;
    ifstream voc(filename.str(), ios::in);
    cout << filename.str() << endl;

    if(voc.is_open()) {
      string word;
      unsigned long key;

      while (voc >> word >> key)
        config->vocabulary_p[word] = key;
      voc.close();
     /* for (auto i = config->vocabulary_p.begin(); i != config->vocabulary_p.end(); ++i)
        cout << i->first << ", " << i->second << endl;*/
    }
Esempio n. 7
0
void RunObjectness(CStr &resName, double base, double intUionThr, int W, int NSS, int numPerSz)
{
	srand((unsigned int)time(NULL));
	//DataSetVOC voc("../../DataSet/VOC2007/"); // BING Training
	DataSetVOC voc("../../DataSet/VOC2007/", true, true); // Personness Training
	//DataSetVOC voc("../../DataSet/VOC2012/", true, true); // Personness Test
	voc.loadAnnotations();
	//voc.loadDataGenericOverCls();

	printf("Dataset:`%s' with %d training and %d testing\n", _S(voc.wkDir), voc.trainNum, voc.testNum);
	printf("%s Base = %g, intUionThr = %g, W = %d, NSS = %d, perSz = %d\n", _S(resName), base, intUionThr, W, NSS, numPerSz);
	
	Objectness objNess(voc, base, intUionThr, W, NSS);

	vector<vector<Vec4i>> boxesTests;
	//objNess.getObjBndBoxesForTests(boxesTests, 250);
	objNess.getObjBndBoxesForTestsFast(boxesTests, numPerSz);
	//objNess.getRandomBoxes(boxesTests);
	//objNess.evaluatePerClassRecall(boxesTests, resName, 1000);
	objNess.illuTestReults(boxesTests);
	//objNess.chammoru_test();
}
Esempio n. 8
0
void loopClosing3d(const BoWFeatures &features)
{    
    int OFFSET = I_OFFSET;
    double SANITY_THRESHOLD = SANITY;
    double MATCH_THRESHOLD = SOGLIA_3D;
    int SIZE_BUCKET = 7;
    int TEMP_CONS = 5;
    bool loop_found = false;

    if (!DEBUG) { wait(); }
    vector<int> bucket;
    vector<double> xs, ys;
    
    readPoseFile((dataset_sub+"syncPCDGT.txt").c_str(), xs, ys);
    cout << "3D: Acquisizione Ground Truth" << endl;
    ofstream report("report_3d.rep");
    
    DUtilsCV::GUI::tWinHandler winplot = "Traiettoria3D";
    
    DUtilsCV::Drawing::Plot::Style normal_style(2); // thickness
    DUtilsCV::Drawing::Plot::Style loop_style('r', 2); // color, thickness
    
    DUtilsCV::Drawing::Plot implot(240, 320,
                                   - *std::max_element(xs.begin(), xs.end()),
                                   - *std::min_element(xs.begin(), xs.end()),
                                   *std::min_element(ys.begin(), ys.end()),
                                   *std::max_element(ys.begin(), ys.end()), 25);
    
    
    NarfVocabulary voc(filename_voc_3d);
    NarfDatabase db(voc, false);
    
    for (int i=0;i<files_list_3d.size();i++){
        loop_found = false;
        if ((i+1)>OFFSET){
            BowVector v1, v2;
            voc.transform(features[i], v1);
            voc.transform(features[i-1], v2);
            double san =  voc.score(v1,v2);
            cout << "S:" << san << endl;
            if (san >= SANITY_THRESHOLD){
                QueryResults ret;
                db.query(features[i], ret,db.size());
                for (int j = 0; j < ret.size(); j++){ //scansiono risultati
                    if (ret[j].Score > MATCH_THRESHOLD){ //sanity check
                        if ((i - OFFSET) >= ret[j].Id){ //scarto la coda
                            if (bucket.size() < SIZE_BUCKET){
                                bucket.push_back(ret[j].Id);
                                cout << i <<"-> bucket: " << ret[j].Id<<endl;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                ret.clear();
                if (bucket.size()>0){
                    cout << "---- TEMPORAL CONSISTENCY {"<<i<< "} ----" << endl;
                    vector<int> i_back; //contiene le precedenti
                    
                    for(int yyy = 0; yyy < TEMP_CONS; yyy++){
                        i_back.push_back((i-(yyy+1)));
                    }                    
                    BowVector v1, v2;
                    for (int aa = 0 ; aa < bucket.size(); aa++){//per ogni elemento del bucket        
                        
                        double max_score = 0;
                        int max_id = -1;                    
                        int centro = -1;
                        
                        for (int cc = 0; cc<i_back.size();cc++){                            
                            voc.transform(features[i - (cc+1)],v1);                            
                            if (centro == -1){ centro = bucket[aa]; }          

                            for(int bb = (centro - (TEMP_CONS/2) - 1) ; bb < centro + (TEMP_CONS/2); bb++){
                                int cursore = bb + 1;
                                
                                if (cursore < 0) {continue;}
                                voc.transform(features[cursore],v2);
                                double score = voc.score(v1,v2);
                                cout << i - (cc+1) << " vs " << cursore << " score: " << score << endl;
                                if (score > MATCH_THRESHOLD && score > max_score){
                                    max_id = cursore;
                                    max_score = score;
                                }               
                            }
                            if (max_id == -1){
                                bucket[aa] = -1; 
                                centro = -1;
                                max_score = 0;                               
                            }else{
                                centro = max_id;
                                max_score = 0;
                                max_id = -1;
                            }
                        }
                    }
                }
                bucket.erase(std::remove( bucket.begin(), bucket.end(),-1), bucket.end());
                double maxInliers = numeric_limits<double>::max();
                double maxIdInliers = -1;
                double tyu = 0;
                if(bucket.size() == 1){
                    maxIdInliers = bucket[0];
                }else{    
                    #pragma omp parallel for
                    for(int yy = 0; yy < bucket.size(); yy++){  
                        BowVector v1,v2;
                        tyu = reg_3D->getCentroidDiff(i,bucket[yy]);
                        cout << "score: " << tyu <<endl;
                        if (maxInliers > tyu){
                            maxInliers = tyu;
                            maxIdInliers = bucket[yy];
                        }                        
                    }                
                }
                if(maxIdInliers != -1){
                    loop_found = true;
                    cout << "LOOP TROVATO : " << i <<" per immagine: " << maxIdInliers << endl;
                    implot.line(-xs[maxIdInliers], ys[maxIdInliers], -xs[i], ys[i], loop_style);
                }
                bucket.clear();
                if(loop_found)
                {
                    string ii,maxid;
                    ii = boost::lexical_cast<string>(i);
                    maxid = boost::lexical_cast<string>(maxIdInliers);
                    report << i <<":"<< maxIdInliers<<endl;
                    report.flush();
                }
            }
        }
        db.add(features[i]);
        implot.line(-xs[i-1], ys[i-1], -xs[i], ys[i], normal_style);
        DUtilsCV::GUI::showImage(implot.getImage(), true, &winplot, 10);        
    }
    report.close();
    stats* owl = new stats("report_3d.rep",registro_interno,OFFSET,"3D");
    cout << owl->toString();
}
Esempio n. 9
0
void bingQdpmRocTest(vector<string> &dirs,
					 int windowLimit = -1, double timeLimitMs = -1, float ratioThreshold = -1)
{
	size_t imageCount = 0;
	size_t personCount = 0;
	size_t matchCount = 0;
	vector<ScoreTp> pScores;
	TickMeter tm;
	vector<std::string>::const_iterator it = dirs.begin();
	char buf[512];

	for (; it != dirs.end(); it++) {
		string dir = *it;
		DataSetVOC voc(dir, true, true);
		voc.loadAnnotations();
		const size_t testNum = voc.testSet.size();
		const char *imgPath =_S(voc.imgPathW);

		// Objectness
		double base = 2;
		double intUionThr = 0.5;
		int W = 8;
		int NSS = 2;

#ifdef WINDOW_GUESS
		Objectness objNess(voc, base, intUionThr, W, NSS);

		objNess.loadTrainedModel(TRAIN_MODEL);
#endif

		// LSVM DPM
		string dpmPersonModel = "../ExtraData/latentsvmXml/person.xml";
		vector<string> models;
		models.push_back(dpmPersonModel);
		QUniLsvmDetector detector(models);
		float overlapThreshold = 0.2f;

		if (ratioThreshold > 0)
			detector.setRatioThreshold(ratioThreshold);

		printf("%d: \n", testNum);
		for (int i = 0; i < testNum; i++) {
			const vector<Vec4i> &boxesGT = voc.gtTestBoxes[i];
			const size_t gtNumCrnt = boxesGT.size();
			if (gtNumCrnt <= 0)
				continue;

			imageCount++;
			personCount += gtNumCrnt;

			Mat image = imread(format(imgPath, _S(voc.testSet[i])));
			if (image.ptr() == NULL) {
				fprintf(stderr, "No JPG Image !\n");
				exit(1);
			}

			int numPerSz = 130;
			ValStructVec<float, Vec4i> boxes;
			double preObj = tm.getTimeMilli();
			double objTime = 0.;

#ifdef WINDOW_GUESS // window guess
			tm.start();
			objNess.getObjBndBoxes(image, boxes, numPerSz);
			tm.stop();
			objTime = tm.getTimeMilli() - preObj;
#endif

			double localTimeLimitMs = timeLimitMs;
			if (timeLimitMs > 0) {
				localTimeLimitMs -= objTime;
				if (localTimeLimitMs < 0.)
					localTimeLimitMs = 0.;
			}

			vector<QRect> searchBoxes;
			if (windowLimit > 0) {
				for (int j = 0; j < (int)boxes.size() && j < windowLimit; j++) {
					const Vec4i &bb = boxes[j];
					QRect rt(bb[0], bb[1], bb[2], bb[3]);
					searchBoxes.push_back(rt);
				}
			} else {
				for (int j = 0; j < (int)boxes.size(); j++) {
					const Vec4i &bb = boxes[j];
					QRect rt(bb[0], bb[1], bb[2], bb[3]);
					searchBoxes.push_back(rt);
				}
			}

			tm.start();
			detector.setup(image, overlapThreshold, localTimeLimitMs);
			tm.stop();

			vector<FeatureMapCoord> ftrMapCoords;
#ifdef WINDOW_GUESS
			detector.cvtBox2FtrMapCoord(&searchBoxes, &ftrMapCoords);
#else
			detector.genFullFtrMapCoord(&ftrMapCoords);

			preObj = tm.getTimeMilli();
			tm.start();
#ifdef SHUFFLE_WINDOW
			random_shuffle(ftrMapCoords.begin(), ftrMapCoords.end());
#endif
			tm.stop();
			double randGenTime = tm.getTimeMilli() - preObj;

			if (localTimeLimitMs > 0 && localTimeLimitMs - preObj >= 0.)
					detector.setTimeLimit(localTimeLimitMs - preObj);
#endif

			vector<QUniLsvmDetector::ObjectDetection> detections;
			vector<vector<FeatureMapCoord> *> fmcss;
			fmcss.push_back(&ftrMapCoords);
			tm.start();
			detector.detect(detections, fmcss);
			tm.stop();

			vector<DetectedInfo> di(detections.size());
			vector<int> gtIdx(gtNumCrnt, -1);

			int detectCount = 0;
			for (size_t j = 0; j < detections.size(); j++) {
				const QUniLsvmDetector::ObjectDetection& od = detections[j];

				if (od.score < RECOMMENDABLE_THRESHOLD)
					continue;

				detectCount++;
				Vec4i bb(od.rect.x + 1, od.rect.y + 1, od.rect.x + od.rect.width, od.rect.y + od.rect.height);

				// score matchScore for the ROC curve
				double maxMatchScore = 0;
				int maxMatchId = -1;
				for (int k = 0; k < gtNumCrnt; k++) {
					double matchScore = DataSetVOC::interUnio(bb, boxesGT[k]);
					if (matchScore > maxMatchScore) {
						maxMatchScore = matchScore;
						maxMatchId = k;
					}
				}

				uchar match = maxMatchScore > 0.5 ? 1 : 0;
				if (match) {
					int preDetectedIdx = gtIdx[maxMatchId];
					if (preDetectedIdx >= 0) {
						if (maxMatchScore > di[preDetectedIdx].matchScore) {
							di[preDetectedIdx].matched = false;
							gtIdx[maxMatchId] = int(j);
							di[j].matchScore = maxMatchScore;
							di[j].matched = true;
						}
					} else {
						gtIdx[maxMatchId] = int(j);
						di[j].matchScore = maxMatchScore;
						di[j].matched = true;
					}
				}

#ifdef SAVE_IMAGE_RESULT
				// save the result image
				char buf[256];
				sprintf(buf, "%2f", od.score);
				Point pt(max((bb[2] + bb[0] - 85) / 2, 0), (bb[1] + bb[3]) / 2);
				putText(image, buf, pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(255), 3, CV_AA);
				putText(image, buf, pt, FONT_HERSHEY_SIMPLEX, 0.5, Scalar::all(0), 1, CV_AA);
				rectangle(image, od.rect, cv::Scalar(0, 255, 0), 2);
#endif
			}

			for (size_t j = 0; j < detectCount; j++) { // detections are sorted in descending order
				const QUniLsvmDetector::ObjectDetection& od = detections[j];
				if (di[j].matched)
					matchCount++;
				pScores.push_back(ScoreTp(od.score, di[j].matched));
			}

#ifdef SAVE_IMAGE_RESULT
			imwrite((voc.testSet[i] + "_DpmResult.png").c_str(), image);
#endif
			printf("%d ", i + 1);
		}
		printf("\n");
	}
	printf("BingQdpmRocTest time = %f sec\n", tm.getTimeSec());
	printf("GT %d, Matched %d/%d \n", personCount, matchCount, pScores.size());

	// Calculate log-average miss rate
	stable_sort(begin(pScores), end(pScores),
		[](const ScoreTp &p1, const ScoreTp &p2) { return p1.first > p2.first; });

	vector<float> fp(pScores.size());
	for (size_t i = 0; i < fp.size(); i++)
		fp[i] = !pScores[i].second;

	vector<float> tp(pScores.size());
	tp[0] = pScores[0].second;
	for (size_t i = 1; i < tp.size(); i++)
		tp[i] = tp[i - 1] + pScores[i].second;
	for (size_t i = 0; i < tp.size(); i++)
		tp[i] /= personCount;

	for (size_t i = 1; i < fp.size(); i++)
		fp[i] += fp[i - 1];
	for (size_t i = 0; i < fp.size(); i++)
		fp[i] /= imageCount;

	sprintf(buf, "%s%03d_%03.fms_6137gt_%04dtp_%04ddt_%.0fs.m",
		METHOD_NAME, max(windowLimit, 0), timeLimitMs, matchCount, pScores.size(), tm.getTimeSec());
	FILE *matlabFile = fopen(buf, "w");
	printVector(matlabFile, tp, "tp");
	printVector(matlabFile, fp, "fp");

	char *matlabContent = "tp = tp'; fp = fp';\n"
		"addpath(genpath('d:/81_dataset/03_Caltech/piotr_toolbox/')); savepath;\n"
		"xs1=[-inf; fp];\n"
		"ys1=[0; tp];\n"
		"ref=10.^(-2:.25:0);\n"
		"lims=[3.1e-4 1e1 .5 1];\n"
		"m=length(ref);\n"
		"for i=1:m\n"
		"\tj=find(xs1<=ref(i));\n"
		"\tmiss(i)=ys1(j(end));\n"
		"end\n"
		"miss=exp(mean(log(max(1e-10,1-miss))));\n"
		"show=figure();\n"
		"plotRoc([fp tp],'logx',1,'logy',1,'xLbl','fppi',...\n"
		"\t'lims',lims,'color','g','smooth',1,'fpTarget',ref);\n"
		"title(sprintf('log-average miss rate = %.2f%%',miss*100));\n"
		"savefig(['MORU' 'Roc'],show,'png');\n";
	fwrite(matlabContent, strlen(matlabContent), 1, matlabFile);

	fclose(matlabFile);
}
void
OrbLocationRecognition::setup(const std::string& vocFilename,
                              const SparseGraphConstPtr& graph,
                              const cv::Mat& matchingMask)
{
    m_frameTags.clear();
    m_frames.clear();

    std::vector<bool> cameraFlags(matchingMask.rows);
    for (int i = 0; i < matchingMask.rows; ++i)
    {
        cameraFlags.at(i) = (cv::countNonZero(matchingMask.row(i)) > 0);
    }

    OrbVocabulary voc(vocFilename);
    m_db.setVocabulary(voc);

    // build vocabulary tree
    std::vector<std::vector<DVision::ORB::bitset> > features;

    for (size_t segmentId = 0; segmentId < graph->frameSetSegments().size(); ++segmentId)
    {
        const FrameSetSegment& segment = graph->frameSetSegment(segmentId);

        for (size_t frameSetId = 0; frameSetId < segment.size(); ++frameSetId)
        {
            const FrameSetPtr& frameSet = segment.at(frameSetId);

            for (size_t frameId = 0; frameId < frameSet->frames().size(); ++frameId)
            {
                const FramePtr& frame = frameSet->frames().at(frameId);

                if (frame.get() == 0)
                {
                    continue;
                }

                if (!cameraFlags.at(frame->cameraId()))
                {
                    continue;
                }

                FrameTag tag;
                tag.frameSetSegmentId = segmentId;
                tag.frameSetId = frameSetId;
                tag.frameId = frameId;

                m_frameTagMap.insert(std::make_pair(tag, m_frameTagMap.size()));
                m_frameTags.push_back(tag);
                m_frames.push_back(frame);

                features.push_back(frameToFeatures(frame));
            }
        }
    }

    for (size_t i = 0; i < features.size(); ++i)
    {
        m_db.add(features.at(i));
    }
}
Esempio n. 11
0
int main()
{
	// Dataset Voc
	string dir = "../DataSet/VOC2012/";
	// string dir = "../DataSet/VOC2007/";
	DataSetVOC voc(dir, false, true);
	voc.loadAnnotations();
	const size_t testNum = voc.testSet.size();
	const char* imgPath =_S(voc.imgPathW);

	// LSVM DPM
	std::string dpmPersonModel = "../ExtraData/latentsvmXml/person.xml";
	std::vector<std::string> models;
	models.push_back(dpmPersonModel);
	QUniLsvmDetector detector(models);
	float overlapThreshold = 0.2f;

	size_t imageCount = 0;
	size_t personCount = 0;
	size_t matchCount = 0;
	vector<ScoreTp> pScores;
	TickMeter tm;
	for (int i = 0; i < testNum; i++){
		const vector<Vec4i> &boxesGT = voc.gtTestBoxes[i];
		const size_t gtNumCrnt = boxesGT.size();
		if (gtNumCrnt <= 0)
			continue;

		imageCount++;
		personCount += gtNumCrnt;

		Mat image = imread(format(imgPath, _S(voc.testSet[i])));

		tm.start();
		vector<QUniLsvmDetector::ObjectDetection> detections;
		detector.setup(image, overlapThreshold);
		// No threading, nearly original LSVM
		vector<FeatureMapCoord> ftrMapCoords;
		vector<vector<FeatureMapCoord> *> fmcss;
		fmcss.push_back(&ftrMapCoords);
		detector.genFullFtrMapCoord(&ftrMapCoords);
		detector.detect(detections, fmcss);
		tm.stop();

		vector<DetectedInfo> di(detections.size());
		vector<int> gtIdx(gtNumCrnt, -1);

		int detectCount = 0;
		for (size_t j = 0; j < detections.size(); j++) {
			const QUniLsvmDetector::ObjectDetection& od = detections[j];

			if (od.score < RECOMMENDABLE_THRESHOLD)
				continue;

			detectCount++;
			Vec4i bb(od.rect.x + 1, od.rect.y + 1, od.rect.x + od.rect.width, od.rect.y + od.rect.height);

			// score matchScore for the ROC curve
			double maxMatchScore = 0;
			int maxMatchId = -1;
			for (int k = 0; k < gtNumCrnt; k++) {
				double matchScore = DataSetVOC::interUnio(bb, boxesGT[k]);
				if (matchScore > maxMatchScore) {
					maxMatchScore = matchScore;
					maxMatchId = k;
				}
			}

			uchar match = maxMatchScore > 0.5 ? 1 : 0;
			if (match) {
				int preDetectedIdx = gtIdx[maxMatchId];
				if (preDetectedIdx >= 0) {
					if (maxMatchScore > di[preDetectedIdx].matchScore) {
						di[preDetectedIdx].matched = false;
						gtIdx[maxMatchId] = int(j);
						di[j].matchScore = maxMatchScore;
						di[j].matched = true;
					}
				} else {
					gtIdx[maxMatchId] = int(j);
					di[j].matchScore = maxMatchScore;
					di[j].matched = true;
				}
			}
		}

		for (size_t j = 0; j < detectCount; j++) {
			const QUniLsvmDetector::ObjectDetection& od = detections[j];
			if (di[j].matched)
				matchCount++;
			pScores.push_back(ScoreTp(od.score, di[j].matched));
		}

#ifdef SAVE_YML
		vector<Vec4i> newBoxesGT;
		for (size_t j = 0; j < gtIdx.size(); j++) {
			if (gtIdx[j] < 0)
				continue;

			newBoxesGT.push_back(boxesGT[j]);
		}

		if (newBoxesGT.size() > 0) {
			// name
			// h, w
			string name = _S(voc.testSet[i]);
			writePersonYml(name, image.rows, image.cols, newBoxesGT);
		}
#endif
	}
	printf("QdpmRocTest time = %f sec\n", tm.getTimeSec());
	printf("GT %d, Matched %d/%d \n", personCount, matchCount, pScores.size());

	// Calculate log-average miss rate
	stable_sort(begin(pScores), end(pScores),
		[](const ScoreTp &p1, const ScoreTp &p2) { return p1.first > p2.first; });

	vector<float> fp(pScores.size());
	for (size_t i = 0; i < fp.size(); i++)
		fp[i] = !pScores[i].second;

	vector<float> tp(pScores.size());
	tp[0] = pScores[0].second;
	for (size_t i = 1; i < tp.size(); i++)
		tp[i] = tp[i - 1] + pScores[i].second;
	for (size_t i = 0; i < tp.size(); i++)
		tp[i] /= personCount;

	for (size_t i = 1; i < fp.size(); i++)
		fp[i] += fp[i - 1];
	for (size_t i = 0; i < fp.size(); i++)
		fp[i] /= imageCount;

	FILE *matlabFile = fopen("drawLAMR.m", "w");
	printVector(matlabFile, tp, "tp");
	printVector(matlabFile, fp, "fp");

	char *matlabContent = "tp = tp'; fp = fp';\n"
		"addpath(genpath('d:/81_dataset/03_Caltech/piotr_toolbox/')); savepath;\n"
		"xs1=[-inf; fp];\n"
		"ys1=[0; tp];\n"
		"ref=10.^(-2:.25:0);\n"
		"lims=[3.1e-4 1e1 0. 1];\n"
		"m=length(ref);\n"
		"for i=1:m\n"
		"\tj=find(xs1<=ref(i));\n"
		"\tmiss(i)=ys1(j(end));\n"
		"end\n"
		"miss=exp(mean(log(max(1e-10,1-miss))));\n"
		"show=figure();\n"
		"plotRoc([fp tp],'logx',1,'logy',1,'xLbl','fppi',...\n"
		"\t'lims',lims,'color','g','smooth',1,'fpTarget',ref);\n"
		"title(sprintf('log-average miss rate = %.2f%%',miss*100));\n"
		"savefig(['MORU' 'Roc'],show,'png');\n";
	fwrite(matlabContent, strlen(matlabContent), 1, matlabFile);

	fclose(matlabFile);

	return 0;
}
Esempio n. 12
0
void Town::depositWithdrawl(int choice) {
	Party &party = *_vm->_party;
	Screen &screen = *_vm->_screen;
	Sound &sound = *_vm->_sound;
	int gold, gems;

	if (choice) {
		gold = party._bankGold;
		gems = party._bankGems;
	} else {
		gold = party._gold;
		gems = party._gems;
	}

	for (uint idx = 0; idx < _buttons.size(); ++idx)
		_buttons[idx]._sprites = &_icons2;
	_buttons[0]._value = Common::KEYCODE_o;
	_buttons[1]._value = Common::KEYCODE_e;
	_buttons[2]._value = Common::KEYCODE_ESCAPE;

	Common::String msg = Common::String::format(Res.GOLD_GEMS,
		Res.DEPOSIT_WITHDRAWL[choice],
		XeenEngine::printMil(gold).c_str(),
		XeenEngine::printMil(gems).c_str());

	screen._windows[35].open();
	screen._windows[35].writeString(msg);
	drawButtons(&screen._windows[35]);
	screen._windows[35].update();

	sound.stopSound();
	File voc("coina.voc");
	bool flag = false;

	do {
		switch (townWait()) {
		case Common::KEYCODE_o:
			flag = false;
			break;
		case Common::KEYCODE_e:
			flag = true;
			break;
		case Common::KEYCODE_ESCAPE:
			break;
		default:
			continue;
		}
		
		if ((choice && !party._bankGems && flag) ||
			(choice && !party._bankGold && !flag) ||
			(!choice && !party._gems && flag) ||
			(!choice && !party._gold && !flag)) {
			party.notEnough(flag, choice, 1, WT_2);
		} else {
			screen._windows[35].writeString(Res.AMOUNT);
			int amount = NumericInput::show(_vm, 35, 10, 77);

			if (amount) {
				if (flag) {
					if (party.subtract(true, amount, choice, WT_2)) {
						if (choice) {
							party._gems += amount;
						} else {
							party._bankGems += amount;
						}
					}
				} else {
					if (party.subtract(false, amount, choice, WT_2)) {
						if (choice) {
							party._gold += amount;
						} else {
							party._bankGold += amount;
						}
					}
				}
			}

			if (choice) {
				gold = party._bankGold;
				gems = party._bankGems;
			} else {
				gold = party._gold;
				gems = party._gems;
			}

			sound.playSound(voc);
			msg = Common::String::format(Res.GOLD_GEMS_2, Res.DEPOSIT_WITHDRAWL[choice],
				XeenEngine::printMil(gold).c_str(), XeenEngine::printMil(gems).c_str());
			screen._windows[35].writeString(msg);
			screen._windows[35].update();
		}
		// TODO
	} while (!_vm->shouldQuit() && _buttonValue != Common::KEYCODE_ESCAPE);

	for (uint idx = 0; idx < _buttons.size(); ++idx)
		_buttons[idx]._sprites = &_icons1;
	_buttons[0]._value = Common::KEYCODE_d;
	_buttons[1]._value = Common::KEYCODE_w;
	_buttons[2]._value = Common::KEYCODE_ESCAPE;
}