Пример #1
0
int main(int argc, char * argv[])
{

  if (argc != 2)
    {
      cerr << "Formato " << argv[0] << " <num_elem>" << endl;
      return -1;
    }

  int n = atoi(argv[1]);

  int * T = new int[n];
  assert(T);

  srandom(time(0));

  for (int i = 0; i < n; i++)
    {
      T[i] = random();
    };

  // escribe_vector(T, n);
  tantes = high_resolution_clock::now();
  heapsort(T, n);
  tdespues = high_resolution_clock::now();
  transcurrido = duration_cast<duration<double>>(tdespues - tantes);
  cout << n << " "<< transcurrido.count() << endl;

  // escribe_vector(T, n);


  delete [] T;

  return 0;
};
Пример #2
0
    iteration_stats do_iteration()
    {
        using namespace boost::chrono;
        using boost::make_tuple;

        // Zero the counters (to be set during advance() by our slot)
        tree_time_ = particle_time_ = 0.0;
        particles_visited_ = pparticles_visited_ = 0;

        // Get the number of acceleration evals before advancing
        const int init_neval = particle_pusher_.num_acceleval();

        // Get the current time
        const steady_clock::time_point start_time = steady_clock::now();

        // Advance the system
        particle_pusher_.advance();

        // Determine how much time has elapsed
        const duration<double> net_push_time = steady_clock::now() - start_time;

        // Generate the iteration statistics; see accel_timings_slot
        return make_tuple(tree_time_,
                          particle_time_,
                          net_push_time.count() - tree_time_ - particle_time_,
                          particles_visited_,
                          pparticles_visited_,
                          particle_pusher_.num_acceleval() - init_neval);
    }
Пример #3
0
/*
 *
 * @brief Funcion Principal:
 *
 */
