Пример #1
0
/*
 * Entry point
 */
int main(int argc, char** argv) {
    // Check if enough parameters were supplied
    if (argc < 3) {
        std::cout << "USAGE: " << argv[0] << " <input image> <output image>\n";
        return -1;
    }

    // These are our file names
    std::string input_path(argv[1]);
    std::string output_path(argv[2]);

    // Read image into memory
    NICE::ImageFile source_file(input_path);
    NICE::Image image;
    source_file.reader(&image);

    // Calculate pseudocolors
    NICE::ColorImage pseudo_image(image.width(), image.height());
    NICE::imageToPseudoColor(image, pseudo_image);

    // Write image to disk
    NICE::ImageFile dest_image(output_path);
    dest_image.writer(&pseudo_image);
    return 0;
}
Пример #2
0
/*
 * Entry point
 */
int main(int argc, char** argv) {
	// Check if enough parameters were supplied
		if (argc < 3) {
			std::cout << "USAGE: " << argv[0] << " <input image> <output image>\n";
			return -1;
		}

		// These are our file names
		std::string input_path(argv[1]);
		std::string output_path(argv[2]);

		// Read file header and display header information
		NICE::ImageFile source_file(input_path);

		// Read image into memory
		NICE::Image image;
		source_file.reader(&image);

		// Allocate memory for result image
		NICE::Image result(image.width(), image.height());

		// Put together a simple convolution kernel for our motion blur effect
		NICE::Matrix kernel(10,10);
		kernel.set(0);
		kernel.addIdentity(0.1);

		// Filter the image
		NICE::Filter::filter(image, kernel, result);

		// Write image to disk
		NICE::ImageFile dest_image(output_path);
		dest_image.writer(&result);
		return 0;
}
Пример #3
0
bool compile()
{
 //shell
 
 shell(compiler_command());
 
 if(!output_path().is_file())
  return false;
  
 //ldd
 
 shell("ldd",output_path());
  
 //du
 
 //shell("du","-h",output_path());
 
 return true; 
}
Пример #4
0
  void deprecated_bind(std::string msg, ParserState pstate)
  {
    std::string cwd(Sass::File::get_cwd());
    std::string abs_path(Sass::File::rel2abs(pstate.path, cwd, cwd));
    std::string rel_path(Sass::File::abs2rel(pstate.path, cwd, cwd));
    std::string output_path(Sass::File::path_for_console(rel_path, abs_path, pstate.path));

    std::cerr << "WARNING: " << msg << std::endl;
    std::cerr << "        on line " << pstate.line+1 << " of " << output_path << std::endl;
    std::cerr << "This will be an error in future versions of Sass." << std::endl;
  }
Пример #5
0
void acceleratet::restrict_traces()
{
  trace_automatont automaton(program);

  for(subsumed_pathst::iterator it=subsumed.begin();
       it!=subsumed.end();
       ++it)
  {
    if(!it->subsumed.empty())
    {
#ifdef DEBUG
      namespacet ns(symbol_table);
      std::cout << "Restricting path:\n";
      output_path(it->subsumed, program, ns, std::cout);
#endif

      automaton.add_path(it->subsumed);
    }

    patht double_accelerator;
    patht::iterator jt=double_accelerator.begin();
    double_accelerator.insert(
      jt, it->accelerator.begin(), it->accelerator.end());
    double_accelerator.insert(
      jt, it->accelerator.begin(), it->accelerator.end());

#ifdef DEBUG
      namespacet ns(symbol_table);
      std::cout << "Restricting path:\n";
      output_path(double_accelerator, program, ns, std::cout);
#endif
    automaton.add_path(double_accelerator);
  }

  std::cout << "Building trace automaton...\n";

  automaton.build();
  insert_automaton(automaton);
}
Пример #6
0
  void deprecated(std::string msg, std::string msg2, ParserState pstate)
  {
    std::string cwd(Sass::File::get_cwd());
    std::string abs_path(Sass::File::rel2abs(pstate.path, cwd, cwd));
    std::string rel_path(Sass::File::abs2rel(pstate.path, cwd, cwd));
    std::string output_path(Sass::File::path_for_console(rel_path, pstate.path, pstate.path));

    std::cerr << "DEPRECATION WARNING on line " << pstate.line + 1;
    if (output_path.length()) std::cerr << " of " << output_path;
    std::cerr << ":" << std::endl;
    std::cerr << msg << " and will be an error in future versions of Sass." << std::endl;
    if (msg2.length()) std::cerr << msg2 << std::endl;
    std::cerr << std::endl;
  }
