QTrk
Classes | Typedefs | Functions
utils.h File Reference
#include "std_incl.h"
#include "scalar_types.h"

Go to the source code of this file.

Classes

struct  TImageData< T >
 
class  CImageData
 
struct  PathSeperator
 
class  Matrix3X3
 

Typedefs

typedef TImageData< float > ImageData
 
typedef TImageData< double > ImageDatad
 

Functions

template<typename T >
bool isNAN (const T &v)
 
void GetFormattedTimeString (char *output)
 
std::string GetCurrentOutputPath (bool ext=true)
 
void dbgout (const std::string &s)
 
std::string SPrintf (const char *fmt,...)
 
void dbgprintf (const char *fmt,...)
 
void dbgsetlogfile (const char *path)
 
template<typename T >
void DeleteAllElems (T &c)
 
template<typename TPixel >
void normalize (TPixel *d, uint w, uint h)
 
template<typename T >
Lerp (T a, T b, float x)
 
template<typename T >
Interpolate (T *image, int width, int height, float x, float y, bool *outside=0)
 
template<typename T >
Interpolate1D (T *d, int len, float x)
 
template<typename T >
Interpolate1D (const std::vector< T > &d, float x)
 
template<typename T >
StdDeviation (T *start, T *end)
 
std::vector< float > ComputeRadialBinWindow (int rsteps)
 Calculate the radial weights for ZLUT profile comparisons. More...
 
float ComputeBgCorrectedCOM1D (float *data, int len, float cf=2.0f)
 
void ComputeCRP (float *dst, int radialSteps, int angularSteps, float minradius, float maxradius, vector2f center, ImageData *src, float mean, float *crpmap=0)
 
void ComputeRadialProfile (float *dst, int radialSteps, int angularSteps, float minradius, float maxradius, vector2f center, ImageData *src, float mean, bool normalize)
 
void NormalizeRadialProfile (float *prof, int rsteps)
 
void NormalizeZLUT (float *zlut, int numLUTs, int planes, int radialsteps)
 
void GenerateImageFromLUT (ImageData *image, ImageData *zlut, float minradius, float maxradius, vector3f pos, bool useSplineInterp=true, int ovs=4)
 
void ApplyPoissonNoise (ImageData &img, float poissonMax, float maxValue=255)
 
void ApplyGaussianNoise (ImageData &img, float sigma)
 
void WriteComplexImageAsCSV (const char *file, std::complex< float > *d, int w, int h, const char *labels[]=0)
 
void WriteArrayAsCSVRow (const char *file, float *d, int len, bool append)
 
void WriteVectorAsCSVRow (const char *file, std::vector< float > d, bool append)
 
void WriteImageAsCSV (const char *file, float *d, int w, int h, const char *labels[]=0)
 
std::vector< std::vector< float > > ReadCSV (const char *filename, char sep='\t')
 
std::vector< vector3fReadVector3CSV (const char *file, char sep='\t')
 
void WriteTrace (std::string file, vector3f *results, int nResults)
 
void GenerateTestImage (ImageData &img, float xp, float yp, float size, float MaxPhotons)
 
std::string GetLocalModuleFilename ()
 
std::string GetLocalModulePath ()
 
std::string GetDirectoryFromPath (std::string fullpath)
 
std::string file_ext (const char *f)
 
ImageData ReadJPEGFile (const char *fn)
 
ImageData ReadLUTFile (const char *lutfile)
 
int ReadJPEGFile (uchar *srcbuf, int srclen, uchar **data, int *width, int *height)
 
void WriteJPEGFile (uchar *data, int w, int h, const char *filename, int quality)
 
void FloatToJPEGFile (const char *name, const float *d, int w, int h)
 
void WriteJPEGFile (const char *name, const ImageData &img)
 
int NearestPowerOf2 (int v)
 
int NearestPowerOf3 (int v)
 
void GenerateGaussianSpotImage (ImageData *img, vector2f pos, float sigma, float I0, float Ibg)
 
std::vector< ucharReadToByteBuffer (const char *filename)
 
double GetPreciseTime ()
 
template<typename T >
void floatToNormalizedInt (T *dst, const float *src, uint w, uint h, T maxValue)
 
template<typename T >
T * floatToNormalizedInt (const float *src, uint w, uint h, T maxValue)
 
template<typename T >
ComputeStdDev (T *data, int len)
 
template<typename T >
qselect (T *data, int start, int end, int k)
 
template<typename T >
erf (T x)
 

Typedef Documentation

§ ImageData

typedef TImageData<float> ImageData

Definition at line 151 of file utils.h.

§ ImageDatad

typedef TImageData<double> ImageDatad

Definition at line 152 of file utils.h.

Function Documentation

§ ApplyGaussianNoise()

void ApplyGaussianNoise ( ImageData img,
float  sigma 
)

Definition at line 454 of file utils.cpp.

455 {
456  for (int k=0;k<img.numPixels();k++) {
457  float v = img.data[k] + sigma * rand_normal<float>();
458  if (v<0.0f) v= 0.0f;
459  img.data[k]=v;
460  }
461 }
int numPixels() const
Definition: utils.h:99
T * data
Definition: utils.h:80

§ ApplyPoissonNoise()

void ApplyPoissonNoise ( ImageData img,
float  poissonMax,
float  maxValue = 255 
)

Definition at line 432 of file utils.cpp.

433 {
434  /*auto f = [&] (int y) {
435  for (int x=0;x<img.w;x++) {
436  img.at(x,y) = rand_poisson<float>(factor*img.at(x,y));
437  }
438  };
439 
440  ThreadPool<int, std::function<void (int index)> > pool(f);
441 
442  for (int y=0;y<img.h;y++) {
443  pool.AddWork(y);
444  }
445  pool.WaitUntilDone();*/
446 
447  float ratio = maxval / poissonMax;
448 
449  for (int x=0;x<img.numPixels();x++) {
450  img[x] = (int)(rand_poisson<float>(poissonMax*img[x]) * ratio );
451  }
452 }
int numPixels() const
Definition: utils.h:99

§ ComputeBgCorrectedCOM1D()

float ComputeBgCorrectedCOM1D ( float *  data,
int  len,
float  cf = 2.0f 
)

Definition at line 231 of file utils.cpp.