int main(int argc, char const *argv[]){

	if (argc != 4){
		cerr << "Formato " << argv[0] << "<ruta_del_archivo_de_entrada>  <num_elem>  <num_vect>" << endl;
		return -1;
    }

	int tam_vectores = atoi(argv[2]); //Tamaño vectores
	int num_vectores = atoi(argv[3]); //Número vectores

	int num = 0;
	string ruta=argv[1];
	ifstream archivo(ruta.c_str());
	// cargamos todos los vectores en una matriz de tipo vector<vector>
	matrix vectorAux(num_vectores,tam_vectores);
	matrix vectorT (num_vectores, tam_vectores);
	vector< vector<int> >  vectorRes;

	for(int i = 0; i < num_vectores; i++){
		for (int j = 0 ; j < tam_vectores; j++){
			archivo >> num;
			vectorT.datos[i][j] = num;
		}
	}
	tantes = high_resolution_clock::now();

	vectorAux = mergeKvectors(vectorT);
	tdespues = high_resolution_clock::now();
	transcurrido = duration_cast<duration<double>>(tdespues - tantes);
	cout <<  tam_vectores << " "<< transcurrido.count() << endl;

	return 0;
}
Пример #4
0
inline std::string policyProgressbar(unsigned const nTotal, unsigned const current = 0){

  using namespace std::chrono;

  static unsigned maxNTotal = 0;
  static unsigned part = 0;
  static unsigned tic  = 0;
  static time_point<steady_clock> startTime;
  if(part==0){ startTime = steady_clock::now(); } // get the starting time on the very first call

  std::stringstream ss;
  auto const now = steady_clock::now();

  maxNTotal = std::max(maxNTotal, nTotal);
  part = current ? current : part+1;

  //limit the update intervall (not faster than every 35ms. This would be madness.)
  duration<float> const timeSpent = now - startTime;
  if(timeSpent.count() > 0.035f*tic || part == maxNTotal){
    ++tic;
    std::string frame;
    unsigned height;

    // use all policies to compose a single frame and save its height
    std::tie(frame, height) = iteratePolicies<PolicyList...>(part, maxNTotal);
    ss << frame;
    ss << std::flush;
    
    //move the cursor back to the beginning
    if(part!=maxNTotal) ss << "\033[" << height << "A\r";
    else ss << "\n";
  }

  return ss.str();
}
Пример #5
0
std::string mir::logging::input_timestamp(nanoseconds when)
{
    // Input events use CLOCK_MONOTONIC, and so we must...
    duration<double, std::milli> const age = steady_clock::now().time_since_epoch() - when;

    char str[64];
    snprintf(str, sizeof str, "%lld (%.6fms ago)",
             static_cast<long long>(when.count()),age.count());

    return std::string(str);
}
Пример #6
0
boost::posix_time::time_duration const
to_boost_duration(
	duration<
		Rep,
		Period
	> const &duration_
)
{
	BOOST_STATIC_ASSERT(
		Period::num == 1
	);

	return
		boost::date_time::subsecond_duration<
			boost::posix_time::time_duration,
			Period::den
		>(
			duration_.count()
		);
}
Пример #7
0
inline bool operator < (duration<Rep1, Period1> const & lhs
        , duration<Rep2, Period2> const & rhs)
{
    return lhs.count() < rhs.count();
}
Пример #8
0
inline duration<Rep1, Period1> operator % (duration<Rep1, Period1> const & lhs
        , duration<Rep2, Period2> const & rhs)
{
    return lhs.count() % rhs.count();
}
Пример #9
0
inline duration<Rep1, Period> operator % (duration<Rep1, Period> const & d
        , Rep2 const & n)
{
    return d.count() % n;
}
int Raw2xBase::run()
{
	if (cmdLine.getArgCount() == 0)
	{
		std::cout << "Not enough arguments!\n";
		printHelpText();
		return 0;
	}

	if (cmdLine.hasFlag("h") || cmdLine.hasFlag("help"))
	{
		printHelpText();
		return 0;
	}

	std::string inFileName, outFileName;

	// input_file + output_file
	if (cmdLine.getArgCount() >= 2 && cmdLine.getArg(1)[0] != '-') // If arg[1] is not a flag...
	{
		inFileName  = cmdLine.getArg(0);
		outFileName = cmdLine.getArg(1);
	}
	else // Just input_file
	{
		inFileName = cmdLine.getArg(0);
		outFileName.clear();
	}

	// Replace '.raw' extension of source file with the proper extension
	// and use it for the output if no explicit filename was provided.
	if (outFileName.empty())
	{
		outFileName = utils::filesys::removeFilenameExtension(inFileName) + outputFileExt;
	}

	if (verbose)
	{
		std::cout << "In file..: " << inFileName  << "\n";
		std::cout << "Out file.: " << outFileName << "\n";
		std::cout << "Options..: " << cmdLine.getFlagsString() << "\n";
	}

	// We optionally measure execution time.
	using namespace std::chrono;
	system_clock::time_point t0, t1;

	if (timings)
	{
		t0 = system_clock::now();
	}

	// Try to open the input file. This might result in an exception.
	siege::RawImage rawImage(inFileName);

	if (rawImage.getSurfaceCount() > 1 && mipmaps)
	{
		std::string surfName;
		const int surfCount = rawImage.getSurfaceCount();

		for (int s = 0; s < surfCount; ++s)
		{
			surfName = utils::filesys::removeFilenameExtension(outFileName) + "_" + std::to_string(s) + outputFileExt;
			writeImageSurf(rawImage, s, surfName, swizzle);
		}
	}
	else // Single image (mipmap 0):
	{
		writeImageSurf(rawImage, 0, outFileName, swizzle);
	}

	if (timings)
	{
		t1 = system_clock::now();

		const duration<double> elapsedSeconds(t1 - t0);
		const auto endTime = system_clock::to_time_t(t1);

#ifdef _MSC_VER
        char timeStr[256];
        ctime_s(timeStr, sizeof(timeStr), &endTime);
#else // _MSC_VER
        const char * const timeStr = std::ctime(&endTime);
#endif // _MSC_VER

		std::cout << "Finished execution on " << timeStr
		          << "Elapsed time: " << elapsedSeconds.count() << "s\n";
	}

	return 0;
}
Пример #11
0
string formatDuration(duration<double> seconds) {
	return fmt::format("{0:.2f}", seconds.count());
}
Пример #12
0
	// we've made this function private as it doesn't need to be accessed outside this
	// functor. It contains implemenatation details.
	void printFormatted( duration<double> elapsed, const string &string )
	{
		cout << "[LOG ENTRY]: " << elapsed.count() << "s, Entry: " << string << endl;
	}