Пример #7
0
void Converter::ConvertPhoto(Photo& photo, const wxString& root,
                             const wxString& group_name, const wxString& extension) {  
  boost::scoped_ptr<Bitmap> bitmap(Bitmap::Read(photo.m_path.GetFullPath()));

  wxFileName output_path(root, photo.m_path.GetName());
  output_path.MakeAbsolute();
  output_path.AppendDir(group_name);
  output_path.SetExt(extension);
  if (!MakeSureDirExists(output_path)) {
      m_listener.OnConvertFail(photo);
      return;
  }

  if (bitmap.get() == NULL) {
    m_listener.OnConvertFail(photo);
    return;
  }
  if (!photo.IsSizeSet()) {
    photo.m_size = bitmap->GetSize();
  }
//  wxRect rect = m_project.HasPhotoCrop(photo) ?
//                m_project.GetPhotoCrop(photo) :
//                wxRect(wxPoint(-1, -1), m_project.GetResizer().GetSize(photo.m_size));
//  if (wxPoint(-1, -1) == rect.GetPosition()) {
//    bitmap->Scale(rect.GetSize());
//  } else {
//    bitmap->Crop(rect);
//  }

  const Resizer& resizer = m_project.GetResizer();
  if (resizer.NeedsCrop(photo.m_size)) {
    wxRect crop = m_project.HasPhotoCrop(photo) ?
                m_project.GetPhotoCrop(photo) :
                wxRect(wxPoint(0, 0), resizer.GetCropSize(photo.m_size));
    bitmap->Crop(crop);
  }

  if (resizer.NeedsRescale(photo.m_size)) {
    bitmap->Scale(resizer.GetScaleSize(photo.m_size));
  }

  if (!bitmap->Write(output_path.GetFullPath())) {    
    m_listener.OnConvertFail(photo);
    return;
  }
  Photo dest(output_path.GetFullPath());
  dest.m_size = bitmap->GetSize();
  m_listener.OnConvertSuccess(photo, dest);
  // Log::d << "ConvertPhoto to [" << output_path.GetFullPath() << "]." << Log::ENDL;
}
Пример #8
0
int main(int argc, char **argv)
{
  ros::init(argc, argv, "stereo_to_matlab");

  ros::NodeHandle node  = ros::NodeHandle();
  ros::NodeHandle pnode = ros::NodeHandle("~");

  std::string str_output_path, output_folder_prefix;

  if(node.getNamespace() == "/") {
    ROS_WARN("Started in global namespace! Use ROS_NAMESPACE=my_camera rosrun stereo_extractor stereo_extractor");
  }

  pnode.param<std::string>("output_folder_prefix", output_folder_prefix, "data");

  if(!pnode.getParam("output_path", str_output_path)) {
    ROS_ERROR("Failed to get param 'output_path'");
    // todo: is this clean?
    ros::shutdown();
    return 1;
  }

  boost::filesystem::path output_path(str_output_path);

  try {
    if(!boost::filesystem::exists(output_path) || !is_directory(output_path)) {
      ROS_ERROR_STREAM("Output path '"<<str_output_path<<"; cannot be found or is not a directory");
      ros::shutdown();
    }
  } catch(const boost::filesystem::filesystem_error& ex) {
    ROS_ERROR("Error while resolving output path: %s", ex.what());
    ros::shutdown();
  }

  // construct path


  // define exporter
  boost::shared_ptr<stereo_extractor::StereoFileExporter> exporter(new stereo_extractor::StereoFileExporter(output_path, output_folder_prefix));

  stereo_extractor::StereoExtractor extractor(node, pnode, exporter);

  ros::spin();
  return 0;
}
Пример #9
0
static bool start_alembic_export(
	const std::string& filepath,
	int export_mode, 
	bool isExportNomals,
	bool is_export_uvs,
	bool is_use_euler_rotation_camera,
	bool is_use_ogawa)
{
	const BridgeParameter& parameter = BridgeParameter::instance();
	if (parameter.export_fps <= 0)
	{
		return false;
	}

	if (!AlembicArchive::instance().archive)
	{
		std::string output_path(filepath);
		if (output_path.empty()) 
		{
			output_path = umbase::UMStringUtil::wstring_to_utf8(parameter.base_path) + ("out\\alembic_file.abc");
		}
		//if (is_use_ogawa) {
		//	AlembicArchive::instance().archive =
		//		new Alembic::Abc::OArchive(Alembic::AbcCoreOgawa::WriteArchive(),
		//		output_path.c_str());
		//}
		//else
		{
			AlembicArchive::instance().archive =
				new Alembic::Abc::OArchive(Alembic::AbcCoreHDF5::WriteArchive(),
				output_path.c_str());
		}

		AlembicArchive &archive = AlembicArchive::instance();
		const double dt = 1.0 / parameter.export_fps;
		archive.timesampling = AbcA::TimeSamplingPtr(new AbcA::TimeSampling(dt, 0.0));
		archive.archive->addTimeSampling(*archive.timesampling);
		archive.is_export_normals = (isExportNomals != 0);
		archive.is_export_uvs = (is_export_uvs != 0);
		archive.is_use_euler_rotation_camera = (is_use_euler_rotation_camera != 0);
		archive.export_mode = export_mode;
		return true;
	}
	return false;
}
Пример #10
0
void pcl::PHVObjectClassifier<PointT, PointNormalT, FeatureT>::saveToFile() {

	// Delete old and create new directory sturcture for output
	boost::filesystem::path output_path(database_dir_);
	boost::filesystem::path output_models_path(database_dir_ + "models/");
	if (boost::filesystem::exists(output_path)) {
		boost::filesystem::remove_all(output_path);
	}

	boost::filesystem::create_directories(output_path);
	boost::filesystem::create_directories(output_models_path);

	YAML::Emitter out;

	out << *this;

	std::ofstream f;
	f.open((database_dir_ + "database.yaml").c_str());
	f << out.c_str();
	f.close();

}
void ColladaExporter::save(const TMD::PostProcessed::Data_t& data, const std::vector<CAT::ResourceEntry_t::SubEntry_t>& references) {
	boost::filesystem::path output_path(_export_folder);
	output_path /= "tmd";
	boost::filesystem::path dae_filename(output_path);
	dae_filename += _dae_suffix;

	/*std::ofstream dae_out;
	open_to_write(dae_out, dae_filename);
	LeftPad_t pad{ 0 };
	PaddedOstream pad_out(dae_out, pad);
	write_document(pad_out, data);
	dae_out.close();*/

	aiScene scene;
	create_assimp_scene(scene, data);

	Assimp::Exporter exporter;
	auto export_format = exporter.GetExportFormatDescription(0);

	exporter.Export(&scene, export_format->id, dae_filename.string().c_str());

}
Пример #12
0
string compiler_command()
{
 array<string> result;
 
 //compiler
  
 if(is_gcc())
  result=gcc_arguments();
 else if(is_clang())
  result=clang_arguments();
 else
  stop();
  
 //common
 
 result.append(compiler_arguments());

 //paths
 
 result.push(input_path()); 
 result.push(space("-o",output_path()));
  
 return result.join(" ");
}
Пример #13
0
int acceleratet::accelerate_loop(goto_programt::targett &loop_header)
{
  pathst loop_paths, exit_paths;
  goto_programt::targett back_jump=find_back_jump(loop_header);
  int num_accelerated=0;
  std::list<path_acceleratort> accelerators;
  natural_loops_mutablet::natural_loopt &loop =
    natural_loops.loop_map[loop_header];

  if(contains_nested_loops(loop_header))
  {
    // For now, only accelerate innermost loops.
#ifdef DEBUG
    std::cout << "Not accelerating an outer loop\n";
#endif
    return 0;
  }

  goto_programt::targett overflow_loc;
  make_overflow_loc(loop_header, back_jump, overflow_loc);
  program.update();

#if 1
  enumerating_loop_accelerationt
    acceleration(
      symbol_table,
      goto_functions,
      program,
      loop,
      loop_header,
      accelerate_limit);
#else
  disjunctive_polynomial_accelerationt
    acceleration(symbol_table, goto_functions, program, loop, loop_header);
#endif

  path_acceleratort accelerator;

  while(acceleration.accelerate(accelerator) &&
        (accelerate_limit < 0 ||
         num_accelerated < accelerate_limit))
  {
    // set_dirty_vars(accelerator);

    if(is_underapproximate(accelerator))
    {
      // We have some underapproximated variables -- just punt for now.
#ifdef DEBUG
      std::cout << "Not inserting accelerator because of underapproximation\n";
#endif

      continue;
    }

    accelerators.push_back(accelerator);
    num_accelerated++;

#ifdef DEBUG
    std::cout << "Accelerated path:\n";
    output_path(accelerator.path, program, ns, std::cout);

    std::cout << "Accelerator has "
              << accelerator.pure_accelerator.instructions.size()
              << " instructions\n";
#endif
  }

  goto_programt::instructiont skip(SKIP);
  program.insert_before_swap(loop_header, skip);

  goto_programt::targett new_inst=loop_header;
  ++new_inst;

  loop.insert(new_inst);


  std::cout << "Overflow loc is " << overflow_loc->location_number << '\n';
  std::cout << "Back jump is " << back_jump->location_number << '\n';

  for(std::list<path_acceleratort>::iterator it=accelerators.begin();
      it!=accelerators.end();
      ++it)
  {
    subsumed_patht inserted(it->path);

    insert_accelerator(loop_header, back_jump, *it, inserted);
    subsumed.push_back(inserted);
    num_accelerated++;
  }

  return num_accelerated;
}
int main(int argc, const char * argv[]) {

    namespace prog_opt = boost::program_options;
    namespace file_sys = boost::filesystem;
    
    
    ///////////////////////////////////////////////////////////////////////////
    ///                                                                     ///
    ///    PROGRAM OPTIONS                                                  ///
    ///                                                                     ///
    ///////////////////////////////////////////////////////////////////////////
    
    
    std::string base_dir_str;
    std::string output_path_str;
	bool use_int_signals;
	std::string climate_signal;
	std::vector<std::string> portfolio_signal;
	int ari_signal;
	int year;

    
    
    prog_opt::options_description desc("Allowed options");
    desc.add_options()
    ("help,h", "produce help message")
    ("base-directory,d", prog_opt::value<std::string>(&base_dir_str), "The base directory for the map database")
	("climate-signal,c", prog_opt::value<std::string>(&climate_signal)->default_value("1"), "The climate change projection that should be used")
	("portfolio-signal,p", prog_opt::value<std::vector<std::string> >(&portfolio_signal), "The mitigation portfolios that should be used. Need to specify exactly the number of portfolios as there are catchments")
	("ARI,r", prog_opt::value<int>(&ari_signal)->default_value(20), "The 1:ari value indicating expected frequency of flood hazard")
	("year,y", prog_opt::value<int>(&year)->default_value(2015), "specify year in which to calculate flood hazard for")
    ("output,o", prog_opt::value<std::string>(&output_path_str)->default_value("output.tif"), "The path to print output interpolated map to")
	("int-signam,i", prog_opt::value<bool>(&use_int_signals)->default_value(true), "Whether to use string or int representation of mitigation and climate scanario signals");

	prog_opt::positional_options_description p;
	p.add("portfolio-signal", -1);

    prog_opt::variables_map vm;
	prog_opt::store(prog_opt::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    prog_opt::notify(vm);

    if (vm.count("help"))
    {
        std::cout << desc << "\n";
        return 1;
    }
	if (vm.count("portfolio-signal"))
	{
		std::cout << "Mitigation portfolios are: "
			<< vm["portfolio-signal"].as< std::vector<std::string> >() << "\n";
	}
    
    file_sys::path base_dir(base_dir_str);
    //Check if base directory exists
    if (!file_sys::exists(base_dir))
    {
        std::cerr << "Base directory of database does not exist" << std::endl;
        //Could throw an error here instead
    }

	
    

    Database my_data;
    processDatabase(my_data, base_dir);
	//Read in template map.
	fs::path template_map = base_dir / "template.tif";
	std::tuple<Map_Double_SPtr, std::string, GeoTransform> gdal_map = read_in_map<double>(template_map, GDT_Float64, NO_CATEGORISATION);
	Map_Double_SPtr map(std::get<0>(gdal_map));
	std::string & map_WKT_projection = (std::get<1>(gdal_map));
	GeoTransform & map_transform = (std::get<2>(gdal_map));
	int nrows = map->NRows();
	int ncols = map->NCols();
	double no_data_val = map->NoDataValue();

	//Set number of mitigaiton portfolios and scenarios
	int num_of_scenarios = my_data.get_catchment(1)->clim_scnrios_ik.size();
	int num_of_portfolios = my_data.get_catchment(1)->get_scenario(1)->mit_prtflios_ik.size();

    StitchedMapSet maps;

	if (use_int_signals == true)
	{
		std::vector<int> portfolios;
		for (int i = 0; i < num_of_portfolios; ++i)
		{
			portfolios[i] = std::stoi(portfolio_signal[i]);
		}
		int scenario = std::stoi(climate_signal);
		getMapSet(climate_signal, portfolio_signal, my_data, maps, ncols, nrows, no_data_val);
	}
	else
	{
		getMapSet(climate_signal, portfolio_signal, my_data, maps, ncols, nrows, no_data_val);
	}

    
    
    Map_Float_SPtr interped_map = interpolatedmap(ari_signal, year, maps);
    
    /********************************************/
    /* Print resultent map                      */
    /********************************************/
    
    //Open template map to get projection and transformation information.
    file_sys::path template_path = base_dir / "template.tif";
    std::string wKTprojection;
    GeoTransform transform;
    Map_Float_SPtr template_map;
    std::tie(template_map, wKTprojection, transform) = read_in_map<float>(template_path, GDT_Float32, NO_CATEGORISATION);
    
    
    file_sys::path output_path(output_path_str);
    std::cout << "\n\n*************************************\n";
    std::cout << "*         Saving output file        *\n";
    std::cout << "*************************************" << std::endl;
    std::string driverName = "GTiff";
    write_map(output_path, GDT_Float32, interped_map, wKTprojection, transform, driverName);
    
    
    std::cout << "finished processing database" << std::endl;
    std::cout << "Another breakpoint" << std::endl;
}
Пример #15
0
int main(int argc, char **argv) {
    Eigen::initParallel();
    args::ArgumentParser parser(
        "A utility for setting up merged 4D files for use with FSL randomise etc.\n"
        "The group for each input file must be specified with --groups (one per line)\n"
        "A value of 0 means ignore this file.\n"
        "\nhttp://github.com/spinicist/QUIT");
    args::PositionalList<std::string> file_paths(parser, "INPUTS", "Input files to be merged.");
    args::HelpFlag                    help(parser, "HELP", "Show this help message", {'h', "help"});
    args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::Flag sort(parser, "SORT", "Sort merged file and GLM in ascending group order",
                    {'s', "sort"});
    args::ValueFlag<std::string> group_path(
        parser, "GROUPS", "File to read group numbers from (REQUIRED)", {'g', "groups"});
    args::ValueFlag<std::string> output_path(parser, "OUT", "Path for output merged file",
                                             {'o', "out"});
    args::ValueFlag<std::string> covars_path(
        parser, "COVARS", "Path to covariates file (added to design matrix)", {'C', "covars"});
    args::ValueFlag<std::string> design_path(parser, "DESIGN", "Path to save design matrix",
                                             {'d', "design"});
    args::ValueFlag<std::string> contrasts_path(parser, "CONTRASTS", "Generate and save contrasts",
                                                {'c', "contrasts"});
    args::ValueFlag<std::string> ftests_path(parser, "FTESTS", "Generate and save F-tests",
                                             {'f', "ftests"});
    QI::ParseArgs(parser, argc, argv, verbose);

    std::ifstream group_file(QI::CheckValue(group_path));
    QI::Log(verbose, "Reading group file");
    std::vector<int> group_list;
    int              temp;
    while (group_file >> temp) {
        group_list.push_back(temp);
    }
    int n_groups = *std::max_element(group_list.begin(), group_list.end());
    int n_images = std::count_if(group_list.begin(), group_list.end(),
                                 [](int i) { return i > 0; }); // Count non-zero elements

    if (file_paths.Get().size() != group_list.size()) {
        QI::Fail("Group list size and number of files do not match.");
    }

    std::vector<std::vector<QI::VolumeF::Pointer>> groups(n_groups);
    QI::Log(verbose, "Groups = {}, Images = {}", n_groups, n_images);
    itk::FixedArray<unsigned int, 4> layout;
    layout[0] = layout[1] = layout[2] = 1;
    layout[3]                         = n_images;
    auto tiler                        = itk::TileImageFilter<QI::VolumeF, QI::SeriesF>::New();
    tiler->SetLayout(layout);

    std::ofstream design_file;
    if (design_path) {
        QI::Log(verbose, "Design matrix will be saved to: {}", design_path.Get());
        design_file = std::ofstream(design_path.Get());
    }
    std::vector<std::vector<std::vector<std::string>>> covars(n_groups);
    std::vector<std::ifstream>                         covars_files;
    if (covars_path) {
        QI::Log(verbose, "All covariates: {}", covars_path.Get());
        std::istringstream stream_covars(covars_path.Get());
        while (!stream_covars.eof()) {
            std::string path;
            getline(stream_covars, path, ',');
            QI::Log(verbose, "Opening covariate file: {}", path);
            std::ifstream covars_file(path);
            if (!covars_file) {
                QI::Fail("Failed to open covariate file: {}", path);
            }
            covars_files.push_back(std::move(covars_file));
        }
    }
    int out_index = 0;
    for (size_t i = 0; i < group_list.size(); i++) {
        const int group = group_list.at(i);
        if (group > 0) { // Ignore entries with a 0
            QI::Log(verbose, "File: {} Group: {}", file_paths.Get().at(i), group);
            QI::VolumeF::Pointer ptr = QI::ReadImage(file_paths.Get().at(i), verbose);
            groups.at(group - 1).push_back(ptr);
            std::vector<std::string> covar;
            if (covars_path) {
                for (auto &f : covars_files) {
                    std::string c;
                    std::getline(f, c);
                    covar.push_back(c);
                }
                covars.at(group - 1).push_back(covar);
                QI::Log(verbose, "Covariate: {}", fmt::join(covar, ","));
            }
            if (!sort) {
                tiler->SetInput(out_index, ptr);
                out_index++;
                if (design_path) {
                    for (int g = 1; g <= n_groups; g++) {
                        if (g == group) {
                            design_file << "1\t";
                        } else {
                            design_file << "0\t";
                        }
                    }
                    if (covars_path) {
                        for (auto &c : covar) {
                            design_file << c << "\t";
                        }
                    }
                    design_file << "\n";
                }
            }
        } else {
            QI::Log(verbose, "Ignoring file: {}", file_paths.Get().at(i));
            // Eat a line in each covariates file
            for (auto &f : covars_files) {
                std::string dummy;
                std::getline(f, dummy);
            }
        }
    }
    if (sort) {
        QI::Log(verbose, "Sorting.");
        for (int g = 0; g < n_groups; g++) {
            for (size_t i = 0; i < groups.at(g).size(); i++) {
                tiler->SetInput(out_index, groups.at(g).at(i));
                out_index++;
                if (design_path) {
                    for (int g2 = 0; g2 < n_groups; g2++) {
                        if (g2 == g) {
                            design_file << "1\t";
                        } else {
                            design_file << "0\t";
                        }
                    }
                    if (covars_path) {
                        for (auto &c : covars.at(g).at(i)) {
                            design_file << c << "\t";
                        }
                    }
                    design_file << "\n";
                }
            }
        }
    }
    int n_covars = covars_path ? covars.front().front().size() : 0;
    if (contrasts_path) {
        QI::Log(verbose, "Generating contrasts");
        std::ofstream con_file(contrasts_path.Get());
        for (int g = 0; g < n_groups; g++) {
            for (int g2 = 0; g2 < n_groups; g2++) {
                if (g2 == g) {
                    con_file << "1\t";
                } else if (g2 == ((g + 1) % (n_groups))) {
                    con_file << "-1\t";
                } else {
                    con_file << "0\t";
                }
            }
            for (int c = 0; c < n_covars; c++) {
                con_file << "0\t";
            }
            con_file << "\n";
        }
        for (int c = 0; c < 2 * n_covars; c++) {
            for (int g = 0; g < n_groups; g++) {
                con_file << "0\t";
            }
            for (int c2 = 0; c2 < n_covars; c2++) {
                if ((c / 2) == c2) {
                    con_file << ((c % 2 == 0) ? "1\t" : "-1\t");
                } else {
                    con_file << "0\t";
                }
            }
            con_file << "\n";
        }
    }
    if (ftests_path) {
        QI::Log(verbose, "Generating F-tests");
        std::ofstream fts_file(ftests_path.Get());
        for (int g = 0; g < n_groups; g++) { // Individual group comparisons
            for (int g2 = 0; g2 < n_groups; g2++) {
                fts_file << ((g2 == g) ? "1\t" : "0\t");
            }
            for (int c = 0; c < 2 * n_covars; c++) {
                fts_file << "0\t";
            }
            fts_file << std::endl;
        }
        if (n_groups > 2) { // Main effect
            for (int g = 0; g < (n_groups - 1); g++) {
                fts_file << "1\t";
            }
            fts_file << "0\t";
            for (int c = 0; c < 2 * n_covars; c++) {
                fts_file << "0\t";
            }
            fts_file << std::endl;
        }
    }
    tiler->UpdateLargestPossibleRegion();
    // Reset space information because tiler messes it up
    QI::SeriesF::Pointer output = tiler->GetOutput();
    output->DisconnectPipeline();
    auto spacing   = output->GetSpacing();
    auto origin    = output->GetOrigin();
    auto direction = output->GetDirection();
    spacing.Fill(1);
    origin.Fill(0);
    direction.SetIdentity();
    for (int i = 0; i < 3; i++) {
        spacing[i] = groups.at(0).at(0)->GetSpacing()[i];
        origin[i]  = groups.at(0).at(0)->GetOrigin()[i];
        for (int j = 0; j < 3; j++) {
            direction[i][j] = groups.at(0).at(0)->GetDirection()[i][j];
        }
    }
    output->SetSpacing(spacing);
    output->SetOrigin(origin);
    output->SetDirection(direction);
    QI::WriteImage<QI::SeriesF>(output, QI::CheckValue(output_path), verbose);
    return EXIT_SUCCESS;
}
Пример #16
0
int main(int argc, char** argv)
{

  if (argc < 5)
  {
    PCL17_INFO ("Usage %s -input_dir /dir/with/models -output_dir /output/dir [options]\n", argv[0]);
    PCL17_INFO (" * where options are:\n"
        "         -height <X>            : simulate scans with sensor mounted on height X\n"
        "         -noise_std <X>         : std of gaussian noise added to pointcloud. Default value 0.0001.\n"
        "         -distance <X>          : simulate scans with object located on a distance X. Can be used multiple times. Default value 4.\n"
        "         -tilt <X>              : tilt sensor for X degrees. X == 0 - sensor looks strait. X < 0 Sensor looks down. X > 0 Sensor looks up . Can be used multiple times. Default value -15.\n"
        "         -shift <X>             : shift object from the straight line. Can be used multiple times. Default value 0.\n"
        "         -num_views <X>         : how many times rotate the object in for every distance, tilt and shift. Default value 6.\n"

        "");
    return -1;
  }

  std::string input_dir, output_dir;
  double height = 1.5;
  double num_views = 6;
  double noise_std = 0.0001;
  std::vector<double> distances;
  std::vector<double> tilt;
  std::vector<double> shift;
  int full_model_n_points = 30000;

  pcl17::console::parse_argument(argc, argv, "-input_dir", input_dir);
  pcl17::console::parse_argument(argc, argv, "-output_dir", output_dir);
  pcl17::console::parse_argument(argc, argv, "-num_views", num_views);
  pcl17::console::parse_argument(argc, argv, "-height", height);
  pcl17::console::parse_argument(argc, argv, "-noise_std", noise_std);
  pcl17::console::parse_multiple_arguments(argc, argv, "-distance", distances);
  pcl17::console::parse_multiple_arguments(argc, argv, "-tilt", tilt);
  pcl17::console::parse_multiple_arguments(argc, argv, "-shift", shift);

  PCL17_INFO("distances size: %d\n", distances.size());
  for (size_t i = 0; i < distances.size(); i++)
  {
    PCL17_INFO("distance: %f\n", distances[i]);
  }

  // Set default values if user didn't provide any
  if (distances.size() == 0)
    distances.push_back(4);
  if (tilt.size() == 0)
    tilt.push_back(-15);
  if (shift.size() == 0)
    shift.push_back(0);

  // Check if input path exists
  boost::filesystem::path input_path(input_dir);
  if (!boost::filesystem::exists(input_path))
  {
    PCL17_ERROR("Input directory doesnt exists.");
    return -1;
  }

  // Check if input path is a directory
  if (!boost::filesystem::is_directory(input_path))
  {
    PCL17_ERROR("%s is not directory.", input_path.c_str());
    return -1;
  }

  // Check if output directory exists
  boost::filesystem::path output_path(output_dir);
  if (!boost::filesystem::exists(output_path) || !boost::filesystem::is_directory(output_path))
  {
    if (!boost::filesystem::create_directories(output_path))
    {
      PCL17_ERROR ("Error creating directory %s.\n", output_path.c_str ());
      return -1;
    }
  }

  // Find all .vtk files in the input directory
  std::vector<std::string> files_to_process;
  PCL17_INFO("Processing following files:\n");
  boost::filesystem::directory_iterator end_iter;
  for (boost::filesystem::directory_iterator iter(input_path); iter != end_iter; iter++)
  {
    boost::filesystem::path class_dir_path(*iter);
    for (boost::filesystem::directory_iterator iter2(class_dir_path); iter2 != end_iter; iter2++)
    {
      boost::filesystem::path file(*iter2);
      if (file.extension() == ".vtk")
      {
        files_to_process.push_back(file.c_str());
        PCL17_INFO("\t%s\n", file.c_str());
      }
    }

  }

  // Check if there are any .vtk files to process
  if (files_to_process.size() == 0)
  {
    PCL17_ERROR("Directory %s has no .vtk files.", input_path.c_str());
    return -1;
  }

  // Iterate over all files
  for (size_t i = 0; i < files_to_process.size(); i++)
  {
    vtkSmartPointer<vtkPolyData> model;
    vtkSmartPointer<vtkPolyDataReader> reader = vtkPolyDataReader::New();
    vtkSmartPointer<vtkTransform> transform = vtkTransform::New();
    pcl17::PointCloud<pcl17::PointXYZ>::Ptr cloud(new pcl17::PointCloud<pcl17::PointXYZ>());

    // Compute output directory for this model
    std::vector<std::string> st;
    boost::split(st, files_to_process.at(i), boost::is_any_of("/"), boost::token_compress_on);
    std::string class_dirname = st.at(st.size() - 2);
    std::string dirname = st.at(st.size() - 1);
    dirname = dirname.substr(0, dirname.size() - 4);
    dirname = output_dir + class_dirname + "/" + dirname;

    // Check if output directory for this model exists. If not create
    boost::filesystem::path dirpath(dirname);
    if (!boost::filesystem::exists(dirpath))
    {
      if (!boost::filesystem::create_directories(dirpath))
      {
        PCL17_ERROR ("Error creating directory %s.\n", dirpath.c_str ());
        return -1;
      }
    }

    // Load model from file
    reader->SetFileName(files_to_process.at(i).c_str());
    reader->Update();
    model = reader->GetOutput();
    PCL17_INFO("Number of points %d\n",model->GetNumberOfPoints());

    // Coumpute bounds and center of the model
    double bounds[6];
    model->GetBounds(bounds);
    double min_z_value = bounds[4];

    double center[3];
    model->GetCenter(center);

    createFullModelPointcloud(model, full_model_n_points, *cloud);
    pcl17::io::savePCDFile(dirname + "/full.pcd", *cloud);

    // Initialize PCLVisualizer. Add model to scene.
    pcl17::visualization::PCLVisualizer viz;
    viz.initCameraParameters();
    viz.updateCamera();
    viz.setCameraPosition(0, 0, 0, 1, 0, 0, 0, 0, 1);
    viz.addModelFromPolyData(model, transform);
    viz.setRepresentationToSurfaceForAllActors();

    // Iterate over all shifts
    for (size_t shift_index = 0; shift_index < shift.size(); shift_index++)
    {

      // Iterate over all tilts
      for (size_t tilt_index = 0; tilt_index < tilt.size(); tilt_index++)
      {

        // Iterate over all distances
        for (size_t distance_index = 0; distance_index < distances.size(); distance_index++)
        {

          // Iterate over all angles
          double angle = 0;
          double angle_step = 360.0 / num_views;
          for (int angle_index = 0; angle_index < num_views; angle_index++)
          {

            // Set transformation with distance, shift, tilt and angle parameters.
            transform->Identity();
            transform->RotateY(tilt[tilt_index]);
            transform->Translate(distances[distance_index], shift[shift_index], -(height + min_z_value));
            transform->RotateZ(angle);

		/*		

            // Render pointcloud
            viz.renderView(640, 480, cloud);

            //Add noise
            addNoise(cloud, noise_std);

            // Compute new coordinates of the model center
            double new_center[3];
            transform->TransformPoint(center, new_center);

            // Shift origin of the poincloud to the model center and align with initial coordinate system.
            pcl17::PointCloud<pcl17::PointXYZ>::Ptr cloud_transformed(new pcl17::PointCloud<pcl17::PointXYZ>());
            moveToNewCenterAndAlign(cloud, cloud_transformed, new_center, tilt[tilt_index]);

            // Compute file name for this pointcloud and save it
            std::stringstream ss;
            ss << dirname << "/rotation" << angle << "_distance" << distances[distance_index] << "_tilt"
                << tilt[tilt_index] << "_shift" << shift[shift_index] << ".pcd";
            PCL17_INFO("Writing %d points to file %s\n", cloud->points.size(), ss.str().c_str());
            pcl17::io::savePCDFile(ss.str(), *cloud_transformed);

		*/

            // increment angle by step
            angle += angle_step;
	
	

          }

        }
      }
    }

  }

  return 0;
}