232 {
233  float sum=0, sum2=0;
234  float moment=0;
235 
236  for (int x=0;x<len;x++) {
237  float v = data[x];
238  sum += v;
239  sum2 += v*v;
240  }
241 
242  float invN = 1.0f/len;
243  float mean = sum * invN;
244  float stdev = sqrtf(sum2 * invN - mean * mean);
245  sum = 0.0f;
246 
247  for(int x=0;x<len;x++)
248  {
249  float v = data[x];
250  v = std::max(0.0f, fabs(v-mean)-cf*stdev);
251  sum += v;
252  moment += x*v;
253  }
254  return moment / (float)sum;
255 }

§ ComputeCRP()

void ComputeCRP ( float *  dst,
int  radialSteps,
int  angularSteps,
float  minradius,
float  maxradius,
vector2f  center,
ImageData src,
float  mean,
float *  crpmap = 0 
)

Definition at line 181 of file utils.cpp.

183 {
184  vector2f* radialDirs = (vector2f*)ALLOCA(sizeof(vector2f)*angularSteps);
185  for (int j=0;j<angularSteps;j++) {
186  float ang = 2*3.141593f*j/(float)angularSteps;
187  radialDirs[j] = vector2f(cosf(ang), sinf(ang) );
188  }
189 
190  for (int i=0;i<radialSteps;i++)
191  dst[i]=0.0f;
192 
193  float* map = crpmap ? crpmap : (float*)ALLOCA(sizeof(float)*radialSteps*angularSteps);
194  float* com = (float*)ALLOCA(sizeof(float)*angularSteps);
195 
196  float rstep = (maxradius-minradius) / radialSteps;
197  float comsum = 0.0f;
198  for (int a=0;a<angularSteps;a++) {
199  float r = minradius;
200  float sum = 0.0f, moment=0.0f;
201  for (int i=0;i<radialSteps; i++) {
202  float x = center.x + radialDirs[a].x * r;
203  float y = center.y + radialDirs[a].y * r;
204  float v = img->interpolate(x,y);
205  r += rstep;
206  map[a*radialSteps+i] = v;
207  sum += v;
208  moment += i*v;
209  }
210  com[a] = moment/sum;
211  comsum += com[a];
212  }
213  float avgcom = comsum/angularSteps;
214  float totalrmssum2 = 0.0f;
215  for (int i=0;i<radialSteps; i++) {
216  double sum = 0.0f;
217  for (int a=0;a<angularSteps;a++) {
218  float shift = com[a]-avgcom;
219  sum += map[a*radialSteps+i];
220  }
221  dst[i] = sum/angularSteps-paddingValue;
222  totalrmssum2 += dst[i]*dst[i];
223  }
224  double invTotalrms = 1.0f/sqrt(totalrmssum2/radialSteps);
225  for (int i=0;i<radialSteps;i++) {
226  dst[i] *= invTotalrms;
227  }
228 }
vector2< float > vector2f
Definition: std_incl.h:39
vector3< T > sqrt(const vector3< T > &a)
Definition: std_incl.h:112
#define ALLOCA(size)
Definition: std_incl.h:151

§ ComputeRadialBinWindow()

std::vector<float> ComputeRadialBinWindow ( int  rsteps)

Calculate the radial weights for ZLUT profile comparisons.

Calculates a mask, a so-called 'Stetson window', to reduce the effect of the edges of the profile in the calculation of error curves.

Parameters
[in]rstepsThe number of radial steps in the window.

Definition at line 706 of file utils.cpp.

707 {
708  std::vector<float> wnd(rsteps);
709  for (int i=0;i<rsteps;i++) {
710  float x = i/(float)rsteps;
711  float t2 = 0.05f;
712  float t1 = 0.01f;
713  float fall = 1.0f-expf(-sq(1-x)/t2);
714  float rise = 1.0f-expf(-sq(x)/t1);
715  wnd[i] = sqrtf(fall*rise*x*2);
716  }
717  return wnd;
718 }
float sq(float x)
Definition: utils.cpp:352

§ ComputeRadialProfile()

void ComputeRadialProfile ( float *  dst,
int  radialSteps,
int  angularSteps,
float  minradius,
float  maxradius,
vector2f  center,
ImageData src,
float  mean,
bool  normalize 
)

Definition at line 298 of file utils.cpp.

300 {
301  vector2f* radialDirs = (vector2f*)ALLOCA(sizeof(vector2f)*angularSteps);
302  for (int j=0;j<angularSteps;j++) {
303  float ang = 2*3.141593f*j/(float)angularSteps;
304  radialDirs[j] = vector2f(cosf(ang), sinf(ang));
305  }
306 
307  for (int i=0;i<radialSteps;i++)
308  dst[i]=0.0f;
309 
310 // center.x += 0.5f;
311 // center.y += 0.5f;
312 
313  bool trace=false;
314  float rstep = (maxradius-minradius) / radialSteps;
315  int totalsmp = 0;
316 
317  //FILE* f = fopen("D:\\TestImages\\test.csv","w");
318 
319  for (int i=0;i<radialSteps; i++) {
320  double sum = 0.0f;
321 
322  int nsamples = 0;
323  float r = minradius+rstep*i;
324  for (int a=0;a<angularSteps;a++) {
325  float x = center.x + radialDirs[a].x * r;
326  float y = center.y + radialDirs[a].y * r;
327  bool outside;
328  float v = img->interpolate(x,y, &outside);
329  if (!outside) {
330  sum += v;
331  nsamples++;
332  }
333 
334  //fprintf(f,"%d\t%d\t%f\n",i,a,v);
335  }
336 
337  if (trace) {
338  dbgprintf("%f,[%d]; ", sum, nsamples);
339  }
340 
341  dst[i] = nsamples > MIN_RADPROFILE_SMP_COUNT ? sum/nsamples : mean;
342  }
343  if(trace)
344  dbgprintf("\n");
345 
346  //fclose(f);
347 
348  if (normalize)
349  NormalizeRadialProfile(dst, radialSteps);
350 }
void normalize(TPixel *d, uint w, uint h)
Definition: utils.h:27
void NormalizeRadialProfile(scalar_t *prof, int rsteps)
Definition: utils.cpp:257
vector2< float > vector2f
Definition: std_incl.h:39
#define MIN_RADPROFILE_SMP_COUNT
Minimum number of samples for a profile radial bin. Below this the image mean will be used...
Definition: QueuedTracker.h:74
void dbgprintf(const char *fmt,...)
Definition: utils.cpp:149
#define ALLOCA(size)
Definition: std_incl.h:151