Пример #13
0
 timeout_t(duration interval, Func&& callback)
     : callback(std::forward<Func>(callback)),
       id{::SDL_AddTimer(interval.count(), run_callback, this)} {
     SDLXX_CHECK(id != 0);
 }
Пример #14
0
std::vector<cv::Mat> HierClassifier::classify(cv::Mat image,
							  	  	  	  	  cv::Mat terrain,
							  	  	  	  	  cv::Mat segmentation,
							  	  	  	  	  cv::Mat maskIgnore,
							  	  	  	  	  int entryWeightThreshold)
{


	Mat regionsOnImage;
	if(segmentation.empty()){
		regionsOnImage = segmentImage(image);
	}
	else{
		regionsOnImage = segmentation;
	}
	vector<Entry> entries = extractEntries(image,
											terrain,
											regionsOnImage,
											maskIgnore,
											entryWeightThreshold);

	using namespace std::chrono;
	high_resolution_clock::time_point start = high_resolution_clock::now();
	high_resolution_clock::time_point end;

	//ofstream log("descriptors");
	//for(int e = 0; e < entries.size(); e++){
	//	log << entries[e].descriptor << endl;
	//}

	map<int, int> imageIdToEntry;
	for(int e = 0; e < entries.size(); e++){
		imageIdToEntry[entries[e].imageId] = e;
	}
	Mat result(entries.size(), numLabels, CV_32FC1, Scalar(0));
	for(int c = 0; c < classifiers.size(); c++){
		//cout << "Classifing using classifier " << c << endl;
		for(int e = 0; e < entries.size(); e++){
			//cout << "classInfo.descBeg = " << classifiersInfo[c].descBeg << ", descEnd = " << classifiersInfo[c].descEnd << endl;
			//cout << "descriptor.numCols = " << entries[e].descriptor.cols << endl;
			Mat desc = entries[e].descriptor.colRange(
													classifiersInfo[c].descBeg,
													classifiersInfo[c].descEnd);
			//cout << "result, entry " << e << ", " << weights[c]*classifiers[c]->classify(desc) << endl;
			result.row(e) = result.row(e) + weights[c]*classifiers[c]->classify(desc);
		}
	}
	vector<Mat> ret;
	ret.resize(numLabels);
	for(int l = 0; l < numLabels; l++){
		ret[l] = Mat(image.rows, image.cols, CV_32FC1, Scalar(-2));
	}
	for(int l = 0; l < numLabels; l++){
		for(int r = 0; r < image.rows; r++){
			for(int c = 0; c < image.cols; c++){
				if(imageIdToEntry.count(regionsOnImage.at<int>(r, c)) > 0){
					ret[l].at<float>(r, c) = result.at<float>(imageIdToEntry[regionsOnImage.at<int>(r, c)], l);
				}
			}
		}
	}

	end = high_resolution_clock::now();
	static duration<double> compTime = duration<double>::zero();
	static int times = 0;

	compTime += duration_cast<duration<double> >(end - start);
	times++;
	if(debugLevel >= 1){
		cout << "Classify Times: " << times << endl;
		cout << "Classify Average computing time: " << compTime.count()/times << endl;
	}

	return ret;
}
Пример #15
0
void f(duration<double> d, double res)  // accept floating point seconds
{
    // d.count() == 3.e-6 when passed microseconds(3)
    BOOST_ASSERT(d.count()==res);
}
Пример #16
0
 duration (duration<Rep2, Period2> const & d)
     : _r(d.count())
 {}
