Basic Image AlgorithmS Library  2.8.0
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
IOUtils.cpp
1 /*
2  This file is part of the BIAS library (Basic ImageAlgorithmS).
3 
4  Copyright (C) 2003-2009 (see file CONTACT for details)
5  Multimediale Systeme der Informationsverarbeitung
6  Institut fuer Informatik
7  Christian-Albrechts-Universitaet Kiel
8 
9 
10  BIAS is free software; you can redistribute it and/or modify
11  it under the terms of the GNU Lesser General Public License as published by
12  the Free Software Foundation; either version 2.1 of the License, or
13  (at your option) any later version.
14 
15  BIAS is distributed in the hope that it will be useful,
16  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  GNU Lesser General Public License for more details.
19 
20  You should have received a copy of the GNU Lesser General Public License
21  along with BIAS; if not, write to the Free Software
22  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  */
24 
25 #include <Utils/IOUtils.hh>
26 
27 #include <Base/Image/ImageConvert.hh>
28 #include <Base/Common/FileHandling.hh>
29 #include <string>
30 
31 using namespace std;
32 using namespace BIAS;
33 
34 #ifdef WIN32
35 #define SEPERATOR ";"
36 #define SUBDIRSEP "\\"
37 #else
38 #define SEPERATOR ":"
39 #define SUBDIRSEP "/"
40 #endif
41 
42 bool IOUtils::
43  ExtractSubPaths(const std::string& environmentVariable,
44  std::vector<std::string>& subPaths)
45 {
46 
47  if (getenv(environmentVariable.c_str()) == NULL)
48  {
49  BIASWARN("environment variable "<<environmentVariable<<" not found");
50  return false;
51  }
52 
53  string concatenatedPaths(getenv(environmentVariable.c_str()));
54 
55  //vector<string> subPaths;
56  vector<unsigned int> seperators;//positions of seperators
57  string::size_type index = concatenatedPaths.find(SEPERATOR, 0);
58  while (index != string::npos)
59  {
60  seperators.push_back(index);
61  index++;
62  index = concatenatedPaths.find(SEPERATOR, index);
63  }
64  seperators.push_back(concatenatedPaths.size());
65 
66  subPaths.push_back(concatenatedPaths.substr(0, seperators[0]));
67  for (unsigned int i = 0; i < seperators.size() - 1; i++)
68  {
69  subPaths.push_back(concatenatedPaths.substr(seperators[i] + 1,
70  seperators[i + 1] - seperators[i] - 1));
71  }
72  return true;
73 }
74 
75 
76 bool
77 IOUtils::FindFile(const std::string& searchPaths,
78  const std::string& baseFileName, std::string& fullFileName)
79 {
80  bool found = false;
81  // string sp = searchPaths;
82  vector<string> subPaths;
83  vector<unsigned int> seperators;
84  string::size_type index = searchPaths.find(SEPERATOR, 0);
85  while (index != string::npos)
86  {
87  seperators.push_back(index);
88  index++;
89  index = searchPaths.find(SEPERATOR, index);
90  }
91  seperators.push_back(searchPaths.size());
92 
93  subPaths.push_back(searchPaths.substr(0, seperators[0]));
94  for (unsigned int i = 0; i < seperators.size() - 1; i++)
95  {
96  subPaths.push_back(searchPaths.substr(seperators[i] + 1,
97  seperators[i + 1] - seperators[i] - 1));
98  }
99 
100  for (unsigned int i = 0; i < subPaths.size() && !found; i++)
101  {
102  fullFileName = subPaths[i];
103  fullFileName += SUBDIRSEP;
104  fullFileName += baseFileName;
105  found = FileHandling::FileExists(fullFileName);
106  }
107  return found;
108 }
109 
110 /** Like FindFile but reads out the searchPath from the specified environmentVariable.
111  **/
112 bool
113 IOUtils::FindFileEnv(const std::string& environmentVariable,
114  const std::string& baseFileName, std::string& fullFileName)
115 {
116 
117  if (getenv(environmentVariable.c_str()) == NULL)
118  {
119  BIASWARN("environment variable "<<environmentVariable<<" not found");
120  return false;
121  }
122  return FindFile(getenv(environmentVariable.c_str()), baseFileName,
123  fullFileName);
124 }
125 
126 bool
127 IOUtils::FindShaderFile(const string& shaderFileName, string& res)
128 {
129  if (!IOUtils::FindFileEnv("SHADERSRC", shaderFileName, res))
130  {
131  cout << "failed loading shader " << shaderFileName << endl;
132  return false;
133  }
134  return true;
135 }
136 
137 string
138 IOUtils::ExtendOutName(const std::string& outname, const std::string& suffix,
139  const std::string& extension)
140 {
141  string path, base, ext;
142  FileHandling::SplitName(outname, path, base, ext);
143  path = FileHandling::StripTerminatingSlash(path);
144  if (path.size() == 0)
145  path = ".";
146  string pathbase;
147 #ifdef WIN32
148  pathbase = path + "\\"+ base;
149 #else
150  pathbase = path + "/" + base;
151 #endif
152 
153  return (pathbase + "_" + extension + "." + suffix);
154 }
155 
156 string
157 IOUtils::ExtendOutName(const std::string& outname, const std::string& extension)
158 {
159  string path, base, ext;
160  FileHandling::SplitName(outname, path, base, ext);
161  path = FileHandling::StripTerminatingSlash(path);
162  if (path.size() == 0)
163  path = ".";
164  string pathbase;
165 #ifdef WIN32
166  pathbase = path + "\\"+ base;
167 #else
168  pathbase = path + "/" + base;
169 #endif
170 
171  return (pathbase + "_" + extension + ext);
172 }
173 
174 
175 bool
176 IOUtils::ParseCommandLineEvalHelp(Param& params, int argc, char* argv[])
177 {
178  int miscGrpID = params.GetFreeGroupID();
179  bool* help = params.AddParamBool("help", "Display help message", false, 'h', miscGrpID);
180  params.SetGroupName(miscGrpID, "Misc");
181 
182  params.ParseCommandLine(argc, argv);
183  if (*help)
184  {
185  params.Usage();
186  return false;
187  }
188  return true;
189 }
190 
191 bool
192 IOUtils::ParseCommandLineEvalHelp(Param& params, int argc, char* argv[],
193  int& fup)
194 {
195  int miscGrpID = params.GetFreeGroupID();
196  bool* help = params.AddParamBool("help", "Display help message", false, 'h', miscGrpID);
197  params.SetGroupName(miscGrpID, "Misc");
198 
199  fup = params.ParseCommandLine(argc, argv);
200  if (*help)
201  {
202  params.Usage();
203  return false;
204  }
205  return true;
206 }
207 
208 void
209 IOUtils::PrintWithLineNumbers(const std::string& text, std::ostream& out)
210 {
211  std::istringstream in(text);
212  int lineNumber = 1;
213  std::string line;
214  while (std::getline(in, line))
215  {
216  out.width(3);
217  out << lineNumber << " | " << line << std::endl;
218  lineNumber++;
219  }
220 }
221 
222 #ifdef BIAS_HAVE_XML2
223 bool
224 IOUtils::GetProjectionParametersPerspective(ImageBase& imgBase,
226 {
227  Projection tempProj;
228  if (!GetProjection(imgBase, tempProj))
229  {
230  return false;
231  }
232  else
233  {
234  if (!CheckTypeDelete(tempProj.GetParameters()->Clone(), ppp))
235  {
236  BIASERR("contained projection is not of type projection parameters perspective!");
237  return false;
238  }
239  return true;
240  }
241 }
242 
243 bool
244 IOUtils::GetProjection(ImageBase& imgBase, Projection& projOut)
245 {
246  AppData ad;
247  MetaData* MD = imgBase.GetMetaData();
248  if (MD->Find(AppData::MD_Projection, "#[Projection]", ad) >= 0)
249  {
250  // BIASDOUT(D_CAMERAMD, "found Projection");
251  std::string flatproj;
252  if (ad.tag == AppData::MD_USE_ASCII)
253  flatproj = ad.sdata;
254 
255  else
256  {
257  char *tmp = new char[ad.length + 1];
258  memcpy(tmp, ad.data, ad.length);
259  tmp[ad.length] = 0;
260  flatproj = tmp;
261  //flatproj = flatproj.substr(0,ad.length);
262  delete[] tmp;
263  //cout << flatproj;
264  }
265 
266  int res = projOut.XMLReadFromString(flatproj);
267  if (res < 0)
268  {
269  BIASERR("Failed to parse string with length: "<<ad.length<<" string: "
270  <<flatproj);
271  return false;
272  }
273  //Proj_.GetParameters()->ValidatePose();
274  if (!projOut.GetParameters()->PoseValid())
275  {
276  BIASERR("returning invalid pose!");
277  return false;
278  }
279 
280  return true;
281 
282  }
283  return false;
284 }
285 
286 #endif //BIAS_HAVE_XML2
287 void
288 IOUtils::ProgressIndicator::operator++(int)
289 {
290  switch (indicatorState)
291  {
292  case 0:
293  std::cerr << "|";
294  break;
295  case 1:
296  std::cerr << "/";
297  break;
298  case 2:
299  std::cerr << "-";
300  break;
301  case 3:
302  std::cerr << "\\";
303  break;
304  }
305  std::cerr << "\b";
306  std::cerr << std::flush;
307  indicatorState++;
308  if (indicatorState > 3)
309  indicatorState = 0;
310 }
311 
312 void
313 IOUtils::ProgressIndicator::Reset()
314 {
315  indicatorState = 0;
316 }
317 
318 void
319 IOUtils::ProgressBar::Init(const int steps)
320 {
321  incrementThreshold_ = 1;
322  incrementPos_ = 0;
323  std::cerr << "[" << std::flush;
324  for (int i = 0; i < steps; i++)
325  {
326  std::cerr << "-";
327  }
328  std::cerr << "]\r[" << std::flush;
329 }
330 
331 void
332 IOUtils::ProgressBar::Init(const int steps, const int maxLength)
333 {
334  if (steps <= maxLength)
335  {
336  Init(steps);
337  }
338  else
339  {
340  float n = static_cast<float> (steps) / static_cast<float> (maxLength);
341  Init(maxLength);
342  incrementThreshold_ = static_cast<int> (ceil(n));
343  }
344 
345 }
346 
347 void
348 IOUtils::ProgressBar::operator++(int)
349 {
350  if (++incrementPos_ == incrementThreshold_)
351  {
352  if (clear_)
353  std::cerr << "\b";
354  std::cerr << "|" << std::flush;
355  incrementPos_ = 0;
356  }
357 }
358 
359 bool
360 IOUtils::LoadFloat(const std::string& filename, BIAS::Image<float>& outcome)
361 {
362  ImageBase img;
363  if (ImageIO::Load(filename, img) != 0)
364  {
365  BIASERR("could not load specified image named: "<<filename);
366  return false;
367  }
368  switch (img.GetStorageType())
369  {
370  case ImageBase::ST_float:
371  outcome = img;
372  outcome.SetMetaData(*img.GetMetaData());
373  break;
374  default:
375  outcome.Init(img.GetWidth(), img.GetHeight(), img.GetChannelCount());
376  if (ImageConvert::ConvertST(img, outcome, ImageBase::ST_float) != 0)
377  {
378  BIASERR("could not convert storage type!");
379  return false;
380  }
381  break;
382 
383  }
384 
385  return true;
386 }
387 
388 bool
389 IOUtils::SaveForPlot(const std::string& filename,
390  const std::vector<double>& x_vector, const std::vector<double>& y_vector)
391 {
392  BIASASSERT(x_vector.size() == y_vector.size());
393  std::ofstream fs(filename.c_str());
394  if (!fs)
395  {
396  return false; // error, could not open file.
397  }
398  else
399  {
400  // write out to disk
401  for (unsigned int row = 0; row < x_vector.size(); row++)
402  {
403  fs << x_vector[row] << "\t" << y_vector[row] << "\n";
404  }
405  fs.close();
406  };
407  return true;
408 }
409 
410 
411 bool
412 IOUtils::LoadImage(
413  const std::string& fileName,
414  ImageBase& img,
415  unsigned int& width,
416  unsigned int& height,
417  unsigned int& channels)
418 {
419  if(ImageIO::Load(fileName, img)!=0) {
420  BIASERR("could not load image named "<<fileName);
421  return false;
422  }
423  width = img.GetWidth();
424  height = img.GetHeight();
425  channels = img.GetChannelCount();
426 
427  return true;
428 }
429 
430 bool
431 IOUtils::ReadIn2DPointList(const std::string& fileName,
432  std::vector<BIAS::Vector2<int> >& pointLst)
433 {
434  std::ifstream ifs(fileName.c_str());
435  if (!ifs) {
436  ifs.close();
437  return false; // error, could not open file.
438  }
439  else {
440  Vector2<int> pt;
441  while(ifs) {
442 
443  ifs >> pt[0] ;
444  ifs >> pt[1] ;
445 
446  pointLst.push_back(pt);
447 
448  }
449  };
450  ifs.close();
451  return true;
452 
453 }
454 
455 
456 bool
457 IOUtils::ReadIn2DPointList(const std::string& fileName,
458  std::vector<unsigned int>& xPos,
459  std::vector<unsigned int>& yPos)
460 {
461  std::ifstream ifs(fileName.c_str());
462  if (!ifs) {
463  ifs.close();
464  return false; // error, could not open file.
465  }
466  else {
467  unsigned int x, y;
468  while(ifs) {
469 
470  ifs >> x ;
471  ifs >> y ;
472 
473  xPos.push_back(x);
474  yPos.push_back(y);
475 
476  }
477  };
478  ifs.close();
479  return true;
480 
481 }
482 
483 
484 
int XMLReadFromString(const std::string &str)
reconstruct xml tree from string
Definition: XMLBase.cpp:111
camera parameters which define the mapping between rays in the camera coordinate system and pixels in...
virtual ProjectionParametersBase * Clone() const =0
Covariant virtual copy constructor used in BIAS::Projection.
MetaData * GetMetaData()
Definition: ImageBase.hh:456
bool * AddParamBool(const std::string &name, const std::string &help, bool deflt=false, char cmdshort=0, int Group=GRP_NOSHOW)
Definition: Param.cpp:305
int length
number of bytes used by the data block
Definition: MetaData.hh:96
unsigned int GetWidth() const
Definition: ImageBase.hh:312
int ParseCommandLine(int &argc, char *argv[])
scan command line arguments for valid parameters
Definition: Param.cpp:1028
std::string sdata
the data as given in ascii meta data
Definition: MetaData.hh:102
char * data
pointer to block of data
Definition: MetaData.hh:98
void Usage(std::ostream &os=std::cout)
print Help-Information to stdout
Definition: Param.cpp:176
const ProjectionParametersBase * GetParameters(unsigned int cam=0) const
const parameter access function
Definition: Projection.hh:194
This class hides the underlying projection model, like projection matrix, spherical camera...
Definition: Projection.hh:70
virtual bool PoseValid() const
Check if current pose is valid.
unsigned int GetChannelCount() const
returns the number of Color channels, e.g.
Definition: ImageBase.hh:382
unsigned int GetHeight() const
Definition: ImageBase.hh:319
int GetFreeGroupID()
returns unused group id
Definition: Param.cpp:1421
int Find(const enum AppData::TAppData tag, AppData &data) const
searches for tag in binary coded AppDatas.
Definition: MetaData.cpp:363
enum TAppData tag
The tag defines the type of data, e.g.
Definition: MetaData.hh:94
void Init(unsigned int Width, unsigned int Height, unsigned int channels=1, enum EStorageType storageType=ST_unsignedchar, const bool interleaved=true)
calls Init from ImageBase storageType is ignored, just dummy argument
Definition: Image.cpp:421
This class Param provides generic support for parameters.
Definition: Param.hh:231
int SetGroupName(const int group_id, const std::string &name)
sets the name for a group
Definition: Param.cpp:1448
this class collects all additional data chunks of type AppData to be written into/read from an image ...
Definition: MetaData.hh:121
enum EStorageType GetStorageType() const
Definition: ImageBase.hh:414
void SetMetaData(const MetaData &m)
Definition: ImageBase.hh:470
This is the base class for images in BIAS.
Definition: ImageBase.hh:102
this is a chunk of metadata, also see MetaData
Definition: MetaData.hh:49