§ ComputeStdDev()

template<typename T >
T ComputeStdDev ( T *  data,
int  len 
)

Definition at line 221 of file utils.h.

222 {
223  T sum = 0.0, sum2=0.0;
224  for (int a=0;a<len;a++) {
225  sum+=data[a];
226  sum2+=data[a]*data[a];
227  }
228  T mean = sum / len;
229  return sqrt(sum2 / len- mean * mean);
230 }
vector3< T > sqrt(const vector3< T > &a)
Definition: std_incl.h:112

§ dbgout()

void dbgout ( const std::string &  s)

Definition at line 143 of file utils.cpp.

143  {
144  OutputDebugString(s.c_str());
145  printf(s.c_str());
146  WriteToLog(s.c_str());
147 }
void WriteToLog(const char *str)
Definition: utils.cpp:88

§ dbgprintf()

void dbgprintf ( const char *  fmt,
  ... 
)

Definition at line 149 of file utils.cpp.

149  {
150  va_list ap;
151  va_start(ap, fmt);
152 
153  char buf[512];
154  VSNPRINTF(buf, sizeof(buf), fmt, ap);
155  OutputDebugString(buf);
156  fputs(buf,stdout);
157  WriteToLog(buf);
158 
159  va_end(ap);
160 }
#define VSNPRINTF
Definition: std_incl.h:150
void WriteToLog(const char *str)
Definition: utils.cpp:88

§ dbgsetlogfile()

void dbgsetlogfile ( const char *  path)

Definition at line 49 of file utils.cpp.

50 {
51  logFilename = path;
52 }
static std::string logFilename
Definition: utils.cpp:47

§ DeleteAllElems()

template<typename T >
void DeleteAllElems ( T &  c)

Definition at line 19 of file utils.h.

19  {
20  for(typename T::iterator i=c.begin();i!=c.end();++i)
21  delete *i;
22  c.clear();
23 }

§ erf()

template<typename T >
T erf ( x)

Definition at line 373 of file utils.h.

374 {
375  // constants
376  T a1 = 0.254829592f;
377  T a2 = -0.284496736f;
378  T a3 = 1.421413741f;
379  T a4 = -1.453152027f;
380  T a5 = 1.061405429f;
381  T p = 0.3275911f;
382 
383  // Save the sign of x
384  int sign = 1;
385  if (x < 0)
386  sign = -1;
387  x = fabs(x);
388 
389  // A&S formula 7.1.26
390  T t = 1.0f/(1.0f + p*x);
391  T y = 1.0f - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);
392 
393  return sign*y;
394 }

§ file_ext()

std::string file_ext ( const char *  f)

Definition at line 121 of file utils.cpp.

121  {
122  int l=strlen(f)-1;
123  while (l > 0) {
124  if (f[l] == '.')
125  return &f[l+1];
126  l--;
127  }
128  return "";
129 }

§ FloatToJPEGFile()

void FloatToJPEGFile ( const char *  name,
const float *  d,
int  w,
int  h 
)

Definition at line 189 of file fastjpg.cpp.

190 {
191  uchar* zlut_bytes = floatToNormalizedInt(d, w,h, (uchar)255);
192  WriteJPEGFile(zlut_bytes, w, h, name, 99);
193  delete[] zlut_bytes;
194 }
void floatToNormalizedInt(T *dst, const float *src, uint w, uint h, T maxValue)
Definition: utils.h:199
void WriteJPEGFile(uchar *data, int w, int h, const char *filename, int quality)
Definition: fastjpg.cpp:89
unsigned char uchar
Definition: std_incl.h:130

§ floatToNormalizedInt() [1/2]

template<typename T >
void floatToNormalizedInt ( T *  dst,
const float *  src,
uint  w,
uint  h,
maxValue 
)

Definition at line 199 of file utils.h.

200 {
201  float maxv = src[0];
202  float minv = src[0];
203  for (uint k=0;k<w*h;k++) {
204  maxv = std::max(maxv, src[k]);
205  minv = std::min(minv, src[k]);
206  }
207  for (uint k=0;k<w*h;k++)
208  dst[k] = maxValue * (src[k]-minv) / (maxv-minv);
209 }
unsigned int uint
Definition: std_incl.h:127

§ floatToNormalizedInt() [2/2]

template<typename T >
T* floatToNormalizedInt ( const float *  src,
uint  w,
uint  h,
maxValue 
)

Definition at line 213 of file utils.h.

214 {
215  T* r = new T[w*h];
216  floatToNormalizedInt(r,src,w,h, maxValue);
217  return r;
218 }
void floatToNormalizedInt(T *dst, const float *src, uint w, uint h, T maxValue)
Definition: utils.h:199

§ GenerateGaussianSpotImage()

void GenerateGaussianSpotImage ( ImageData img,
vector2f  pos,
float  sigma,
float  I0,
float  Ibg 
)

Definition at line 421 of file utils.cpp.

422 {
423  float edenom = 1/sqrt(2*sigma*sigma);
424  for (int y=0;y<img->h;y++)
425  for(int x=0;x<img->w;x++) {
426  float DeltaX = 0.5f * erf( (x-pos.x + .5f) * edenom ) - 0.5f * erf((x-pos.x - .5f) * edenom);
427  float DeltaY = 0.5f * erf( (y-pos.y + .5f) * edenom ) - 0.5f * erf((y-pos.y - .5f) * edenom);
428  img->at(x,y) = Ibg + I0 * DeltaX * DeltaY;
429  }
430 }
T erf(T x)
Definition: utils.h:373
vector3< T > sqrt(const vector3< T > &a)
Definition: std_incl.h:112
int h
Definition: utils.h:81
T & at(int x, int y)
Definition: utils.h:96
int w
Definition: utils.h:81

§ GenerateImageFromLUT()

void GenerateImageFromLUT ( ImageData image,
ImageData zlut,
float  minradius,
float  maxradius,
vector3f  pos,
bool  useSplineInterp = true,
int  ovs = 4 
)

