Exemplo n.º 1
0
/*
Open the output file, initialize the output stream, and return the file's
length. If reload is true, first truncate any preexisting file
*/
unsigned long Download::openfile(char *url, bool reload, ofstream &fout, char *name)
{
    char fname[MAX_FILENAME_SIZE];

    if(!getfname(url, fname))
        throw DLExc("File name error");

    for(int i = 0; i < 5 && (!fout.is_open() || !fout); ++i)
    {
         if(!reload)
            fout.open(fname, ios::binary | ios::out | ios::app | ios::ate);
        else
            fout.open(fname, ios::binary | ios::out | ios::trunc);

         if(!fout.is_open() || !fout)
         {
            char buff[MAX_FILENAME_SIZE];
            strcpy(buff, fname);
            sprintf(fname, "%s-%u", buff, time(0)-i);
            fout.clear();
         }
    }

    if(!fout)
        throw DLExc("Could not open TEMP file!");

    strcpy(name, fname);

    // get current file length
    return fout.tellp();
}
Exemplo n.º 2
0
void figure()
{
	int i;

	/*fout.open("E:\\data\\KSP\\Fat-tree\\bn-B\\4.txt");
	fout.clear();
	fout.close();
	fout.open("E:\\data\\KSP\\Fat-tree\\bw-B\\1.txt");
	fout.clear();
	fout.close();*/
	fout.open("E:\\data\\KSP\\Fat-tree\\suc-B\\1.txt");
	fout.clear();
	fout.close();

	/*fout.open("E:\\data\\KSP\\Fat-tree\\bn-B\\4.txt",ios::app);
	for(i=1;i<=cycle;i++)
		fout<<bn_array[i]<<" ";
	fout.close();

	fout.open("E:\\data\\KSP\\Fat-tree\\bw-B\\1.txt",ios::app);
	for(i=1;i<=cycle;i++) 
		fout<<bw_array[i]<<" ";
	fout.close();*/

	fout.open("E:\\data\\KSP\\Fat-tree\\suc-B\\1.txt",ios::app);
	for(i=1;i<=cycle;i++)
		fout<<double(suc_array[i])/(times-1)<<" "; //times会增长到6
	fout.close();
}
Exemplo n.º 3
0
int Towers_sm(int disks, int arr1[], int arr2[], int count, bool &ppart, ofstream &fout, ofstream &outfile)
{
	int split;
   	int split_res;
   	int remaining;
 	int remaining_res;
 	int result;
 	int diskssofar;
 	int smallest_so_far;

	for(diskssofar = 1; diskssofar < count; diskssofar++)
	{
		arr2[diskssofar - 1] = 2*(diskssofar) - 1;
		ppart = true;
	}
		
 	if(diskssofar >= count)
 	{
 		for(int a = diskssofar; a <= disks; a++)
		{
			//Resetting "smallest_so_far"
			smallest_so_far = INT_MAX;

			for(split = 1; split < diskssofar; split++)
			{
				remaining = diskssofar - split;
				split_res = arr2[split - 1];

				remaining_res = arr1[remaining - 1];
				result = 2*(split_res) + remaining_res;

				//Only update "smallest_so_far" if "result" is lower
				if(result <= smallest_so_far)
					smallest_so_far = result;
			}
			//Setting the used array to "smallest_so_far"
			arr1[a-1] = smallest_so_far;
			ppart = false;
		}
 	}

 	cout << "The array is: ";
	outfile << "The array is: ";
 	for (int g = 0; g < disks; g++)
 	{
		cout << arr2[g] << " ";
		fout << arr2[g] << " ";
		outfile << arr2[g] << " ";
	}
	cout << endl;
	outfile << endl;

	//Setting the writting stream cursor back to the beginning
	fout.clear();
	fout.seekp(0);

	return arr2[disks - 1];
}
Exemplo n.º 4
0
void a::fileopenbinary(ofstream &out, const string &filename, Error &error) {
  out.clear();
  out.open(filename.c_str(),ios::binary);
  if (!out) {
    error.addwarning(2,15,"Misc",
                     "Could not open "+string(filename)+" for output!");
    error.writewarnings();
  }
}
Exemplo n.º 5
0
void a::fileopen(ofstream &out, const char *filename, Error &error) {
  out.clear();
  out.open(filename);
  if (!out) {
    error.addwarning(2,15,"Misc",
                     "Could not open "+string(filename)+" for output!");
    error.writewarnings();
  }
}
Exemplo n.º 6
0
void ReadAlignChunk::chunkFstreamCat (fstream &chunkOut, ofstream &allOut, bool mutexFlag, pthread_mutex_t &mutexVal){
    chunkOut.flush();
    chunkOut.seekg(0,ios::beg);
    if (mutexFlag) pthread_mutex_lock(&mutexVal);
    allOut << chunkOut.rdbuf();
    allOut.clear();
    if (mutexFlag) pthread_mutex_unlock(&mutexVal);
    chunkOut.clear();
    chunkOut.seekp(0,ios::beg); //set put pointer at the beginning
};
Exemplo n.º 7
0
string promptUserForFile(ofstream & stream, string prompt) {
   while (true) {
      cout << prompt;
      string filename;
      getline(cin, filename);
      openFile(stream, filename);
      if (!stream.fail()) return filename;
      stream.clear();
      cout << "Unable to open that file.  Try again." << endl;
      if (prompt == "") prompt = "Output file: ";
   }
}
Exemplo n.º 8
0
void figure()
{
	int i;

	fout.open("E:\\data\\N-bn\\bottleneck3.txt");
	fout.clear();
	fout.close();
	fout.open("E:\\data\\N-suc\\success3.txt");
	fout.clear();
	fout.close();

	fout.open("E:\\data\\N-bn\\bottleneck3.txt",ios::app);
	for(i=0;i<cycle;i++) //(N=1;N<=20;N++)
		fout<<bn[i]<<" ";
	fout.close();

	fout.open("E:\\data\\N-suc\\success3.txt",ios::app);
	for(i=0;i<cycle;i++) //(N=1;N<=20;N++)
		fout<<double(success[i])/(times-1)<<" "; //times-1是因为for循环多加了1
	fout.close();
}
Exemplo n.º 9
0
void setup_debug(int level, const string &filename, const string& prefix)
{
    string fname = filename;
    debug_level = level;
    logfile_prefix = prefix;
    logfile_filename = filename;

    if ( logfile_file.is_open() )
        logfile_file.close();
    ostream *output = 0;
    if ( filename.length() ) {
	logfile_file.clear();
        logfile_file.open( filename.c_str(), fstream::out | fstream::app );
#ifdef __linux__
        if (fname[0] != '/') {
            char buf[256];
            if (getcwd(buf, sizeof(buf))) {
                fname.insert(0, "/");
                fname.insert(0, buf);
            }
        }
        setenv("SEGFAULT_OUTPUT_NAME", fname.c_str(), false);
#endif
        output = &logfile_file;
    } else
        output = &cerr;

#ifdef __linux__
    (void) dlopen("libSegFault.so", RTLD_NOW | RTLD_LOCAL);
#endif

    if ( debug_level & Debug )
        logfile_trace = output;
    else
        logfile_trace = &logfile_null;

    if ( debug_level & Info )
        logfile_info = output;
    else
        logfile_info = &logfile_null;

    if ( debug_level & Warning )
        logfile_warning = output;
    else
        logfile_warning = &logfile_null;

    if ( debug_level & Error )
        logfile_error = output;
    else
        logfile_error = &logfile_null;

    signal( SIGHUP, reset_debug );
}
Exemplo n.º 10
0
int main(int argc,char *argv[])
{
    string name,oname;
    int i;

    //char ts1[16] = "0.trace";
    //char ts2[12] = "0.symbol";
    //char ts3[10] = "1";


    if (argc != 4)
    {
        cout<<"Usage: trace2symbol inputfile outputfile $n\n"<<endl;
        return 0;
    }

    name.assign(argv[1]);
    //name.assign(ts1);
    oname.assign(argv[2]);
    //oname.assign(ts2);
    for (i=0; i<atoi(argv[3]); i++)
        //for (i=0;i<atoi(ts3);i++)
    {
        fin.open(name.c_str());

        if (fin.fail())
        {
            cout<<"Bad file name!\n"<<endl;
            return 0;
        }

        fout.open(oname.c_str());

        cout<<"Trace2Symbol(V1.0) "<<endl;

        cout << "Dealing with " << name << "...";

        work();

        fin.close();
        fout.close();
        fin.clear();
        fout.clear();

        cout << "Done." << endl;
        name=nextName(name);
        oname=nextName(oname);
    }
    return 0;
}
Exemplo n.º 11
0
bool openFile( const string fname, ofstream &fobj )
   {
   // vars 
   bool success = false;

   // clear and open
   fobj.clear();
   fobj.open(fname.c_str());

   // check for file opening success
   if( fobj.good() )
     {
     success = true;
     }   

   // return success state
   return success;
   }