Пример #17
0
std::vector<Entry> HierClassifier::extractEntries(	cv::Mat imageBGR,
													cv::Mat terrain,
													cv::Mat regionsOnImage,
													cv::Mat maskIgnore,
													int entryWeightThreshold)
{
	using namespace std::chrono;
	high_resolution_clock::time_point start = high_resolution_clock::now();

	if(maskIgnore.empty()){
		maskIgnore = Mat(imageBGR.rows, imageBGR.cols, CV_32SC1, Scalar(0));
	}
	//namedWindow("imageBGR");
	Mat imageHSV;
	cvtColor(imageBGR, imageHSV, CV_BGR2HSV);
	vector<Pixel> pixels;
	//pixels.resize(imageHSV.rows * imageHSV.cols);
	for(int r = 0; r < imageHSV.rows; r++){
		for(int c = 0; c < imageHSV.cols; c++){
			if(maskIgnore.at<int>(r, c) == 0){
				pixels.push_back(Pixel(r, c, regionsOnImage.at<int>(r, c)));
			}
		}
	}
	sort(pixels.begin(), pixels.end());

	vector<pair<int, int> > terrainRegion;
	if(!terrain.empty()){
		Mat terrainPointsImage(terrain.cols, 2, CV_32FC1);
		Mat tmpTerrain = terrain.rowRange(0, 3).t();
		Mat tvec(1, 3, CV_32FC1, Scalar(0));
		Mat rvec(1, 3, CV_32FC1, Scalar(0));
		Mat distCoeffs(1, 5, CV_32FC1, Scalar(0));
		projectPoints(tmpTerrain, tvec, rvec, cameraMatrix, Mat(), terrainPointsImage);
		//terrainPointsImage = terrainPointsImage.t();
		terrainPointsImage = terrainPointsImage.reshape(1).t();
		//cout << tmpTerrain.rowRange(1, 10) << endl;
		//cout << terrainPointsImage.rowRange(1, 10) << endl;
		//cout << cameraMatrix << endl;
		for(int p = 0; p < terrain.cols; p++){
			int imageRow = round(terrainPointsImage.at<float>(1, p));
			int imageCol = round(terrainPointsImage.at<float>(0, p));
			if(imageRow >= 0 && imageRow < imageBGR.rows &&
				imageCol >= 0 && imageCol < imageBGR.cols &&
				maskIgnore.at<int>(imageRow, imageCol) == 0)
			{
				int region = regionsOnImage.at<int>(imageRow, imageCol);
				terrainRegion.push_back(pair<int, int>(region, p));
			}
		}
		sort(terrainRegion.begin(), terrainRegion.end());
	}

	high_resolution_clock::time_point endSorting = high_resolution_clock::now();

	if(debugLevel >= 1){
		cout << "End sorting terrain, terrainRegion.size() = " << terrainRegion.size() << endl;
	}

	vector<Entry> ret;
	int endIm = 0;
	int endTer = 0;
	while(endIm < pixels.size()){
		Mat values, valuesTer, histogramHS, histogramV, statisticsHSV, stisticsLaser;
		int begIm = endIm;
		while(pixels[begIm].imageId == pixels[endIm].imageId){
			endIm++;
			if(endIm == pixels.size()){
				break;
			}
		}
		if(debugLevel >= 1){
			cout << "segment id = " << pixels[begIm].imageId << ", begIm = " << begIm << ", endIm = " << endIm << endl;
		}
		values = Mat(1, endIm - begIm, CV_8UC3);
		for(int p = begIm; p < endIm; p++){
			values.at<Vec3b>(p - begIm) = imageHSV.at<Vec3b>(pixels[p].r, pixels[p].c);
		}

		int begTer = endTer;
		if(begTer < terrainRegion.size()){
			while(terrainRegion[begTer].first != pixels[begIm].imageId){
				begTer++;
				if(begTer >= terrainRegion.size()){
					break;
				}
			}
		}
		endTer = begTer;
		if(endTer < terrainRegion.size()){
			while(terrainRegion[begTer].first == terrainRegion[endTer].first){
				endTer++;
				if(endTer >= terrainRegion.size()){
					break;
				}
			}
		}
		if(endTer - begTer > 0){
			valuesTer = Mat(terrain.rows, endTer - begTer, CV_32FC1);
			Mat tmpImageBGR(imageBGR);
			for(int p = begTer; p < endTer; p++){
				//cout << terrainRegion[p].second << endl;
				terrain.colRange(terrainRegion[p].second, terrainRegion[p].second + 1).copyTo(valuesTer.colRange(p - begTer, p - begTer + 1));
				//cout << "terrainRegion[p].second = " << terrainRegion[p].second << endl;
				//int imageRow = round(terrainPointsImage.at<float>(1 ,terrainRegion[p].second));
				//int imageCol = round(terrainPointsImage.at<float>(0, terrainRegion[p].second));
				//cout << "Point: " << imageRow << ", " << imageCol << endl;
				//tmpImageBGR.at<Vec3b>(imageRow, imageCol) = Vec3b(0x00, 0x00, 0xff);
			}
			//cout << "ImageId = " << pixels[begIm].imageId << endl;
			//imshow("imageBGR", imageBGR);
			//waitKey();
		}
		else{
			//cout << "Warning - no terrain values for imageId " << pixels[begIm].imageId << endl;
			valuesTer = Mat(6, 1, CV_32FC1, Scalar(0));
		}

		if(endIm - begIm > 0){
			int channelsHS[] = {0, 1};
			float rangeH[] = {0, 60};
			float rangeS[] = {0, 256};
			const float* rangesHS[] = {rangeH, rangeS};
			int sizeHS[] = {histHLen, histSLen};
			int channelsV[] = {2};
			float rangeV[] = {0, 256};
			const float* rangesV[] = {rangeV};
			int sizeV[] = {histVLen};
			calcHist(&values, 1, channelsHS, Mat(), histogramHS, 2, sizeHS, rangesHS);
			calcHist(&values, 1, channelsV, Mat(), histogramV, 1, sizeV, rangesV);
			histogramHS = histogramHS.reshape(0, 1);
			histogramV = histogramV.reshape(0, 1);
			normalize(histogramHS, histogramHS);
			normalize(histogramV, histogramV);

			if(debugLevel >= 1){
				cout << "V size = " << histogramV.size() << ", HS size = " << histogramHS.size() << endl;
			}


			values = values.reshape(1, 3);
			//cout << "values size = " << values.size() << endl;
			Mat covarHSV;
			Mat meanHSV;
			calcCovarMatrix(values,
							covarHSV,
							meanHSV,
							CV_COVAR_NORMAL | CV_COVAR_SCALE | CV_COVAR_COLS,
							CV_32F);

			if(debugLevel >= 1){
				cout << "Calculated covar matrix" << endl;
			}
			covarHSV = covarHSV.reshape(0, 1);
			meanHSV = meanHSV.reshape(0, 1);
			//normalize(covarHSV, covarHSV);
			//normalize(meanHSV, meanHSV);

			Mat covarLaser, meanLaser;
			calcCovarMatrix(valuesTer.rowRange(4, 6),
							covarLaser,
							meanLaser,
							CV_COVAR_NORMAL | CV_COVAR_SCALE | CV_COVAR_COLS,
							CV_32F);
			covarLaser = covarLaser.reshape(0, 1);
			meanLaser = meanLaser.reshape(0, 1);
			//normalize(covarLaser, covarLaser);
			//normalize(meanLaser, meanLaser);
			//cout << "covarLaser = " << covarLaser << endl;
			//cout << "meanLaser = " << meanLaser << endl;

			//cout << "Entry " << ret.size() << endl;
			//cout << "histHS = " << histogramHS << endl;
			//cout << "histV = " << histogramV << endl;
			//cout << "covarHSV = " << covarHSV << endl;
			//cout << "meanHSV = " << meanHSV << endl;

			Mat kurtLaser(1, 2, CV_32FC1);
			Mat tmpVal;
			valuesTer.rowRange(4, 6).copyTo(tmpVal);
			//cout << "tmpVal = " << tmpVal << endl;
			//cout << "mean(0) = " << meanLaser.at<float>(0) << ", mean(1) = " << meanLaser.at<float>(1) << endl;
			//cout << "stdDev^4(0) = " << pow(covarLaser.at<float>(0), 2) << ", stdDev^4(3) = " << pow(covarLaser.at<float>(3), 2) << endl;
			tmpVal.rowRange(0, 1) -= meanLaser.at<float>(0);
			tmpVal.rowRange(1, 2) -= meanLaser.at<float>(1);

			pow(tmpVal, 4, tmpVal);
			kurtLaser.at<float>(0) = sum(tmpVal.rowRange(0, 1))(0);
			if(tmpVal.cols * pow(covarLaser.at<float>(0), 2) != 0){
				kurtLaser.at<float>(0) = kurtLaser.at<float>(0) / (tmpVal.cols * pow(covarLaser.at<float>(0), 2)) - 3;
			}
			kurtLaser.at<float>(1) = sum(tmpVal.rowRange(1, 2))(0);
			if(tmpVal.cols * pow(covarLaser.at<float>(3), 2) != 0){
				kurtLaser.at<float>(1) = kurtLaser.at<float>(1) / (tmpVal.cols * pow(covarLaser.at<float>(3), 2)) - 3;
			}

			Mat histogramDI;
			int channelsDI[] = {0, 1};
			float rangeD[] = {1500, 2500};
			float rangeI[] = {1800, 4000};
			const float* rangesDI[] = {rangeD, rangeI};
			int sizeDI[] = {histDLen, histILen};
			Mat valHistD = valuesTer.rowRange(4, 5);
			Mat valHistI = valuesTer.rowRange(5, 6);
			Mat valuesHistDI[] = {valHistD, valHistI};
			calcHist(valuesHistDI, 2, channelsDI, Mat(), histogramDI, 2, sizeDI, rangesDI);
			histogramDI = histogramDI.reshape(0, 1);
			normalize(histogramDI, histogramDI);

			//cout << "histogramDI = " << histogramDI << endl;

			Entry tmp;
			tmp.imageId = pixels[begIm].imageId;
			tmp.weight = (endIm - begIm)/* + (endTer - begTer)*/;
			tmp.descriptor = Mat(1, histHLen*histSLen +
								histVLen +
								meanHSVLen +
								covarHSVLen +
								histDLen*histILen +
								meanLaserLen +
								covarLaserLen,
								CV_32FC1);

			int begCol = 0;
			histogramHS.copyTo(tmp.descriptor.colRange(begCol, begCol + histHLen*histSLen));
			begCol += histHLen*histSLen;
			histogramV.copyTo(tmp.descriptor.colRange(begCol, begCol + histVLen));
			begCol += histVLen;
			meanHSV.copyTo(tmp.descriptor.colRange(begCol, begCol + meanHSVLen));
			begCol += meanHSVLen;
			covarHSV.copyTo(tmp.descriptor.colRange(begCol, begCol + covarHSVLen));
			begCol += covarHSVLen;
			histogramDI.copyTo(tmp.descriptor.colRange(begCol, begCol + histDLen*histILen));
			begCol += histDLen*histILen;
			meanLaser.copyTo(tmp.descriptor.colRange(begCol, begCol + meanLaserLen));
			begCol += meanLaserLen;
			covarLaser.copyTo(tmp.descriptor.colRange(begCol, begCol + covarLaserLen));
			begCol += covarLaserLen;
			//kurtLaser.copyTo(tmp.descriptor.colRange(begCol, begCol + kurtLaserLen));
			//begCol += kurtLaserLen;
			//cout << "descriptor = " << tmp.descriptor << endl;

			if(endIm - begIm > entryWeightThreshold){
				ret.push_back(tmp);
			}
		}
	}

	static duration<double> sortingTime = duration<double>::zero();
	static duration<double> compTime = duration<double>::zero();
	static duration<double> wholeTime = duration<double>::zero();
	static int times = 0;

	high_resolution_clock::time_point endComp = high_resolution_clock::now();
	sortingTime += duration_cast<duration<double> >(endSorting - start);
	compTime += duration_cast<duration<double> >(endComp - endSorting);
	wholeTime += duration_cast<duration<double> >(endComp - start);
	times++;
	if(debugLevel >= 1){
		cout << "Times: " << times << endl;
		cout << "Extract Average sorting time: " << sortingTime.count()/times << endl;
		cout << "Extract Average computing time: " << compTime.count()/times << endl;
		cout << "Extract Average whole time: " << wholeTime.count()/times << endl;
	}

	return ret;
}
Пример #18
0
/*!
 Wait a specfied time interval before returning.

 @note The standard library provides `std::this_thread::sleep_for()` and
 `std::this_thread::sleep_until()` which may be preferred to this function.
 */