Definition at line 354 of file utils.cpp.

355 {
356 // lut.w = radialcov * ( (image->w/2 * roicov ) - minradius );
357 // lut.w = radialcov * ( maxradius - minradius );
358 
359  float radialcov = zlut->w / (maxradius-minradius);
360  float* zinterp = (float*)ALLOCA(zlut->w * sizeof(float));
361 
362  if (splineInterp) {
363  int iz = std::max(1, std::min(zlut->h-3, (int)pos.z));
364  float weights[4];
365  float fz = pos.z-iz;
366  ComputeBSplineWeights(weights, fz);
367  // Interpolate ZLUT using B-spline weights
368  for (int r=0;r<zlut->w;r++) {
369  float zlutv = 0;
370  for (int i=0;i<4;i++)
371  zlutv += weights[i] * zlut->at(r, i-1+iz);
372  zinterp[r] = zlutv;
373  }
374  }
375  else {
376  // The two Z planes to interpolate between
377  int iz = (int)pos.z;
378  if (iz < 0)
379  zinterp = zlut->data;
380  else if (iz>=zlut->h-1)
381  zinterp = &zlut->data[ (zlut->h-1)*zlut->w ];
382  else {
383  float* zlut0 = &zlut->data [ (int)pos.z * zlut->w ];
384  float* zlut1 = &zlut->data [ ((int)pos.z + 1) * zlut->w ];
385  zinterp = (float*)ALLOCA(sizeof(float)*zlut->w);
386  for (int r=0;r<zlut->w;r++)
387  zinterp[r] = Lerp(zlut0[r], zlut1[r], pos.z-iz);
388  }
389  }
390 
391  int oversampleWidth=oversampleSubdiv,oversampleHeight=oversampleSubdiv;
392  float oxstep = 1.0f / oversampleWidth;
393  float oystep = 1.0f / oversampleHeight;
394 
395  for (int y=0;y<image->h;y++)
396  for (int x=0;x<image->w;x++)
397  {
398  float s = 0.0f;
399 
400  for (int ox=0;ox<oversampleWidth;ox++)
401  for (int oy=0;oy<oversampleHeight;oy++) {
402 
403  float X = x+(ox+0.5f)*oxstep - pos.x - 0.5f;
404  float Y = y+(oy+0.5f)*oystep - pos.y - 0.5f;
405 
406  float pixr = sqrtf(X*X+Y*Y);
407  float r = (pixr - minradius) * radialcov;
408 
409  if (r > zlut->w-2)
410  r = zlut->w-2;
411  if (r < 0) r = 0;
412 
413  int i=(int)r;
414  s += Lerp(zinterp[i], zinterp[i+1], r-i);
415  }
416 
417  image->at(x,y) = s/(oversampleWidth*oversampleHeight);
418  }
419 }
T Lerp(T a, T b, float x)
Definition: utils.h:40
int h
Definition: utils.h:81
T & at(int x, int y)
Definition: utils.h:96
void CUDA_SUPPORTED_FUNC ComputeBSplineWeights(float w[], float t)
Definition: CubicBSpline.h:15
#define ALLOCA(size)
Definition: std_incl.h:151
T * data
Definition: utils.h:80
int w
Definition: utils.h:81

§ GenerateTestImage()

void GenerateTestImage ( ImageData img,
float  xp,
float  yp,
float  size,
float  MaxPhotons 
)

Definition at line 162 of file utils.cpp.

163 {
164  float S = 1.0f/sqrt(size);
165  for (int y=0;y<img.h;y++) {
166  for (int x=0;x<img.w;x++) {
167  float X = x - xp;// + 0.5;
168  float Y = y - yp;// + 0.5;
169  float r = sqrtf(X*X+Y*Y)+1;
170  float v = sinf(r/(5*S)) * expf(-r*r*S*0.001f);
171  img.at(x,y)=v;
172  }
173  }
174 
175  if (SNratio>0) {
176  ApplyGaussianNoise(img, 1.0f/SNratio);
177  }
178  img.normalize();
179 }
void ApplyGaussianNoise(ImageData &img, float sigma)
Definition: utils.cpp:454
vector3< T > sqrt(const vector3< T > &a)
Definition: std_incl.h:112
void normalize()
Definition: utils.h:101
int h
Definition: utils.h:81
T & at(int x, int y)
Definition: utils.h:96
int w
Definition: utils.h:81

§ GetCurrentOutputPath()

std::string GetCurrentOutputPath ( bool  ext = true)

Definition at line 19 of file utils.cpp.

20 {
21  std::string base = "D:\\TestImages\\TestOutput\\";
22  std::string search = base + "*";
23  LPCSTR w_folder = _T(search.c_str());
24 
25  WIN32_FIND_DATA FindFileData;
26  HANDLE hFind;
27 
28  hFind = FindFirstFile(w_folder,&FindFileData);
29  std::string dirName;
30  while(FindNextFile(hFind,&FindFileData))
31  dirName = FindFileData.cFileName;
32  if(ext)
33  return SPrintf("%s%s\\%s",base.c_str(),dirName.c_str(),"ZLUTDiag\\");
34  else
35  return SPrintf("%s%s",base.c_str(),dirName.c_str());
36 }
std::string SPrintf(const char *fmt,...)
Definition: utils.cpp:132

§ GetDirectoryFromPath()

std::string GetDirectoryFromPath ( std::string  fullpath)

Definition at line 104 of file utils.cpp.

105 {
106  for (int i=fullpath.size()-1;i>=0;i--) {
107  if (fullpath[i] == '/' || fullpath[i] == '\\') {
108  return fullpath.substr(0, i);
109  }
110  }
111  return "";
112 }

§ GetFormattedTimeString()

void GetFormattedTimeString ( char *  output)

Definition at line 38 of file utils.cpp.

39 {
40  time_t rawtime;
41  struct tm * timeinfo;
42  time(&rawtime);
43  timeinfo = localtime(&rawtime);
44  sprintf(output, "%02d%02d%02d-%02d%02d%02d",timeinfo->tm_year-100,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
45 }

§ GetLocalModuleFilename()

std::string GetLocalModuleFilename ( )

Definition at line 54 of file utils.cpp.

55 {
56 #ifdef WIN32
57  char path[256];
58  HMODULE hm = NULL;
59 
60  GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
61  (LPCSTR) &GetLocalModuleFilename, &hm);
62 
63  GetModuleFileNameA(hm, path, sizeof(path));
64  return path;
65 #else
66  #error GetLocalModuleName() not implemented for this platform
67 #endif
68 }
std::string GetLocalModuleFilename()
Definition: utils.cpp:54