Exemplo n.º 12
0
//Modify file content function
bool modelA::modifyContFile(ofstream mdfos,unsigned int startPos,unsigned int endPos,string newContent)
{
	if(endPos<startPos)
		return false;
	else
	{
		//Move ofstream pointer to end position 
		mdfos.seekp(endPos,ios_base::beg);
		//Delete old content
		for(int i=0;i<int(endPos-startPos);i++)
			mdfos.put(char(8));
		//Write new content
		mdfos<<newContent<<flush;
		//Exit and go to begin
		mdfos.clear();
		mdfos.seekp(0,ios_base::beg);
	}

	return true;
}
Exemplo n.º 13
0
BOOL CMultithreadDlg::Cls_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) 
{
	hList = GetDlgItem(hwnd, IDC_LIST1);
	InitializeCriticalSection(&our_section);

	sec_time = clock(); // начальное время
	HANDLE th1 = CreateThread(NULL, 0, Thread3, (LPVOID)0, 0, NULL);
	HANDLE th2 = CreateThread(NULL, 0, Thread4, (LPVOID)1, 0, NULL);
	HANDLE th3 = CreateThread(NULL, 0, Thread_file, (LPVOID)1, 0, NULL);

	WaitForSingleObject(th1, INFINITE);
	WaitForSingleObject(th2, INFINITE);
	WaitForSingleObject(th3, INFINITE);

	unsigned int end_time_2 = clock(); // конечное время
	sec_time = end_time_2 - sec_time; // искомое время

	SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)(to_wstring(sec_time).c_str()));

	sec_time = clock(); // начальное время
	fout_2.clear();
	Thread5(0);

	end_time_2 = clock(); // конечное время
	sec_time = end_time_2 - sec_time; // искомое время

	SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)(to_wstring(sec_time).c_str()));
	fout_3.close();
	//sec_time = clock(); // начальное время
	//HANDLE th3 = CreateThread(NULL, 0, Thread5, (LPVOID)0, 0, NULL);

	//WaitForSingleObject(th3, INFINITE);

	//end_time_2 = clock(); // конечное время
	//sec_time = end_time_2 - sec_time; // искомое время

	//SendMessage(hList, LB_ADDSTRING, 0, (LPARAM)(to_wstring(sec_time).c_str()));
	//CreateThread(NULL, 0, Thread_main, (LPVOID)2, 0, NULL);
	return TRUE;
}
Exemplo n.º 14
0
  Log() {
    n = 0;
    done = false;

    output.open(LOG_FILE);
    if (!output.is_open()) {
      output.copyfmt(cout);
      output.clear(cout.rdstate());
      output.basic_ios<char>::rdbuf(cout.rdbuf());
    }

    logStartTime = chrono::high_resolution_clock::now();
    t = thread([&]() {

      Report report;
      while (!done) {
        for (int i = 0; i < NUMBER_OF_QUEUES; ++i)
          while (queue[i].pop(report))  // XXX change to if to avoid starvation?
            priority.push(report);

        double now = chrono::duration_cast<chrono::duration<double>>(
            chrono::high_resolution_clock::now() - logStartTime).count();
        while ((!priority.empty()) && ((now - priority.top().time) > 0.5)) {
          output << priority.top().text << endl;
          priority.pop();
        }

        usleep(WAIT_MICROSECONDS);
      }

      for (int i = 0; i < NUMBER_OF_QUEUES; ++i)
        while (queue[i].pop(report))
          priority.push(report);

      while (!priority.empty()) {
        output << priority.top().text << endl;
        priority.pop();
      }
    });
  }