inline void delay(duration interval) { ::SDL_Delay(interval.count()); }
Пример #19
0
void physics_function(duration<double> d)
{
    std::cout << "d = " << d.count() << '\n';
}
Пример #20
0
 void store(duration const& d)
 {
   this->base_type::store(d);
   acc_(d.count());
 }
Пример #21
0
 iter_type put_value(iter_type s, std::ios_base& ios, char_type fill, duration<Rep, Period> const& d) const
 {
   return std::use_facet<std::num_put<CharT, iter_type> >(ios.getloc()).put(s, ios, fill,
       static_cast<long int> (d.count()));
 }
Пример #22
0
cv::Mat HierClassifier::segmentImage(cv::Mat image, int kCurSegment){

	using namespace std::chrono;
	high_resolution_clock::time_point start = high_resolution_clock::now();
	high_resolution_clock::time_point endSorting;
	high_resolution_clock::time_point endComp;
	high_resolution_clock::time_point endMerging;

	Mat imageR(image.rows, image.cols, CV_32FC1);
	Mat imageG(image.rows, image.cols, CV_32FC1);
	Mat imageB(image.rows, image.cols, CV_32FC1);
	Mat imageChannels[] = {imageR, imageG, imageB};
	Mat imageFloat(image.rows, image.cols, CV_32FC3);
	int nchannels = 3;
	int nhood[][2] = {{-1, 1},
					{1, 0},
					{1, 1},
					{0, 1}};
	/*int nhood[][2] = {{1, 0},
					{0, 1}};*/
	//cout << "Size of nhood " << sizeof(nhood)/sizeof(nhood[0]) << endl;
	//cout << "rows: " << image.rows << ", cols: " << image.cols << endl;
	if(kCurSegment == -1){
		kCurSegment = kSegment;
	}
	image.convertTo(imageFloat, CV_32F);
	//resize(imageFloat, imageFloat, Size(320, 240));
	GaussianBlur(imageFloat, imageFloat, Size(7, 7), 0.8);
	split(imageFloat, imageChannels);

	int nrows = imageFloat.rows;
	int ncols = imageFloat.cols;

	Mat segments(nrows, ncols, CV_32SC1);

	vector<Edge> edges;
	for(int r = 0; r < nrows; r++){
		for(int c = 0; c < ncols; c++){
			for(int nh = 0; nh < sizeof(nhood)/sizeof(nhood[0]); nh++){
				if((r + nhood[nh][0] < nrows) && (r + nhood[nh][0] >= 0) &&
						(c + nhood[nh][1] < ncols) && (c + nhood[nh][1] >= 0))
				{
					float diffAll = 0;
					for(int ch = 0; ch < nchannels; ch++){
						float diff = abs(imageChannels[ch].at<float>(r, c) - imageChannels[ch].at<float>(r + nhood[nh][0], c + nhood[nh][1]));
						diffAll += diff*diff;
					}
					diffAll = sqrt(diffAll);
					edges.push_back(Edge(c + ncols*r, c + nhood[nh][1] + ncols*(r + nhood[nh][0]), diffAll));
					//if(edges.back().i == 567768 || edges.back().j == 567768){
					//	cout << "diff = abs(" << (int)imageChannels[ch].at<unsigned char>(r, c) << " - " << (int)imageChannels[ch].at<unsigned char>(r + nhood[nh][0], c + nhood[nh][1]) << ") = " << diff << endl;
					//}
				}
			}
		}
	}
	sort(edges.begin(), edges.end()); //possible improvement by bin sorting

	endSorting = high_resolution_clock::now();
	cout << "End sorting" << endl;

	//cout << "Channel " << ch << endl;

	//cout << "Largest differece = " << edges[edges.size() - 1].weight <<
	//		", between (" << edges[edges.size() - 1].i << ", " << edges[edges.size() - 1].j <<
	//		")" << endl;

	UnionFind sets(nrows * ncols);
	vector<float> intDiff;
	intDiff.assign(nrows * ncols, 0);
	for(vector<Edge>::iterator it = edges.begin(); it != edges.end(); it++){
		int iRoot = sets.findSet(it->i);
		int jRoot = sets.findSet(it->j);
		//cout << "i = " << it->i << ", j = " << it->j << ", weight = " << it->weight << endl;
		if(iRoot != jRoot){
			//cout << "intDiff[iRoot] + (float)k/sizes[iRoot] = " << intDiff[iRoot] << " + " << (float)k/sizes[iRoot] << " = " << intDiff[iRoot] + (float)k/sizes[iRoot] << endl;
			//cout << "intDiff[jRoot] + (float)k/sizes[jRoot] = " << intDiff[jRoot] << " + " << (float)k/sizes[jRoot] << " = " << intDiff[jRoot] + (float)k/sizes[jRoot] << endl;
			if(min(intDiff[iRoot] + (float)kCurSegment/sets.size(iRoot), intDiff[jRoot] + (float)kCurSegment/sets.size(jRoot))
					>=
					it->weight)
			{
				//cout << "union " << min(intDiff[iRoot] + (float)k/sizes[iRoot], intDiff[jRoot] + (float)k/sizes[jRoot]) << " >= " << it->weight << endl;
				int newRoot = sets.unionSets(iRoot, jRoot);
				intDiff[newRoot] = it->weight;
			}
		}
	}
	cout << "Mergining small segments" << endl;
	for(vector<Edge>::iterator it = edges.begin(); it != edges.end(); it++){
		int iRoot = sets.findSet(it->i);
		int jRoot = sets.findSet(it->j);
		if((iRoot != jRoot) && ((sets.size(iRoot) < minSizeSegment) || (sets.size(jRoot) < minSizeSegment))){
			sets.unionSets(iRoot, jRoot);
		}
	}
	cout << "Counting elements" << endl;
	set<int> numElements;
	for(int r = 0; r < nrows; r++){
		for(int c = 0; c < ncols; c++){
			segments.at<int>(r, c) = sets.findSet(c + ncols*r);
			numElements.insert(sets.findSet(c + ncols*r));
		}
	}
	cout << "number of elements = " << numElements.size() << endl;


	endComp = high_resolution_clock::now();

	/*Mat finSegments(nrows, ncols, CV_32SC1);
	UnionFind sets(nrows * ncols);

	for(vector<Edge>::iterator it = edges.begin(); it != edges.end(); it++){
		bool areOneSegment = true;
		for(int ch = 0; ch < segments.size(); ch++){
			if(segments[ch].at<int>(it->i / ncols, it->i % ncols) != segments[ch].at<int>(it->j / ncols, it->j % ncols)){
				areOneSegment = false;
				break;
			}
		}
		if(areOneSegment){
			sets.unionSets(it->i, it->j);
		}
	}
	for(int r = 0; r < nrows; r++){
		for(int c = 0; c < ncols; c++){
			finSegments.at<int>(r, c) = sets.findSet(c + ncols*r);
		}
	}*/

	endMerging = high_resolution_clock::now();

	static duration<double> sortingTime = duration<double>::zero();
	static duration<double> compTime = duration<double>::zero();
	static duration<double> mergingTime = duration<double>::zero();
	static duration<double> wholeTime = duration<double>::zero();
	static int times = 0;

	sortingTime += duration_cast<duration<double> >(endSorting - start);
	compTime += duration_cast<duration<double> >(endComp - endSorting);
	mergingTime += duration_cast<duration<double> >(endMerging - endComp);
	wholeTime += duration_cast<duration<double> >(endMerging - start);
	times++;
	cout << "Segment Times: " << times << endl;
	cout << "Segment Average sorting time: " << sortingTime.count()/times << endl;
	cout << "Segment Average computing time: " << compTime.count()/times << endl;
	cout << "Segment Average merging time: " << mergingTime.count()/times << endl;
	cout << "Segment Average whole time: " << wholeTime.count()/times << endl;


	return segments;
}
Пример #23
0
constexpr int
f (duration < 0 > d, duration < 0 > )
{
  return d.count ();
}