§ GetLocalModulePath()

std::string GetLocalModulePath ( )

Definition at line 114 of file utils.cpp.

115 {
116  std::string dllpath = GetLocalModuleFilename();
117  return GetDirectoryFromPath(dllpath);
118 }
std::string GetDirectoryFromPath(std::string fullpath)
Definition: utils.cpp:104
std::string GetLocalModuleFilename()
Definition: utils.cpp:54

§ GetPreciseTime()

double GetPreciseTime ( )

Definition at line 669 of file utils.cpp.

670 {
671  uint64_t freq, time;
672 
673  QueryPerformanceCounter((LARGE_INTEGER*)&time);
674  QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
675 
676  return (double)time / (double)freq;
677 }

§ Interpolate()

template<typename T >
T Interpolate ( T *  image,
int  width,
int  height,
float  x,
float  y,
bool *  outside = 0 
)
inline

Definition at line 43 of file utils.h.

44 {
45  int rx=x, ry=y;
46  if (rx<0 || ry <0 || rx+1 >= width || ry+1>=height) {
47  if (outside) *outside=true;
48  return 0.0f;
49  }
50  if (outside) *outside=false;
51 
52  T v00 = image[width*ry+rx];
53  T v10 = image[width*ry+rx+1];
54  T v01 = image[width*(ry+1)+rx];
55  T v11 = image[width*(ry+1)+rx+1];
56 
57  T v0 = Lerp(v00, v10, x-rx);
58  T v1 = Lerp(v01, v11, x-rx);
59 
60  return Lerp(v0, v1, y-ry);
61 }
T Lerp(T a, T b, float x)
Definition: utils.h:40

§ Interpolate1D() [1/2]

template<typename T >
T Interpolate1D ( T *  d,
int  len,
float  x 
)
inline

Definition at line 64 of file utils.h.

65 {
66  int fx = (int)x;
67  if (fx < 0) return d[0];
68  if (fx >= len-1) return d[len-1];
69  return (d[fx+1]-d[fx]) * (x-fx) + d[fx];
70 }

§ Interpolate1D() [2/2]

template<typename T >
T Interpolate1D ( const std::vector< T > &  d,
float  x 
)
inline

Definition at line 73 of file utils.h.

74 {
75  return Interpolate1D(&d[0],d.size(),x);
76 }
T Interpolate1D(T *d, int len, float x)
Definition: utils.h:64

§ isNAN()

template<typename T >
bool isNAN ( const T &  v)

Definition at line 6 of file utils.h.

6  {
7  return !(v == v);
8 }

§ Lerp()

template<typename T >
T Lerp ( a,
b,
float  x 
)
inline

Definition at line 40 of file utils.h.

40 { return a + (b-a)*x; }

§ NearestPowerOf2()

int NearestPowerOf2 ( int  v)

Definition at line 679 of file utils.cpp.

680 {
681  int r=1;
682  while (r < v)
683  r *= 2;
684  if ( fabsf(r-v) < fabsf(r/2-v) )
685  return r;
686  return r/2;
687 }

§ NearestPowerOf3()

int NearestPowerOf3 ( int  v)

Definition at line 689 of file utils.cpp.

690 {
691  int r=1;
692  while (r < v)
693  r *= 3;
694  if ( fabsf(r-v) < fabsf(r/3-v) )
695  return r;
696  return r/3;
697 }

§ normalize()

template<typename TPixel >
void normalize ( TPixel *  d,
uint  w,
uint  h 
)

Definition at line 27 of file utils.h.

28 {
29  TPixel maxv = d[0];
30  TPixel minv = d[0];
31  for (uint k=0;k<w*h;k++) {
32  maxv = std::max(maxv, d[k]);
33  minv = std::min(minv, d[k]);
34  }
35  for (uint k=0;k<w*h;k++)
36  d[k]=(d[k]-minv)/(maxv-minv);
37 }
unsigned int uint
Definition: std_incl.h:127

§ NormalizeRadialProfile()

void NormalizeRadialProfile ( float *  prof,
int  rsteps 
)

Definition at line 257 of file utils.cpp.

258 {
259  double sum=0.0f;
260  for (int i=0;i<rsteps;i++)
261  sum += prof[i];
262 
263  float mean =sum/rsteps;
264  double rmssum2 = 0.0;
265 
266  for (int i=0;i<rsteps;i++) {
267  prof[i] -= mean;
268  rmssum2 += prof[i]*prof[i];
269  }
270  double invTotalrms = 1.0f/sqrt(rmssum2/rsteps);
271  for (int i=0;i<rsteps;i++)
272  prof[i] *= invTotalrms;
273 
274 /*
275  scalar_t minVal = prof[0];
276  for (int i=0;i<rsteps;i++)
277  if(prof[i]<minVal) minVal=prof[i];
278 
279  float rms=0;
280  for (int i=0;i<rsteps;i++) {
281  prof[i]-=minVal;
282  rms += prof[i]*prof[i];
283  }
284  rms=1.0f/sqrt(rms);
285  for (int i=0;i<rsteps;i++) {
286  prof[i]*=rms;
287  }*/
288 }
vector3< T > sqrt(const vector3< T > &a)
Definition: std_incl.h:112

§ NormalizeZLUT()

void NormalizeZLUT ( float *  zlut,
int  numLUTs,
int  planes,
int  radialsteps 
)

Definition at line 291 of file utils.cpp.

292 {
293  for(int i=0;i<numBeads;i++)
294  for (int j=0;j<planes;j++)
295  NormalizeRadialProfile(&zlut[radialsteps*planes*i + radialsteps*j], radialsteps);
296 }
void NormalizeRadialProfile(scalar_t *prof, int rsteps)
Definition: utils.cpp:257

§ qselect()

template<typename T >
T qselect ( T *  data,
int  start,
int  end,
int  k 
)

Definition at line 233 of file utils.h.