Exemplo n.º 15
0
int main(int argc,char *argv[])
{
  string nameIn;

  if (argc != 4) {
    cout << "Usage: combine inputfile outputfile $n" << endl << endl;
    return 0;
  }

  nameIn.assign(argv[1]);

  for (int i=0;i<atoi(argv[3]);i++) {
    input_is.open(nameIn.c_str());

    if (input_is.fail()) {
      cout << "Bad file name: [" << nameIn << "]!" << endl << endl;
      return 0;
    }

    cout << "Combine(V2.0)" << endl;
    cout << "Reading " << nameIn << "...";

    readfile();

    input_is.close();
    input_is.clear();

    cout << "Done." << endl;
    nameIn=nextName(nameIn);
  }

  res_os.open(argv[2]);
  work();

  res_os.close();
  res_os.clear();

  return 0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[]) {
	string inputfile_name;
	string outputfile_name;

	if (argc != 4) {
		cout << "Usage: combine inputfile outputfile $n\n" << endl;
		return 0;
	}

	inputfile_name.assign(argv[1]);
	outputfile_name.assign(argv[2]);

	fin.open(argv[1]);
	fout.open(argv[2]);
	num_procs = boost::lexical_cast<int>(argv[3]);

	if (fin.fail()) {
		cout << "Bad file name: [" << inputfile_name << "]!\n" << endl;
		return 0;
	}

	fout << preamble();

	populate_func_map();

	work();

	fin.close();
	fin.clear();

	fout << postamble();


	fout.close();
	fout.clear();

	return 0;
}
Exemplo n.º 17
0
void OpenFiles (ifstream &Inp, ofstream &Out)
{
   char Fname[255];

   do
   {
      cout << "Input file name: " << flush;
      cin.getline(Fname, 255);
      Inp.clear();
	  Inp.open(Fname, ios::in); //Inp.open(Fname, ios::in|ios::nocreate);
	  if (Inp.fail())
         cout << "Failed to open " << Fname << " --- try again\n";
   } while ( Inp.fail() );

   do
   {
      cout << "Output file name:  " << flush;
      cin.getline(Fname, 255);
      Out.clear();
      Out.open(Fname);
      if (Out.fail())
         cout << "Failed to open hw2output.txt  " << Fname << " --- try again\n";
   } while ( Out.fail() );
}
Exemplo n.º 18
0
int KiCadSCH::patchFile(ofstream &oFile)
{
    string iline, oline, last_oline;
    modiFile_t currentpatch;
    int line_n;
    unsigned i;
    unsigned olineNbr = 0;

    iSCHfile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    oFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);

    try{
        last_oline = "";
        for(line_n=0; true; line_n++){
            getline(iSCHfile, iline);
            oline = iline;
            currentpatch.add = false;
            currentpatch.del = false;
            currentpatch.line = "";
            currentpatch.lineNbr = 0;
            for(i=0;i<patchvec.size();i++){
                if(line_n == patchvec[i].lineNbr){
                    currentpatch = patchvec[i];
                    patchvec[i].prevline = last_oline;
                    if(currentpatch.add){
                        oFile << currentpatch.line << endl;
                        olineNbr++;
                        patchvec[i].olineNbr = olineNbr;
                    }
                }
            }
            if(!currentpatch.del){
                oFile << oline << endl;
                last_oline = oline;
                olineNbr++;
                if(patchvec.size()>i){ // if patchvec is empty
                    patchvec[i].olineNbr = olineNbr;
                }
            }else{
                if(patchvec.size()<i) patchvec[i].deletedline = oline;
            }
        }
    }
    catch(std::fstream::failure e){
        if(iSCHfile.bad()) return -1;
        if(oFile.bad()) return -2;
        if(iSCHfile.fail()) return -1;
        if(oFile.fail()) return -2;
        if(iSCHfile.eof()){
            iSCHfile.clear();
            iSCHfile.seekg(0, ios::beg);
            return 0;
        }
        if(oFile.eof()) {
            oFile.clear();
            return -2;
        }
        return -255;
    }
    return 0;
}
Exemplo n.º 19
0
int Towers_lg(int disks, int count, int arr2[], int arr3[], bool &ppart, ifstream &infile, ofstream & outfile, ofstream &fout)
{
	int even = count%2;
	int totres;
	int split;
   	int split_res;
   	int remaining;
 	int remaining_res;
 	int result;
 	int smallest_so_far;
 	int disks1;

	//Setting in reading stream cursor back to the beginning
	infile.clear();
	infile.seekg(0);


	for(disks1 = 1; disks1 < count; disks1++)
 	{
 		arr2[disks1 - 1] = 2*(disks1) - 1;
 		arr3[disks1 - 1] = 2*(disks1) - 1;
 	}

	//If the number of disks is equal to or less than the number of pegs, then calculate based on 2n-1
	if(disks < count)
	{
		cout << "The array is: ";
		outfile << "The array is: ";
		if(even == 0)
		{
			for (int g = 0; g < disks; g++)
			{
				cout << arr2[g] << " ";
				outfile << arr2[g] << " ";
				fout << arr2[g] << " ";
			}
			cout << endl;
			outfile << endl;
			//Setting the writting stream cursor back to the beginning
			fout.clear();
			fout.seekp(0);
			//Making sure the reading stream is at the beginning of the file
			infile.clear();
			infile.seekg(0);

			ppart = true;
			return totres = arr2[disks - 1];
		}
		else
		{
			cout << "The array is: ";
			outfile << "The array is: ";
			for (int r = 0; r < disks; r++)
			{
				cout << arr3[r] << " ";
				outfile << arr3[r] << " ";
				fout << arr3[r] << " ";
			}
			cout << endl;
			outfile << endl;

			//Setting the writting stream cursor back to the beginning
			fout.clear();
			fout.seekp(0);

			//Making sure the reading stream is at the beginning of the file
			infile.clear();
			infile.seekg(0);

			ppart = true;
			return totres = arr3[disks - 1];
		}
	}
	else
	{
		while(!infile.eof())
		{
			for(int z = 0; z < disks; z++)
			{
				infile >> arr2[z];
			}
		}
		//Resetting the reading cursor back to the beginning
		infile.clear();
		infile.seekg(0);

		//Setting the first position in the next array
		arr3[0] = 1;
		
		for(int j = 4; j <= count; j++)
		{
			//Resetting "smallest_so_far"
			smallest_so_far = INT_MAX;

			for(split = 1; split < disks1; split++)
			{
				remaining = disks1 - split;
				split_res = arr3[split - 1];

				remaining_res = arr3[remaining - 1];
				result = 2*(split_res) + remaining_res;

				//Only update "smallest_so_far" if "result" is lower
				if(result <= smallest_so_far)
					smallest_so_far = result;
			}
			//Setting the used array to "smallest_so_far"
			arr2[j - 1] = smallest_so_far;
		}
	
		cout << "The array is: ";
		outfile << "The array is: ";
		for (int g = 0; g < disks; g++)
		{
			cout << arr2[g] << " ";
			outfile << arr2[g] << " ";
			fout << arr2[g] << " ";
		}
		cout << endl;
		outfile << endl;

		//Setting the writting stream cursor back to the beginning
		fout.clear();
		fout.seekp(0);

		//Making sure the reading stream is at the beginning of the file
		infile.clear();
		infile.seekg(0);
		
		ppart = false;
	}
	return totres = arr3[disks - 1];
}
Exemplo n.º 20
0
void setup_debug(int level, const string &filename, const string &prefix)
{
    debug_level = level;
    logfile_prefix = prefix;
    logfile_filename = filename;

    if (logfile_file.is_open()) {
        logfile_file.close();
    }

    ostream *output = 0;

    if (filename.length()) {
        logfile_file.clear();
        logfile_file.open(filename.c_str(), fstream::out | fstream::app);
#ifdef __linux__

        string fname = filename;
        if (fname[0] != '/') {
            char buf[PATH_MAX];

            if (getcwd(buf, sizeof(buf))) {
                fname.insert(0, "/");
                fname.insert(0, buf);
            }
        }

        setenv("SEGFAULT_OUTPUT_NAME", fname.c_str(), false);
#endif
        output = &logfile_file;
    } else if( const char* ccache_err_fd = getenv( "UNCACHED_ERR_FD" )) {
        output = ccache_stream( atoi( ccache_err_fd ));
    } else {
        output = &cerr;
    }

#ifdef __linux__
    (void) dlopen("libSegFault.so", RTLD_NOW | RTLD_LOCAL);
#endif

    if (debug_level >= Debug) {
        logfile_trace = output;
    } else {
        logfile_trace = &logfile_null;
    }

    if (debug_level >= Info) {
        logfile_info = output;
    } else {
        logfile_info = &logfile_null;
    }

    if (debug_level >= Warning) {
        logfile_warning = output;
    } else {
        logfile_warning = &logfile_null;
    }

    if (debug_level >= Error) {
        logfile_error = output;
    } else {
        logfile_error = &logfile_null;
    }

    signal(SIGHUP, reset_debug_signal_handler);
}
Exemplo n.º 21
0
int main ()
{
    output.open ("output.txt");
    output.clear ();
	srand (time (0));
	float *A = 0, *b = 0, *c = 0, *d = 0, *B = 0, *x = 0, *xk = 0;
	A = new float [N*N];
	B = new float [N*N];
	b = new float [N];
	c = new float [N];
	d = new float [N];
	x = new float [N];
	xk = new float [N];
	GenMatrix (A, 0);
	for (int i = 0; i < N; i ++)
		A[i*N + i] = rand ()%10001*N + 10000*N;
    output << "Matrix A:";
    Out (A, 0);
	GenMatrix(b, 1);
	output << "Vector b:";
	Out (b, 1);

	fill (&x[0], &x[N-1], 0);
	fill (&xk[0], &xk[N-1], 0);

	float Bnorm = 0;

	for (int i = 0; i < N; i ++) // формирование матрицы B = -D^-1 * (A - D)
	{
		c[i] = b[i] / A[i*N + i];
		for (int j = 0; j < N; j ++)
		{
			if (i == j)
			{
				B[i*N + j] = 0;
			}
			else
			{
				B[i*N + j] = - A[i*N + j] / A[i*N + i];
				Bnorm += B[i*N+j] * B[i*N+j];
			}
		}
	}

	Bnorm = sqrt (Bnorm);

	float Teps = 1;

	while (Teps > eps) // прогон метода
	{
		MultipleMatrixToVector (B, x, d); // очередна¤ итераци¤
		SumMatrixes (d, c, xk, N);
		Teps = Norm (xk, x, N)/(1 - Bnorm); // подсчет погрешности
		iter ++;
        memcpy (x, xk, N*sizeof (float));
	}
	output << "x:";
	Out (x, 1);
	output << "xk:";
	Out (xk, 1);
	MultipleMatrixToVector(A, x, d);
	DifMatrix (d, b, d, N);
	output << "Difference A*xk and b:";
	Out (d, 1);
	output << "Solution:";
	Out (x, 1);
    output.close ();
	return 0;
}
Exemplo n.º 22
0
void processVideo(CMFC_CartoonApp *theApp)
{
	processedFrame = false;
	vector<Rect> vec_rect_facesCascade;
	Mat myFrame = cvQueryFrame(myCap);//frame 指向g_capture指向的AVI文件的当前读入帧

	if (myFrame.empty())//判断是否帧为空  
	{
		cout << "视频文件播放完毕" << endl;
		cout << "nnn " << nnn << endl; 
		theApp->dlg.KillTimer(1);	//停止
		return;
	}
	
	Mat targetImg, originalMat;
	targetImg = myFrame.clone();
	originalMat = myFrame.clone();
	//滚动条
	theApp->dlg.m_slider.SetPos(++pos);


	//绘制人脸检测矩形框
	if(detectFace && grabFlag == false)
	{
		//TFacePosition *FaceArray;
		//HImage hTargetImg;
		//int detectedCount = -1;	//当前帧的人脸数
		//hTargetImg = loadImageFromMat(targetImg);
		//FSDK_FaceTemplate *detectedFaceTemplates = new FSDK_FaceTemplate[20];
		//FaceArray = detectUsingLuxand(hTargetImg, detectedCount, detectedFaceTemplates, NULL);	//检测当前帧的人脸
		//for (int i = 0; i < detectedCount; i++)
		//{
		//	TFacePosition facePosition = FaceArray[i];
		//	rectangle(targetImg, Rect(facePosition.xc - facePosition.w/2, facePosition.yc - facePosition.w/2, facePosition.w, facePosition.w), cvScalar(255, 0, 255), 2);		
		//}
		
		detectCascade(targetImg, cascade1, 1, vec_rect_facesCascade);
		for(int j = 0; j < vec_rect_facesCascade.size(); j++)
		{
			rectangle(targetImg, vec_rect_facesCascade.at(j), cvScalar(255, 0, 255), 2);		
		}
	}

	if (grabFlag == true && vec_FaceCartoons.size() > 0)
	{
		base_test1_str += "pos: " + toString(pos) + "\n";

		//检测是否切换了场景
		if(!preFrame.empty() && !myFrame.empty())
		{
			base_test1 = compareHist1(preFrame, myFrame);	//计算出两帧之间的相似度
			base_test1_str += toString(base_test1) +  "\n";
			cout<<"ffsd  "<<base_test1<<endl;
			if(base_test1 > 6)	//超过阈值,认为切换了场景
			{
				nnn++;
				situationCount = 0;	//切换场景后,统计帧数归零
				selectFace = false;
				vec_formerTemplates.clear();
				//waitKey(0);
				for (int i = 0; i < 20; i++)	//将统计切换场景后,匹配人脸情况的数组清零,重新统计
				{
					changeBackArray[i] = 0;
				}
			}else{
				situationCount++; //没切换场景后,帧数加1
			}
		}
		preFrame = myFrame.clone();	//保存当前帧

		double t,tt,ttt;
		t = (double)cvGetTickCount();
		int detectedCount = -1;	//当前帧的人脸数
		HImage hTargetImg;
		hTargetImg = loadImageFromMat(targetImg);
		/*imwrite("targetImg.jpg", targetImg);
		FSDK_LoadImageFromFile(&hTargetImg, "targetImg.jpg");*/
		FSDK_FaceTemplate *detectedFaceTemplates = new FSDK_FaceTemplate[20];
		TFacePosition *FaceArray;
			
		FaceArray = detectUsingLuxand(hTargetImg, detectedCount, detectedFaceTemplates, NULL);	//检测当前帧的人脸
			
		tt = (double)cvGetTickCount() - t;
		printf("detect time = %g ms\n", tt / ((double)cvGetTickFrequency()*1000.));

		if (detectedCount > 0)	//当前帧有人脸才去进行匹配替换
		{
			//绘制人脸检测矩形框
			if(detectFace)
			{
				for (int i = 0; i < detectedCount; i++)
				{
					TFacePosition facePosition = FaceArray[i];
					rectangle(targetImg, Rect(facePosition.xc - facePosition.w/2, facePosition.yc - facePosition.w/2, facePosition.w, facePosition.w), cvScalar(255, 0, 255), 2);		
				}
			}

			ttt = (double)cvGetTickCount();
			float temp_same_num_all = 0;
			float max_same_num_all = 0;
			int similiestFaceNum_all_cartoon = -1;
			int similiestFaceNum_all_man = -1;
			//从画面所有脸中找出与选定人脸最相似的一张脸
			for(int i = 0; i < vec_FaceCartoons.size(); i++)
			{
				FaceCartoon *faceCartoonObj = vec_FaceCartoons.at(i);
				float temp_same_num = 0;
				float max_same_num = 0;
				int similiestFaceNum = -1;
				for(int j = 0; j < detectedCount; j++)
				{
					for(int k = 0; k < faceCartoonObj->faceTemplates.size(); k++)
					{
						temp_same_num = getSimilarityBetweenTemplate(faceCartoonObj->faceTemplates.at(k), detectedFaceTemplates[j]);
						if(temp_same_num > max_same_num){
							similiestFaceNum = j;
							max_same_num = temp_same_num;
						}
					}

				}
				if(max_same_num > max_same_num_all)
				{
					max_same_num_all = max_same_num;
					similiestFaceNum_all_cartoon = similiestFaceNum;
					similiestFaceNum_all_man = i;
				}
				cout<<"相似度  "<<max_same_num<<endl;
				base_test1_str += "similirity: " + toString(max_same_num) +  "\n";
			}

			base_test1_str += "sitCount: " + toString(situationCount) +  "\n";
			base_test1_str += "sitCartNum: " + toString(situationCartoonNum) +  "\n";

			//场景没切换,已经贴了5帧,则这一帧也贴 //选脸替换的第一个场景,直接贴
			if ((base_test1 <= 6 && situationCartoonNum >= 5) || selectFace)
			{
				//切换场景后,通过前十帧来确定后续要显示的人脸
				//超过10帧,则以后都选取匹配最多的那个FcObj来卡通化
				if(situationCount > 10)	
				{
					base_test1_str += ">10";
					base_test1_str += "\n";
					int mostMatchManNum = 0, maxMatchTime = 0;
					for(int k = 0; k < 20; k++)	//选出前十帧匹配次数最多的那个人
					{
						if(changeBackArray[k] > maxMatchTime)
						{
							mostMatchManNum = k;
							maxMatchTime = changeBackArray[k];
						}
					}
					FaceCartoon *tempFaceObj = vec_FaceCartoons.at(mostMatchManNum);
					tempFaceObj->facePosition =  FaceArray[similiestFaceNum_all_cartoon];
					detect_and_draw(myFrame, *tempFaceObj);

					//如果当前帧的相似度低于阈值,则加入到模板中用于以后匹配
					if(max_same_num_all < threshhold){
						tempFaceObj->faceTemplates.push_back(detectedFaceTemplates[similiestFaceNum_all_cartoon]);
						base_test1_str += "add Temp \n";
					}

					//确定使用哪个FcObj之后,如果之前有未匹配的帧,则将其加入模板
					if(!vec_formerTemplates.empty()){
						base_test1_str += "use former!! \n";
						for(int i = 0; i < vec_formerTemplates.size(); i++){
							tempFaceObj->faceTemplates.push_back(vec_formerTemplates.at(i));
						}
						//使用完之后,清空
						vec_formerTemplates.clear();
					}
				}else{	//小于10帧,则使用当前最相似的那个FcObj
					base_test1_str += "<10";
					base_test1_str += "\n";
					changeBackArray[similiestFaceNum_all_man]++;

					FaceCartoon *faceCartoonObj = vec_FaceCartoons.at(similiestFaceNum_all_man);
					//faceCartoonObj->faceTemplate = detectedFaceTemplates[similiestFaceNum_all_cartoon];

					//为当前FcObj选取一个配对的卡通形象,如果是半自动的,则不会去找,是固定的
					matchCartoonForFcObj(faceCartoonObj, frameCount, base_test1_str);

					double drawTime = (double)cvGetTickCount();
					faceCartoonObj->facePosition =  FaceArray[similiestFaceNum_all_cartoon];
					detect_and_draw(myFrame, *faceCartoonObj);

					//如果当前帧的相似度低于阈值,则加入到模板中用于以后匹配
					if(max_same_num_all < threshhold){
						faceCartoonObj->faceTemplates.push_back(detectedFaceTemplates[similiestFaceNum_all_cartoon]);
						base_test1_str += "add temp \n";
					}
							
					printf("draw time = %g ms\n", ((double)cvGetTickCount() - drawTime) / ((double)cvGetTickFrequency()*1000.));
				}
				situationCartoonNum++;
			}else if((base_test1 > 6 || base_test1 == -1) || (situationCount < 10 ) || (base_test1 <= 6 && situationCartoonNum < 5 && situationCount < 20)){	//场景切换了 //选择第一个人脸 //该场景前10帧 //场景没切换,场景前20帧中贴图小于10帧
				cout<<"没吊用!"<<endl;
				if(base_test1 > 6 || base_test1 == -1){	 //场景切换了	//选择第一个人脸 
					situationCartoonNum = 0;
				}
					
				if(max_same_num_all > threshhold)	//如果当前帧人脸相似度超过阈值,则贴图
				{
					changeFlag = true;
					changeBackArray[similiestFaceNum_all_man]++;

					FaceCartoon *faceCartoonObj = vec_FaceCartoons.at(similiestFaceNum_all_man);
					//faceCartoonObj->faceTemplate = detectedFaceTemplates[similiestFaceNum_all_cartoon];

					//为当前FcObj选取一个配对的卡通形象
					matchCartoonForFcObj(faceCartoonObj, frameCount, base_test1_str);

					double drawTime = (double)cvGetTickCount();
					faceCartoonObj->facePosition =  FaceArray[similiestFaceNum_all_cartoon];
					detect_and_draw(myFrame, *faceCartoonObj);

					printf("draw time = %g ms\n", ((double)cvGetTickCount() - drawTime) / ((double)cvGetTickFrequency()*1000.));
					situationCartoonNum++;
				}else{	//不相似则当前帧不贴图
					changeFlag = false;

					//保存该帧模板
					vec_formerTemplates.push_back(detectedFaceTemplates[similiestFaceNum_all_cartoon]);
					base_test1_str += "add to former \n";
				}
			}else if(base_test1 <= 6 && !changeFlag){	//场景没切换,上一帧没贴图
				base_test1_str += "enter: " + toString(38) + "\n";
			}
			base_test1_str += "changeFlag: " + toString((double)changeFlag)  + "\n";
			base_test1_str += "simi: " + toString(simiAuto) + "\n";

			t = (double)cvGetTickCount() - t;
			totalTime = t / ((double)cvGetTickFrequency()*1000.);
			base_test1_str += "totalTime: " + toString(totalTime) + "\n";
			if(drawStringFlag)
				drawString(myFrame, base_test1_str);

			ttt = (double)cvGetTickCount() - ttt;
			printf("similarity time = %g ms\n", ttt / ((double)cvGetTickFrequency()*1000.));
				
			//显示这个最像的人脸
			//Rect faceRegionRect = getROIFromTFacePosition(targetImg, FaceArray[similiestFaceNum]);
			//Mat selected_faceImg(targetImg, faceRegionRect);
			//imshow("检测出的人脸", selected_faceImg);
		}
		base_test1_str = "";	//清空参数表
		FSDK_FreeImage(hTargetImg);
		free(detectedFaceTemplates);

	}
	
	if (theApp->dlg.key_esc) {	//如果按下Esc键中断   
		theApp->dlg.key_esc = false;
		theApp->dlg.KillTimer(1);
		if(saveSelectedTemplates)	//清空和关闭输出流
		{
			fout.clear();
			fout.close();
		}
		return;
	}else if (theApp->dlg.key_space){	//按下空格键取消卡通化操作
		theApp->dlg.key_space = false;
		if(grabFlag)
		{
			grabFlag = false;
		}else{
			grabFlag = true;
		}
			
	}
	else if (theApp->dlg.key_enter){
		theApp->dlg.KillTimer(1);	//暂停
		cout << "按了enter" << endl;
		judge_Image = myFrame.clone();
		int grabReturn = grab(originalMat, name, selected_rect);	//按下enter则暂停,去调用抠图程序,selected_rect为选中的区域
		
		if(grabReturn == GRAB_OK)	//判断是否抠图成功
		{
			int tempCount = -1;	//当前帧人脸个数
			HImage h_judge_image;
			h_judge_image = loadImageFromMat(judge_Image);
			/*imwrite("judgeImg.jpg", judge_Image);
			FSDK_LoadImageFromFile(&h_judge_image, "judgeImg.jpg");*/
			//FSDK_SaveImageToFile(h_judge_image,"multiddddddddddddd.jpg");
			FSDK_FaceTemplate *judgeFaceTemplates = new FSDK_FaceTemplate[20];
			TFacePosition *judgeFaceArray;
			int genders[20];
			judgeFaceArray = detectUsingLuxand(h_judge_image, tempCount, judgeFaceTemplates, genders);

			int center_x = -1;
			int center_y = -1;
			if(tempCount > 0){
				selectFace = true;
				situationCount = 0;

				//计算区域中心
				center_x = selected_rect.x + selected_rect.width / 2;
				center_y = selected_rect.y + selected_rect.height / 2;
				//区域中心落在哪个人脸区域则选的哪个人脸
				int minDist = INT_MAX, closestFaceNum = -1;
				for (int i = 0; i < tempCount; i++)
				{
					int dist = myDist(center_x, center_y, judgeFaceArray[i].xc, judgeFaceArray[i].yc);
					if(dist < minDist)
					{
						minDist = dist;
						closestFaceNum = i;
					}
				}
				//FaceCartoon faceCartoon;	//创建对象,这样不行,每次创建的地址都相同
				FaceCartoon *faceCartoon = new FaceCartoon();	
				faceCartoon->cartoonNumArray = new int[vec_faceTemplates.size()];	//创建对应动画个数的数组大小
				//数组归零
				for(int i = 0; i < vec_faceTemplates.size(); i++)
				{
					faceCartoon->cartoonNumArray[i] = 0;
				}
				faceCartoon->faceTemplates.push_back(judgeFaceTemplates[closestFaceNum]);	//获取目标人脸模板
				faceCartoon->gender = genders[closestFaceNum];
				//找出最相似的人,以及卡通
				int *cartoonNums = findMatchCartoonNum(*faceCartoon);
				for(int i = 0; i< vec_faceTemplates.size(); i++) cout<< cartoonNums[i] << " ";
				cout<<"fwff"<<endl;
				int cartoonNum;
				if(simiAuto){
					theApp->selectCartoonDlg.cartoonNums = cartoonNums;
					theApp->selectCartoonDlg.DoModal();

					cartoonNum = theApp->selectCartoonDlg.getSelectedCartoonNum();
					//cartoonNum = showSelectCartoonWindow(cartoonNums, simiNum);
				}else{
					cartoonNum = cartoonNums[0];	//最相似的一个
				}

				faceCartoon->cartoonMatchNum = cartoonNum;
				faceCartoon->cartoonNumArray[cartoonNum]++;

				grabFlag = true;
				vec_FaceCartoons.push_back(faceCartoon);

				if(saveSelectedTemplates)	//是否保存模板
				{
					fout.write((char *)(&judgeFaceTemplates[closestFaceNum]), sizeof(judgeFaceTemplates[closestFaceNum])); 
				}
					
				//画出标定的人脸
				Rect faceRegionRect = getROIFromTFacePosition(judge_Image, judgeFaceArray[closestFaceNum]);
				Mat selected_faceImg(judge_Image, faceRegionRect);
					
				FSDK_FreeImage(h_judge_image);
			}else{
				cout << "当前图像没有检测出人脸!!" << endl;
			}
		}
	}

	//imshow("视频播放", myFrame);
	IplImage *originalImg, *cartoonImg;
	originalImg = &IplImage(targetImg);
	cartoonImg = &IplImage(myFrame);
	theApp->dlg.DrawPicToHDC(cartoonImg, IDC_showcartoon);
	theApp->dlg.DrawPicToHDC(originalImg, IDC_showOriginal);
	if(createVideo)
	{
		//合成视频
		outputVideo.write(myFrame);
	}
	//重启计时器
	if(theApp->dlg.key_enter == true){
		theApp->dlg.key_enter = false;
		theApp->dlg.SetTimer(1,1000/fps,NULL);  	//开始
		theApp->dlg.m_playBtn.SetWindowTextA("暂停");
		theApp->dlg.isPlay = true;
	}
	processedFrame = true;
}
Exemplo n.º 23
0
int main(int argc, char* argv[])
{
		namedWindow("Frame");
    data.clear();
    data.open("data.log",ios::out);
    // Load test images
    cv::Mat a = cv::imread(argv[1]);
		String name = argv[2];
		VideoCapture capture(name);
		if(!capture.isOpened())
		{
			//error in opening the video input
			cerr << "Unable to open video file: " << name << endl;
			exit(EXIT_FAILURE);
  	}
		//read input data. ESC or 'q' for quitting
  	while( (char)keyboard != 'q' && (char)keyboard != 27 )
		{
			//read the current frame
			if(!capture.read(frame)) {
			cerr << "Unable to read next frame." << endl;
			cerr << "Exiting..." << endl;
			exit(EXIT_FAILURE);
		}
    //cv::Mat b = cv::imread(argv[2]);
    rect = Rect(0, 500, 1440, 525); // Rect(x, y, w, h)
		// 655 = 1025−575
		//rect = Rect(0, 500, 268, 400); 
		cv::Mat a_ROI = a(rect);
    cv::Mat b_ROI = frame(rect);
    //cv::Mat b_ROI = b(rect);
    //data << " a.size().width " << a.size().width << endl;
    //if (a.empty() || b.empty())
		/*if (a.empty() || frame.empty())
        return -1;*/

    // Start motion detection
    //intruderAlarm(a_ROI, b_ROI);
		intruderAlarm(a, frame);
    // Display result
	
	makeGrid(a);
	cv::line(a, cv::Point(0, 370), cv::Point(a.size().width, 525), cv::Scalar(0, 0, 255), 2, 8);
	cv::line(a, cv::Point(0, 870), cv::Point(a.size().width, 1025), cv::Scalar(0, 0, 255), 2, 8);
	cv::line(a, boundary[0], boundary[3], cv::Scalar(0, 255, 255), 2, 8);
	cv::line(a, boundary[2], boundary[1], cv::Scalar(0, 255, 255), 2, 8);
  	cv::imshow("a", a);
		cv::imshow("Frame", frame);
		//cv::imshow("b", b_ROI);
		//cv::imshow("frame2", b_ROI);
	//setMouseCallback( "a", onMouse, 0 );	
    //cv::imshow("b", b);
		//get the input from the keyboard
  	keyboard = waitKey( 30 );
	}
	//delete capture object
    capture.release();
  //  cv::waitKey(0);

    return 0;
}
Exemplo n.º 24
0
bool openFile(ofstream & stream, string filename) {
   stream.clear();
   stream.open(expandPathname(filename).c_str());
   return !stream.fail();
}