234 {
235  if (end-start==1)
236  return data[start];
237 
238  // select one of the elements as pivot
239  int p = 0;
240  T value = data[p+start];
241  // swap with last value
242  std::swap(data[p+start], data[end-1]);
243 
244  // move all items < pivot to the left
245  int nSmallerItems=0;
246  for(int i=start;i<end-1;i++)
247  if(data[i]<value) {
248  std::swap(data[i], data[start+nSmallerItems]);
249  nSmallerItems++;
250  }
251  // pivot is now at [# items < pivot]
252  std::swap(data[start+nSmallerItems], data[end-1]);
253 
254  // we are trying to find the kth element
255  // so if pivotpos == k, we found it
256  // if k < pivotpos, we need to recurse left side
257  // if k > pivotpos, we need to recurse right side
258  int pivotpos = start+nSmallerItems;
259  if (k == pivotpos)
260  return data[k];
261  else if (k < pivotpos)
262  return qselect(data, start, pivotpos, k);
263  else
264  return qselect(data, pivotpos+1, end, k);
265 }
T qselect(T *data, int start, int end, int k)
Definition: utils.h:233

§ ReadCSV()

std::vector< std::vector<float> > ReadCSV ( const char *  filename,
char  sep = '\t' 
)

Definition at line 463 of file utils.cpp.

464 {
465  std::list< std::vector <float> > data;
466 
467  FILE *f=fopen(filename,"r");
468  if (f) {
469  std::string buf;
470  std::vector<float> vals;
471  while (!feof(f)) {
472  char c=fgetc(f);
473  if (c == sep || c=='\n') {
474  vals.push_back( atof(buf.c_str()) );
475  buf.clear();
476  }
477  if (c == '\n') {
478  data.push_back( vals );
479  vals.clear();
480  }
481 
482  if (c != sep && c!= '\n')
483  buf+=c;
484  }
485  fclose(f);
486  }
487 
488  std::vector<std::vector<float> > r;
489  r.reserve(data.size());
490  r.insert(r.begin(), data.begin(), data.end());
491  return r;
492 }

§ ReadJPEGFile() [1/2]

ImageData ReadJPEGFile ( const char *  fn)

Definition at line 626 of file utils.cpp.

627 {
628  int w, h;
629  uchar* imgdata;
630  std::vector<uchar> jpgdata = ReadToByteBuffer(fn);
631  ReadJPEGFile(&jpgdata[0], jpgdata.size(), &imgdata, &w,&h);
632 
633  float* fbuf = new float[w*h];
634  for (int x=0;x<w*h;x++)
635  fbuf[x] = imgdata[x]/255.0f;
636  delete[] imgdata;
637 
638  return ImageData(fbuf,w,h);
639 }
TImageData< float > ImageData
Definition: QueuedTracker.h:69
std::vector< uchar > ReadToByteBuffer(const char *filename)
Definition: utils.cpp:608
ImageData ReadJPEGFile(const char *fn)
Definition: utils.cpp:626
unsigned char uchar
Definition: std_incl.h:130

§ ReadJPEGFile() [2/2]

int ReadJPEGFile ( uchar srcbuf,
int  srclen,
uchar **  data,
int *  width,
int *  height 
)

Definition at line 12 of file fastjpg.cpp.

13 {
14  struct jpeg_decompress_struct cinfo;
15 
16  JSAMPARRAY buffer; /* Output row buffer */
17  int row_stride; /* physical row width in output buffer */
18  my_error_mgr jerr;
19  cinfo.err = jpeg_std_error(&jerr.pub);
20  jpeg_create_decompress(&cinfo);
21 
22  j_mem_src(&cinfo, srcbuf, srclen);
23 
24  /* Step 3: read file parameters with jpeg_read_header() */
25  jpeg_read_header(&cinfo, TRUE);
26 
27  jpeg_start_decompress(&cinfo);
28  row_stride = cinfo.output_width * cinfo.output_components;
29  /* Make a one-row-high sample array that will go away when done with image */
30  buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
31 
32  *width = cinfo.output_width;
33  *height = cinfo.output_height;
34  *data = new uchar[cinfo.output_width*cinfo.output_height];
35 
36 // ResizeLVArray2D(output, cinfo.output_height, cinfo.output_width);
37 
38  /* Step 6: while (scan lines remain to be read) */
39  /* jpeg_read_scanlines(...); */
40 
41  /* Here we use the library's state variable cinfo.output_scanline as the
42  * loop counter, so that we don't have to keep track ourselves.
43  */
44  uchar* dst = *data;
45  while (cinfo.output_scanline < cinfo.output_height) {
46  /* jpeg_read_scanlines expects an array of pointers to scanlines.
47  * Here the array is only one element long, but you could ask for
48  * more than one scanline at a time if that's more convenient.
49  */
50  jpeg_read_scanlines(&cinfo, buffer, 1);
51  /* Assume put_scanline_someplace wants a pointer and sample count. */
52 
53  unsigned char* src = buffer[0];
54  if (cinfo.output_components == 1) {
55  memcpy(dst, src, cinfo.output_width);
56  } else {
57  for (uint x=0;x<cinfo.output_width;x++)
58  dst[x] = src[x * cinfo.output_components];
59  }
60  dst += cinfo.output_width;
61  }
62 
63  /* Step 7: Finish decompression */
64  jpeg_finish_decompress(&cinfo);
65  /* We can ignore the return value since suspension is not possible
66  * with the stdio data source.
67  */
68 
69  /* Step 8: Release JPEG decompression object */
70 
71  /* This is an important step since it will release a good deal of memory. */
72  jpeg_destroy_decompress(&cinfo);
73 
74  /* After finish_decompress, we can close the input file.
75  * Here we postpone it until after no more JPEG errors are possible,
76  * so as to simplify the setjmp error logic above. (Actually, I don't
77  * think that jpeg_destroy can do an error exit, but why assume anything...)
78  */
79 // fclose(infile);
80 
81  /* At this point you may want to check to see whether any corrupt-data
82  * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
83  */
84 
85  return 1;
86 }
struct jpeg_error_mgr pub
Definition: fastjpg.cpp:9
unsigned int uint
Definition: std_incl.h:127
unsigned char uchar
Definition: std_incl.h:130

§ ReadLUTFile()

ImageData ReadLUTFile ( const char *  lutfile)

Definition at line 720 of file utils.cpp.

721 {
722  PathSeperator sep(lutfile);
723  if(sep.extension == "jpg") {
724  return ReadJPEGFile(lutfile);
725  }
726  else {
727  std::string fn = lutfile;
728  fn = std::string(fn.begin(), fn.begin()+fn.find('#'));
729  std::string num( ++( sep.extension.begin() + sep.extension.find('#') ), sep.extension.end());
730  int lutIndex = atoi(num.c_str());
731 
732  int nbeads, nplanes, nsteps;
733  FILE *f = fopen(fn.c_str(), "rb");
734 
735  if (!f)
736  throw std::runtime_error("Can't open " + fn);
737 
738  fread(&nbeads, 4, 1, f);
739  fread(&nplanes, 4, 1, f);
740  fread(&nsteps, 4, 1, f);
741 
742 
743  fseek(f, 12 + 4* (nsteps*nplanes * lutIndex), SEEK_SET);
744  ImageData lut = ImageData::alloc(nsteps,nplanes);
745  fread(lut.data, 4, nsteps*nplanes,f);
746  fclose(f);
747  lut.normalize();
748  return lut;
749  }
750 }
static TImageData alloc(int w, int h)
Definition: utils.h:110
void normalize()
Definition: utils.h:101
ImageData ReadJPEGFile(const char *fn)
Definition: utils.cpp:626
T * data
Definition: utils.h:80

§ ReadToByteBuffer()

std::vector<uchar> ReadToByteBuffer ( const char *  filename)

Definition at line 608 of file utils.cpp.

609 {
610  FILE *f = fopen(filename, "rb");
611 
612  if (!f)
613  throw std::runtime_error(SPrintf("%s was not found", filename));
614 
615  fseek(f, 0, SEEK_END);
616  int len = ftell(f);
617  fseek(f, 0, SEEK_SET);
618 
619  std::vector<uchar> buf(len);
620  fread(&buf[0], 1,len, f);
621 
622  fclose(f);
623  return buf;
624 }
std::string SPrintf(const char *fmt,...)
Definition: utils.cpp:132

§ ReadVector3CSV()

std::vector<vector3f> ReadVector3CSV ( const char *  file,
char  sep = '\t' 
)

Definition at line 494 of file utils.cpp.

495 {
496  auto data=ReadCSV(file ,sep);
497 
498  std::vector<vector3f> r(data.size());
499 
500  for (uint i=0;i<data.size();i++){
501  r[i]=vector3f(data[i][0],data[i][1],data[i][2]);
502  }
503  return r;
504 }
std::vector< std::vector< float > > ReadCSV(const char *filename, char sep)
Definition: utils.cpp:463
unsigned int uint
Definition: std_incl.h:127
vector3< float > vector3f
Definition: std_incl.h:114

§ SPrintf()

std::string SPrintf ( const char *  fmt,
  ... 
)

Definition at line 132 of file utils.cpp.

132  {
133  va_list ap;
134  va_start(ap, fmt);
135 
136  char buf[512];
137  VSNPRINTF(buf, sizeof(buf), fmt, ap);
138 
139  va_end(ap);
140  return buf;
141 }
#define VSNPRINTF
Definition: std_incl.h:150

§ StdDeviation()

template<typename T >
T StdDeviation ( T *  start,
T *  end 
)

Definition at line 139 of file utils.h.

139  {
140  T sum=0,sum2=0;
141  for (T* s = start; s!=end; ++s) {
142  sum+=*s; sum2+=(*s)*(*s);
143  }
144 
145  T invN = 1.0f/(end-start);
146  T mean = sum * invN;
147  return sqrt(sum2 * invN - mean * mean);
148 }
vector3< T > sqrt(const vector3< T > &a)
Definition: std_incl.h:112

§ WriteArrayAsCSVRow()

void WriteArrayAsCSVRow ( const char *  file,
float *  d,
int  len,
bool  append 
)

Definition at line 537 of file utils.cpp.

538 {
539  FILE *f = fopen(file, append?"a":"w");
540  if(f) {
541  for (int i=0;i<len;i++)
542  fprintf(f, "%.7f\t", d[i]);
543 
544  fprintf(f, "\n");
545  fclose(f);
546  }
547  else
548  dbgprintf("WriteArrayAsCSVRow: Unable to open file %s\n", file);
549 }
void dbgprintf(const char *fmt,...)
Definition: utils.cpp:149

§ WriteComplexImageAsCSV()

void WriteComplexImageAsCSV ( const char *  file,
std::complex< float > *  d,
int  w,
int  h,
const char *  labels[] = 0 
)

Definition at line 579 of file utils.cpp.

580 {
581  FILE* f = fopen(file, "w");
582 
583  if (!f) {
584  dbgprintf("WriteComplexImageAsCSV: Unable to open file %s\n", file);
585  return;
586  }
587 
588  if (labels) {
589  for (int i=0;i<w;i++) {
590  fprintf(f, "%s;\t", labels[i]);
591  }
592  fputs("\n", f);
593  }
594 
595  for (int y=0;y<h;y++) {
596  for (int x=0;x<w;x++)
597  {
598  float i=d[y*w+x].imag();
599  fprintf(f, "%f%+fi", d[y*w+x].real(), i);
600  if(x<w-1) fputs("\t", f);
601  }
602  fprintf(f, "\n");
603  }
604 
605  fclose(f);
606 }
void dbgprintf(const char *fmt,...)
Definition: utils.cpp:149

§ WriteImageAsCSV()

void WriteImageAsCSV ( const char *  file,
float *  d,
int  w,
int  h,
const char *  labels[] = 0 
)

Definition at line 551 of file utils.cpp.

552 {
553  FILE* f = fopen(file, "w");
554 
555  if (f) {
556 
557  if (labels) {
558  for (int i=0;i<w;i++) {
559  fprintf(f, "%s;\t", labels[i]);
560  }
561  fputs("\n", f);
562  }
563 
564  for (int y=0;y<h;y++) {
565  for (int x=0;x<w;x++)
566  {
567  fprintf(f, "%.10f", d[y*w+x]);
568  if(x<w-1) fputs("\t", f);
569  }
570  fprintf(f, "\n");
571  }
572 
573  fclose(f);
574  }
575  else
576  dbgprintf("WriteImageAsCSV: Unable to open file %s\n", file);
577 }
void dbgprintf(const char *fmt,...)
Definition: utils.cpp:149

§ WriteJPEGFile() [1/2]

void WriteJPEGFile ( uchar data,
int  w,
int  h,
const char *  filename,
int  quality 
)

Definition at line 89 of file fastjpg.cpp.

90 {
91  /* This struct contains the JPEG compression parameters and pointers to
92  * working space (which is allocated as needed by the JPEG library).
93  * It is possible to have several such structures, representing multiple
94  * compression/decompression processes, in existence at once. We refer
95  * to any one struct (and its associated working data) as a "JPEG object".
96  */
97  struct jpeg_compress_struct cinfo;
98  /* This struct represents a JPEG error handler. It is declared separately
99  * because applications often want to supply a specialized error handler
100  * (see the second half of this file for an example). But here we just
101  * take the easy way out and use the standard error handler, which will
102  * print a message on stderr and call exit() if compression fails.
103  * Note that this struct must live as long as the main JPEG parameter
104  * struct, to avoid dangling-pointer problems.
105  */
106  struct jpeg_error_mgr jerr;
107  /* More stuff */
108  JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
109  int row_stride; /* physical row width in image buffer */
110 
111  /* Step 1: allocate and initialize JPEG compression object */
112 
113  /* We have to set up the error handler first, in case the initialization
114  * step fails. (Unlikely, but it could happen if you are out of memory.)
115  * This routine fills in the contents of struct jerr, and returns jerr's
116  * address which we place into the link field in cinfo.
117  */
118  cinfo.err = jpeg_std_error(&jerr);
119  /* Now we can initialize the JPEG compression object. */
120  jpeg_create_compress(&cinfo);
121 
122  /* Step 2: specify data destination (eg, a file) */
123  /* Note: steps 2 and 3 can be done in either order. */
124 
125  uint len = w*h * 2;
126  uchar* memBuf = new uchar[len];
127  j_mem_dest(&cinfo, (void**)&memBuf, &len);
128  //jpeg_stdio_dest(&cinfo, outfile);
129 
130  /* Step 3: set parameters for compression */
131 
132  /* First we supply a description of the input image.
133  * Four fields of the cinfo struct must be filled in:
134  */
135  cinfo.image_width = w; /* image width and height, in pixels */
136  cinfo.image_height = h;
137  cinfo.input_components = 1; /* # of color components per pixel */
138  cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
139  /* Now use the library's routine to set default compression parameters.
140  * (You must set at least cinfo.in_color_space before calling this,
141  * since the defaults depend on the source color space.)
142  */
143  jpeg_set_defaults(&cinfo);
144  /* Now you can set any non-default parameters you wish to.
145  * Here we just illustrate the use of quality (quantization table) scaling:
146  */
147  jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
148 
149  /* Step 4: Start compressor */
150 
151  /* TRUE ensures that we will write a complete interchange-JPEG file.
152  * Pass TRUE unless you are very sure of what you're doing.
153  */
154  jpeg_start_compress(&cinfo, TRUE);
155 
156  /* Step 5: while (scan lines remain to be written) */
157  /* jpeg_write_scanlines(...); */
158 
159  /* Here we use the library's state variable cinfo.next_scanline as the
160  * loop counter, so that we don't have to keep track ourselves.
161  * To keep things simple, we pass one scanline per call; you can pass
162  * more if you wish, though.
163  */
164  row_stride = w; /* JSAMPLEs per row in image_buffer */
165 
166  while (cinfo.next_scanline < cinfo.image_height) {
167  /* jpeg_write_scanlines expects an array of pointers to scanlines.
168  * Here the array is only one element long, but you could pass
169  * more than one scanline at a time if that's more convenient.
170  */
171  row_pointer[0] = &data[cinfo.next_scanline * row_stride];
172  (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
173  }
174  jpeg_finish_compress(&cinfo);
175  jpeg_destroy_compress(&cinfo);
176 
177 
178  FILE *f = fopen(filename, "wb");
179  if (f) {
180  fwrite(memBuf, 1, len, f);
181  fclose(f);
182  } else
183  dbgprintf("Failed to open file %s for writing\n", filename);
184 
185  delete[] memBuf;
186 }
unsigned int uint
Definition: std_incl.h:127
void dbgprintf(const char *fmt,...)
Definition: utils.cpp:149
unsigned char uchar
Definition: std_incl.h:130

§ WriteJPEGFile() [2/2]

void WriteJPEGFile ( const char *  name,
const ImageData img 
)
inline

Definition at line 190 of file utils.h.

190 { FloatToJPEGFile(name, img.data, img.w,img.h); }
void FloatToJPEGFile(const char *name, const float *d, int w, int h)
Definition: fastjpg.cpp:189
int h
Definition: utils.h:81
int w
Definition: utils.h:81
T * data
Definition: utils.h:80

§ WriteTrace()

void WriteTrace ( std::string  file,
vector3f results,
int  nResults 
)

Definition at line 507 of file utils.cpp.

508 {
509  FILE *f = fopen(filename.c_str(), "w");
510 
511  if (!f) {
512  throw std::runtime_error(SPrintf("Can't open %s", filename.c_str()));
513  }
514 
515  for (int i=0;i<nResults;i++)
516  {
517  fprintf(f, "%.7f\t%.7f\t%.7f\n", results[i].x, results[i].y, results[i].z);
518  }
519 
520  fclose(f);
521 }
std::string SPrintf(const char *fmt,...)
Definition: utils.cpp:132

§ WriteVectorAsCSVRow()

void WriteVectorAsCSVRow ( const char *  file,
std::vector< float >  d,
bool  append 
)

Definition at line 523 of file utils.cpp.

524 {
525  FILE *f = fopen(file, append?"a":"w");
526  if(f) {
527  for (uint i=0;i<d.size();i++)
528  fprintf(f, "%1.7f\t", d[i]);
529 
530  fprintf(f, "\n");
531  fclose(f);
532  }
533  else
534  dbgprintf("WriteArrayAsCSVRow: Unable to open file %s\n", file);
535 }
unsigned int uint
Definition: std_incl.h:127
void dbgprintf(const char *fmt,...)
Definition: utils.cpp:149