Xmipp  v3.23.11-Nereus
Public Member Functions | Public Attributes | List of all members
ProgOpticalAligment Class Reference
Inheritance diagram for ProgOpticalAligment:
Inheritance graph
[legend]
Collaboration diagram for ProgOpticalAligment:
Collaboration graph
[legend]

Public Member Functions

void defineParams ()
 
void readParams ()
 
void saveMat (const FileName &fnOut, const cv::Mat &M)
 
void readMat (const FileName &fnIn, cv::Mat &M)
 
void xmipp2Opencv (const MultidimArray< float > &xmippArray, cv::Mat &opencvMat)
 
void opencv2Xmipp (const cv::Mat &opencvMat, MultidimArray< float > &xmippArray)
 
void convert2Uint8 (cv::Mat opencvDoubleMat, cv::Mat &opencvUintMat)
 
void applyWindow (MultidimArray< double > &data)
 
int computeAvg (size_t begin, size_t end, cv::Mat &cvAvgImg)
 
void evaluateDisplacements (const cv::Mat *flowCurrentGroup, const cv::Mat *flowPreviousGroup, Matrix1D< double > &meanStdDev)
 
void removeFlows (int level)
 
void produceSideInfo ()
 
void run ()
 
- Public Member Functions inherited from XmippProgram
const char * getParam (const char *param, int arg=0)
 
const char * getParam (const char *param, const char *subparam, int arg=0)
 
int getIntParam (const char *param, int arg=0)
 
int getIntParam (const char *param, const char *subparam, int arg=0)
 
double getDoubleParam (const char *param, int arg=0)
 
double getDoubleParam (const char *param, const char *subparam, int arg=0)
 
float getFloatParam (const char *param, int arg=0)
 
float getFloatParam (const char *param, const char *subparam, int arg=0)
 
void getListParam (const char *param, StringVector &list)
 
int getCountParam (const char *param)
 
bool checkParam (const char *param)
 
bool existsParam (const char *param)
 
void addParamsLine (const String &line)
 
void addParamsLine (const char *line)
 
ParamDefgetParamDef (const char *param) const
 
virtual void quit (int exit_code=0) const
 
virtual int tryRun ()
 
void initProgress (size_t total, size_t stepBin=60)
 
void setProgress (size_t value=0)
 
void endProgress ()
 
void processDefaultComment (const char *param, const char *left)
 
void setDefaultComment (const char *param, const char *comment)
 
virtual void initComments ()
 
void setProgramName (const char *name)
 
void addUsageLine (const char *line, bool verbatim=false)
 
void clearUsage ()
 
void addExampleLine (const char *example, bool verbatim=true)
 
void addSeeAlsoLine (const char *seeAlso)
 
void addKeywords (const char *keywords)
 
const char * name () const
 
virtual void usage (int verb=0) const
 
virtual void usage (const String &param, int verb=2)
 
int version () const
 
virtual void show () const
 
virtual void read (int argc, const char **argv, bool reportErrors=true)
 
virtual void read (int argc, char **argv, bool reportErrors=true)
 
void read (const String &argumentsLine)
 
 XmippProgram ()
 
 XmippProgram (int argc, const char **argv)
 
virtual ~XmippProgram ()
 

Public Attributes

FileName fnMovie
 
FileName fnOut
 
FileName fnGain
 
FileName fnDark
 
FileName fnMovieOut
 
FileName fnMicOut
 
FileName fnMovieUncOut
 
FileName fnMicUncOut
 
FileName fnMicInitial
 
MetaDataVec movie
 
int winSize
 
int gpuDevice
 
int nfirst
 
int nlast
 
int numberOfFrames
 
int finalGroupSize
 
bool globalShiftCorr
 
bool inMemory
 
double dose0
 
double doseStep
 
double accelerationVoltage
 
double sampling
 
int compensationMode
 
int xLTcorner
 
int yLTcorner
 
int xDRcorner
 
int yDRcorner
 
FileName fnmovieRoot
 
FileName fnTempStack
 
FileName fnBaseOut
 
size_t Xdim
 
size_t Ydim
 
size_t Zdim
 
size_t Ndim
 
MultidimArray< float > tempStack
 
Image< float > tempAvg
 
FourierTransformer transformer
 
ProgMovieFilterDosefilterDose
 
- Public Attributes inherited from XmippProgram
bool doRun
 
bool runWithoutArgs
 
int verbose
 Verbosity level. More...
 
int debug
 

Additional Inherited Members

- Protected Member Functions inherited from XmippProgram
void defineCommons ()
 
- Protected Attributes inherited from XmippProgram
int errorCode
 
ProgramDefprogDef
 Program definition and arguments parser. More...
 
std::map< String, CommentListdefaultComments
 
int argc
 Original command line arguments. More...
 
const char ** argv
 

Detailed Description

Definition at line 62 of file movie_optical_alignment_cpu.cpp.

Member Function Documentation

◆ applyWindow()

void ProgOpticalAligment::applyWindow ( MultidimArray< double > &  data)
inline

Definition at line 224 of file movie_optical_alignment_cpu.cpp.

225  {
226  if (yDRcorner!=-1)
228  }
void selfWindow(int n0, int z0, int y0, int x0, int nF, int zF, int yF, int xF, T init_value=0)

◆ computeAvg()

int ProgOpticalAligment::computeAvg ( size_t  begin,
size_t  end,
cv::Mat &  cvAvgImg 
)
inline

Definition at line 231 of file movie_optical_alignment_cpu.cpp.

232  {
233  Image<float> frame;
234  end=std::min(end,movie.size()-1);
235  end=std::min(end,(size_t)nlast);
236  if (begin>end)
237  return 0;
238 // std::cout << "Computing average: " << begin << " " << end << std::endl;
239 
240  for (size_t i=begin;i<=end;i++)
241  {
242  int actualIdx=i-nfirst;
243  if (inMemory)
244  frame().aliasImageInStack(tempStack,actualIdx);
245  else
246  {
247 // std::cout << "Reading " << fnTempStack << " " << actualIdx+1 << std::endl;
248  frame.read(fnTempStack,DATA,actualIdx+1);
249  }
250 
251  if (i==begin)
252  tempAvg()=frame();
253  else
254  tempAvg()+=frame();
255  }
256  tempAvg()/=float(end-begin+1);
257 // std::cout << "Avg stats: "; tempAvg().printStats(); std::cout << std::endl;
258  xmipp2Opencv(tempAvg(), cvAvgImg);
259  return end-begin+1;
260  }
void min(Image< double > &op1, const Image< double > &op2)
size_t size() const override
#define i
MultidimArray< float > tempStack
void xmipp2Opencv(const MultidimArray< float > &xmippArray, cv::Mat &opencvMat)
int read(const FileName &name, DataMode datamode=DATA, size_t select_img=ALL_IMAGES, bool mapData=false, int mode=WRITE_READONLY)

◆ convert2Uint8()

void ProgOpticalAligment::convert2Uint8 ( cv::Mat  opencvDoubleMat,
cv::Mat &  opencvUintMat 
)
inline

Definition at line 216 of file movie_optical_alignment_cpu.cpp.

217  {
218  double min,max;
219  cv::minMaxLoc(opencvDoubleMat, &min, &max);
220  opencvDoubleMat.convertTo(opencvUintMat, CV_8U, 255.0/(max - min), -min * 255.0/(max - min));
221  }
void min(Image< double > &op1, const Image< double > &op2)
void max(Image< double > &op1, const Image< double > &op2)

◆ defineParams()

void ProgOpticalAligment::defineParams ( )
inlinevirtual

Function in which the param of each Program are defined.

Reimplemented from XmippProgram.

Definition at line 95 of file movie_optical_alignment_cpu.cpp.

96  {
97  addUsageLine ("Align movies using optical flow");
98  addParamsLine(" -i <inMoviewFnName> : input movie File Name");
99  addParamsLine(" [-o <fn=\"out.xmd\">] : Metadata with the shifts of each frame.");
100  addParamsLine(" [--oavg <fn=\"\">] : Give the name of a micrograph to generate an aligned micrograph");
101  addParamsLine(" [--oavgInitial <fn=\"\">] : Use this option to save the initial average micrograph ");
102  addParamsLine(" : before applying any alignment. ");
103  addParamsLine(" [--oUnc <fnMic=\"\"> <fnMovie=\"\">] : Give the name of a micrograph and movie to generate an aligned and dose uncompensated micrograph");
104  addParamsLine(" [--cropULCorner <x=0> <y=0>] : crop up left corner (unit=px, index starts at 0)");
105  addParamsLine(" [--cropDRCorner <x=-1> <y=-1>] : crop down right corner (unit=px, index starts at 0), -1 -> no crop");
106  addParamsLine(" [--frameRange <n0=-1> <nF=-1>] : First and last frame to align, frame numbers start at 0");
107  addParamsLine(" [--bin <s=-1>] : Binning factor, it may be any floating number");
108  addParamsLine(" [--winSize <int=150>] : window size for optical flow algorithm");
109  addParamsLine(" [--groupSize <int=1>] : the depth of pyramid for optical flow algorithm");
110  addParamsLine(" [--outMovie <fn=\"\">] : save corrected, dose compensated stack");
111  addParamsLine(" [--dark <fn=\"\">] : Dark correction image");
112  addParamsLine(" [--gain <fn=\"\">] : Gain correction image (we will multiply by it)");
113  addParamsLine(" [--inmemory] : Do not write a temporary file with the ");
114  addParamsLine(" [--doseCorrection <dosePerFrame=0> <Ts=1> <kV=200> <previousDose=0> <mode=\"pre\">] : Set dosePerFrame to 0 if you do not want to correct by the dose");
115  addParamsLine(" : Dose in e/A^2, Sampling rate (Ts) in A. Valid modes are pre and post");
116  addParamsLine(" : Pre compensates before aligning and post after aligning");
117 
118 #ifdef GPU
119  addParamsLine(" [--gpu <int=0>] : GPU device to be used");
120 #endif
121  }
void addUsageLine(const char *line, bool verbatim=false)
void addParamsLine(const String &line)

◆ evaluateDisplacements()

void ProgOpticalAligment::evaluateDisplacements ( const cv::Mat *  flowCurrentGroup,
const cv::Mat *  flowPreviousGroup,
Matrix1D< double > &  meanStdDev 
)
inline

Definition at line 262 of file movie_optical_alignment_cpu.cpp.

263  {
264  double sumX=0, sumY=0;
265  double absSumX=0, absSumY=0;
266  double sqSumX=0, sqSumY=0;
267  double valSubtract;
268  int h=flowCurrentGroup[0].rows;
269  int w=flowCurrentGroup[0].cols;
270  for(int i=0;i<h;i++)
271  for(int j=0;j<w;j++)
272  {
273  valSubtract=flowCurrentGroup[0].at<float>(i,j)-flowPreviousGroup[0].at<float>(i,j);
274  sumX+=valSubtract;
275  absSumX+=abs(valSubtract);
276  sqSumX+=valSubtract*valSubtract;
277  valSubtract=flowCurrentGroup[1].at<float>(i,j)-flowPreviousGroup[1].at<float>(i,j);
278  sumY+=valSubtract;
279  absSumY+=abs(valSubtract);
280  sqSumY+=valSubtract*valSubtract;
281  }
282  double n=h*w;
283  double avgX=sumX/n;
284  double avgY=sumY/n;
285  meanStdDev(0)=absSumX/n;
286  meanStdDev(1)=sqrt(std::max(sqSumX/n-avgX*avgX,0.0));
287  meanStdDev(2)=absSumY/n;
288  meanStdDev(3)=sqrt(std::max(sqSumY/n-avgY*avgY,0.0));
289  }
void sqrt(Image< double > &op)
doublereal * w
void abs(Image< double > &op)
#define i
void max(Image< double > &op1, const Image< double > &op2)
#define j
int * n

◆ opencv2Xmipp()

void ProgOpticalAligment::opencv2Xmipp ( const cv::Mat &  opencvMat,
MultidimArray< float > &  xmippArray 
)
inline

Definition at line 206 of file movie_optical_alignment_cpu.cpp.

207  {
208  int h = opencvMat.rows;
209  int w = opencvMat.cols;
210  xmippArray.resizeNoCopy(h, w);
211  for (int row=0; row<h; ++row)
212  memcpy(&DIRECT_A2D_ELEM(xmippArray,row,0),&opencvMat.at<float>(row,0),XSIZE(xmippArray)*sizeof(float));
213  }
void resizeNoCopy(const MultidimArray< T1 > &v)
#define DIRECT_A2D_ELEM(v, i, j)
doublereal * w
#define XSIZE(v)

◆ produceSideInfo()

void ProgOpticalAligment::produceSideInfo ( )
inline

Definition at line 305 of file movie_optical_alignment_cpu.cpp.

306  {
309 
310  // If input is an stack create a metadata.
311  if (fnMovie.isMetaData())
312  {
313  movie.read(fnMovie);
315  Ndim=movie.size();
316  }
317  else
318  {
319  ImageGeneric movieStack;
320  movieStack.read(fnMovie,HEADER);
321  movieStack.getDimensions(Xdim,Ydim,Zdim,Ndim);
322  if (fnMovie.getExtension()=="mrc" and Ndim ==1)
323  Ndim = Zdim;
324  size_t id;
325  FileName fn;
326  for (size_t i=0;i<Ndim;i++)
327  {
328  id = movie.addObject();
330  movie.setValue(MDL_IMAGE, fn, id);
331  }
332  }
333 
334  // Get corners
335  if (yDRcorner!=-1)
336  {
337  Xdim = xDRcorner - xLTcorner +1 ;
338  Ydim = yDRcorner - yLTcorner +1 ;
339  }
340  if (Zdim!=1)
341  REPORT_ERROR(ERR_ARG_INCORRECT,"This program is meant to align 2D frames, not 3D");
342 
343  // Dark and gain images
344  Image<double> dark, igain;
345  if (fnDark!="")
346  {
347  dark.read(fnDark);
348  applyWindow(dark());
349  }
350 
351  if (fnGain!="")
352  {
353  igain.read(fnGain);
354  applyWindow(igain());
355  // Pablo with coss: Consistency with other alignment methods
356  // Do not divide by the gain, as the gain is expected to be inverted already
357  double avg = igain().computeAvg();
358  if (std::isinf(avg) || std::isnan(avg))
360  "The input gain image is incorrect, it contains infinite or nan");
361  }
362 
363  // Count the number of frames to process
365  if (nfirst<0)
366  nfirst=0;
367  if (nlast<0)
370 
371  // Initialize the stack for the output movie
372  if (!fnMovieOut.isEmpty())
374  if (!fnMovieUncOut.isEmpty())
376 
377  // Prepare stack
378  if (inMemory)
380  else
381  {
382  fnTempStack=fnmovieRoot+"tmpMovie.stk";
384  }
385 
386  int currentFrameInIdx=0,currentFrameOutIdx=0;
387  FileName fnFrame;
388  Image<double> frameImage, translatedImage;
389  MultidimArray<float> Ifloat;
390  Matrix1D<double> shift(2);
394  for (size_t objId : movie.ids())
395  {
396  if (currentFrameInIdx>=nfirst && currentFrameInIdx<=nlast)
397  {
398  movie.getValue(MDL_IMAGE, fnFrame, objId);
399  frameImage.read(fnFrame);
400  applyWindow(frameImage());
401 
402  if (XSIZE(dark())>0)
403  frameImage()-=dark();
404  if (XSIZE(igain())>0)
405  frameImage()*=igain();
406 
408  {
409  movie.getValue(MDL_SHIFT_X, XX(shift), objId);
410  movie.getValue(MDL_SHIFT_Y, YY(shift), objId);
411  if (fabs(XX(shift))>0 || fabs(YY(shift))>0)
412  {
413 // std::cout << "Translating " << fnFrame << " by " << shift.transpose() << std::endl;
414  translate(xmipp_transformation::BSPLINE3, translatedImage(), frameImage(), shift, xmipp_transformation::WRAP);
415  frameImage()=translatedImage();
416  }
417  }
418 
419  if (fnMovieUncOut!="")
420  frameImage.write(fnMovieUncOut, currentFrameOutIdx+1, true, WRITE_REPLACE);
421 
423  {
424  transformer.FourierTransform(frameImage(), FFTI, false);
425  filterDose->applyDoseFilterToImage(YSIZE(frameImage()), XSIZE(frameImage()), FFTI,
426  dose0+currentFrameInIdx*doseStep, dose0+(currentFrameInIdx+1)*doseStep);
428  }
429 // std::cout << "Reading " << fnFrame << " "; frameImage().printStats(); std::cout << std::endl;
430  if (inMemory)
431  {
432  typeCast(frameImage(),Ifloat);
433  memcpy(&DIRECT_NZYX_ELEM(tempStack,currentFrameOutIdx,0,0,0),&Ifloat(0,0),MULTIDIM_SIZE(Ifloat)*sizeof(float));
434  }
435  else
436  {
437  frameImage.write(fnTempStack, currentFrameOutIdx+1, true, WRITE_REPLACE);
438 // std::cout << "Writing " << currentFrameOutIdx+1 << "@" << fnTempStack << std::endl;
439  }
440  currentFrameOutIdx++;
441  }
442  currentFrameInIdx++;
443  }
444  }
#define PRECOMPENSATION
#define YSIZE(v)
void applyDoseFilterToImage(int Ydim, int Xdim, const MultidimArray< std::complex< double > > &FFT1, const double dose_start, const double dose_finish)
Apply a dose filter to the image Fourier transform.
#define DIRECT_NZYX_ELEM(v, l, k, i, j)
void inverseFourierTransform()
Definition: xmipp_fftw.cpp:329
void read(const FileName &inFile, const std::vector< MDLabel > *desiredLabels=nullptr, bool decomposeStack=true) override
#define REPORT_ERROR(nerr, ErrormMsg)
Definition: xmipp_error.h:211
#define MULTIDIM_SIZE(v)
void resizeNoCopy(const MultidimArray< T1 > &v)
Shift for the image in the X axis (double)
void write(const FileName &name="", size_t select_img=ALL_IMAGES, bool isStack=false, int mode=WRITE_OVERWRITE, CastWriteMode castMode=CW_CAST, int _swapWrite=0)
void getImageSize(const MetaData &md, size_t &Xdim, size_t &Ydim, size_t &Zdim, size_t &Ndim, MDLabel image_label)
void compose(const String &str, const size_t no, const String &ext="")
FileName removeDirectories(int keep=0) const
ProgMovieFilterDose * filterDose
void applyWindow(MultidimArray< double > &data)
virtual IdIteratorProxy< false > ids()
size_t size() const override
#define i
String getExtension() const
#define XX(v)
Definition: matrix1d.h:85
void getDimensions(size_t &Xdim, size_t &Ydim, size_t &Zdim, size_t &Ndim) const
bool setValue(const MDObject &mdValueIn, size_t id)
size_t addObject() override
Incorrect argument received.
Definition: xmipp_error.h:113
#define XSIZE(v)
void createEmptyFile(const FileName &filename, int xdim, int ydim, int Zdim, size_t select_img, bool isStack, int mode, int _swapWrite, const MDRowVec *md)
void FourierTransform(T &v, T1 &V, bool getCopy=true)
Definition: xmipp_fftw.h:166
#define YY(v)
Definition: matrix1d.h:93
bool getValue(MDObject &mdValueOut, size_t id) const override
bool isMetaData(bool failIfNotExists=true) const
void translate(PDB *pdb_original, PDB *pdb_move, unsigned num_atoms, double x0, double y0, double z0)
Definition: lib_pwk.cpp:125
MultidimArray< float > tempStack
bool isEmpty() const
void typeCast(const Matrix1D< T1 > &v1, Matrix1D< T2 > &v2)
Definition: matrix1d.h:1227
FileName getDir() const
int read(const FileName &name, DataMode datamode=DATA, size_t select_img=ALL_IMAGES, bool mapData=false, int mode=WRITE_READONLY)
#define FIRST_IMAGE
Shift for the image in the Y axis (double)
bool containsLabel(const MDLabel label) const override
int read(const FileName &name, DataMode datamode=DATA, size_t select_img=ALL_IMAGES, bool mapData=false)
Name of an image (std::string)

◆ readMat()

void ProgOpticalAligment::readMat ( const FileName fnIn,
cv::Mat &  M 
)
inline

Definition at line 183 of file movie_optical_alignment_cpu.cpp.

184  {
185  std::ifstream ifp(fnIn.c_str(), std::ios::in | std::ios::binary);
186  int rows, cols;
187  ifp.read(reinterpret_cast<char*>(&rows), sizeof(int));
188  ifp.read(reinterpret_cast<char*>(&cols), sizeof(int));
189  M.create(rows, cols, CV_32FC1);
190  for (int row=0; row<rows; ++row)
191  ifp.read(reinterpret_cast<char*>(&(M.at<float>(row,0))), cols * sizeof(float));
192  ifp.close();
193  }
int in

◆ readParams()

void ProgOpticalAligment::readParams ( )
inlinevirtual

Function in which each program will read parameters that it need. If some error occurs the usage will be printed out.

Reimplemented from XmippProgram.

Definition at line 123 of file movie_optical_alignment_cpu.cpp.

124  {
125  fnMovie = getParam("-i");
126  fnOut = getParam("-o");
127  fnGain = getParam("--gain");
128  fnDark = getParam("--dark");
129  fnMicOut = getParam("--oavg");
130  fnMicInitial = getParam("--oavgInitial");
131  fnMovieOut = getParam("--outMovie");
132  if (checkParam("--oUnc"))
133  {
134  fnMicUncOut = getParam("--oUnc",0);
135  fnMovieUncOut = getParam("--oUnc",1);
136  if (fnMicUncOut!="" && fnMovieUncOut=="")
137  REPORT_ERROR(ERR_ARG_MISSING,"Writing the uncompensated images require both movie and micrograph");
138  }
139  finalGroupSize = getIntParam("--groupSize");
140  nfirst = getIntParam("--frameRange",0);
141  nlast = getIntParam("--frameRange",1);
142  winSize = getIntParam("--winSize");
143  xLTcorner= getIntParam("--cropULCorner",0);
144  yLTcorner= getIntParam("--cropULCorner",1);
145  xDRcorner = getIntParam("--cropDRCorner",0);
146  yDRcorner = getIntParam("--cropDRCorner",1);
147  inMemory = checkParam("--inmemory");
148  doseStep = getDoubleParam("--doseCorrection",0);
149  sampling = getDoubleParam("--doseCorrection",1);
150  accelerationVoltage = getDoubleParam("--doseCorrection",2);
151  dose0 = getDoubleParam("--doseCorrection",3);
152  String aux;
153  aux=getParam("--doseCorrection",4);
154  if (doseStep==0)
156  else
157  {
158  if (aux=="pre")
160  else
162  }
163 #ifdef GPU
164  gpuDevice = getIntParam("--gpu");
165 #endif
166  }
#define PRECOMPENSATION
Argument missing.
Definition: xmipp_error.h:114
double getDoubleParam(const char *param, int arg=0)
#define REPORT_ERROR(nerr, ErrormMsg)
Definition: xmipp_error.h:211
#define NOCOMPENSATION
const char * getParam(const char *param, int arg=0)
std::string String
Definition: xmipp_strings.h:34
#define POSTCOMPENSATION
bool checkParam(const char *param)
int getIntParam(const char *param, int arg=0)

◆ removeFlows()

void ProgOpticalAligment::removeFlows ( int  level)
inline

Definition at line 291 of file movie_optical_alignment_cpu.cpp.

292  {
293  int g=0;
294  FileName fnAuxX=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowx_%d_%d.flow",level,g);
295  FileName fnAuxY=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowy_%d_%d.flow",level,g++);
296  while (fileExists(fnAuxX))
297  {
298  deleteFile(fnAuxX);
299  deleteFile(fnAuxY);
300  fnAuxX=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowx_%d_%d.flow",level,g);
301  fnAuxY=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowy_%d_%d.flow",level,g++);
302  }
303  }
FileName removeLastExtension() const
doublereal * g
void deleteFile(const char *line)
Definition: tools.cpp:280
bool fileExists(const char *filename)
String formatString(const char *format,...)

◆ run()

void ProgOpticalAligment::run ( )
inlinevirtual

This function will be start running the program. it also should be implemented by derived classes.

Reimplemented from XmippProgram.

Definition at line 446 of file movie_optical_alignment_cpu.cpp.

447  {
448  produceSideInfo();
449 
450  Matrix1D<double> meanStdev;
451  Image<float> undeformedGroupAverage, uncompensatedMic;
452 
453 #ifdef GPU
454 #ifndef CV_VERSION_EPOCH // version 3 or newer
455  // Matrices required in GPU part
456  cv::cuda::GpuMat d_currentReference8, d_currentGroupAverage8;
457 #else
458  cv::gpu::GpuMat d_flowx, d_flowy, d_currentReference8, d_currentGroupAverage8;
459 #endif
460 #else
461  cv::Mat flow;
462 #endif // GPU
463 
464  // Matrices required by Opencv
465  cv::Mat cvCurrentReference, cvNewReference, cvCurrentGroupAverage, cvUndeformedGroupAverage, cvCurrentGroupAverage8, cvCurrentReference8;
466  cv::Mat flowxCurrentGroup, flowyCurrentGroup, flowxPreviousGroup, flowyPreviousGroup;
467  cv::Mat flowCurrentGroup[]={flowxCurrentGroup, flowyCurrentGroup};
468  cv::Mat flowPreviousGroup[]={flowxPreviousGroup, flowyPreviousGroup};
469 
470  meanStdev.initZeros(4);
471 #ifdef GPU
472 #ifndef CV_VERSION_EPOCH // version 3 or newer
473  cv::cuda::setDevice(gpuDevice);
474  cv::Ptr<cv::cuda::FarnebackOpticalFlow> d_calc = cv::cuda::FarnebackOpticalFlow::create(
475  6, // numLevels
476  0.5, // pyrScale
477  true, // fastPyramids
478  winSize, // winSize
479  1, // numIters
480  5, // polyN
481  1.1, // polySigma
482  0); // flags
483 #else
484  cv::gpu::setDevice(gpuDevice);
485  // Object for optical flow
486  cv::gpu::FarnebackOpticalFlow d_calc;
487  // Initialize the parameters for optical flow structure
488  d_calc.numLevels=6;
489  d_calc.pyrScale=0.5;
490  d_calc.fastPyramids=true;
491  d_calc.winSize=winSize;
492  d_calc.numIters=1;
493  d_calc.polyN=5;
494  d_calc.polySigma=1.1;
495  d_calc.flags=0;
496 #endif
497 #endif // GPU
498 
499  computeAvg(nfirst, nlast, cvCurrentReference);
500  if (!fnMicInitial.isEmpty())
502 
503  cout << "Frames " << nfirst << " to " << nlast << " under processing ..." << std::endl;
504 
505  int numberOfGroups=2;
506  int levelNum=int(ceil(log(double(numberOfFrames)/finalGroupSize)/log(2.0))), levelCounter=0;
507  MetaDataVec MDout; // To save plot information
508  while (levelCounter<levelNum)
509  {
510  convert2Uint8(cvCurrentReference,cvCurrentReference8);
511  #ifdef GPU
512  d_currentReference8.upload(cvCurrentReference8);
513  #endif
514  int currentGroupSize=int(ceil((float)numberOfFrames/numberOfGroups));
515 
516  bool lastLevel = levelCounter==levelNum-1;
517  // avgStep to hold the sum of aligned frames of each group at each step
518  cvNewReference=cv::Mat::zeros(Ydim, Xdim, CV_32FC1);
519 
520  cout << "Level " << levelCounter << "/" << levelNum-1
521  << " of the pyramid is under processing" << std::endl;
522  cout << " Group size: " << currentGroupSize << ", Number of groups: " << numberOfGroups << std::endl;
523 
524  // Compute time for each level
525  clock_t tStart = clock();
526 
527  for (int currentGroup=0; currentGroup<numberOfGroups; currentGroup++)
528  {
529  int NimgsInAvg=computeAvg(currentGroup*currentGroupSize+nfirst, (currentGroup+1)*currentGroupSize+nfirst-1, cvCurrentGroupAverage);
530  if (NimgsInAvg==0)
531  continue;
532  convert2Uint8(cvCurrentGroupAverage,cvCurrentGroupAverage8);
533 
534  if (numberOfGroups>2)
535  {
536  FileName flowXFileName=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowx_%d_%d.flow",levelCounter-1,currentGroup/2);
537  readMat(flowXFileName.c_str(), flowCurrentGroup[0]);
538 // std::cout << "Reading flow " << flowXFileName << std::endl;
539 
540  FileName flowYFileName=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowy_%d_%d.flow",levelCounter-1,currentGroup/2); // ***
541  readMat(flowYFileName.c_str(), flowCurrentGroup[1]);
542  }
543 
544 #ifdef GPU
545  d_currentGroupAverage8.upload(cvCurrentGroupAverage8);
546 #ifndef CV_VERSION_EPOCH // version 3 or newer
547  cv::cuda::GpuMat d_flow(cvCurrentGroupAverage8.size(), CV_32FC2);
548  cv::cuda::GpuMat planes[2];
549  if (numberOfGroups>2)
550  {
551  cv::cuda::split(d_flow, planes);
552  planes[0].upload(flowCurrentGroup[0]);
553  planes[1].upload(flowCurrentGroup[1]);
554  d_calc->setFlags(cv::OPTFLOW_USE_INITIAL_FLOW);
555  }
556  d_calc->calc(d_currentReference8, d_currentGroupAverage8, d_flow);
557 
558  cv::cuda::split(d_flow, planes);
559  planes[0].download(flowCurrentGroup[0]);
560  planes[1].download(flowCurrentGroup[1]);
561 #else
562  if (numberOfGroups>2)
563  {
564  d_flowx.upload(flowCurrentGroup[0]);
565  d_flowy.upload(flowCurrentGroup[1]);
566  d_calc.flags=cv::OPTFLOW_USE_INITIAL_FLOW;
567  }
568  d_calc(d_currentReference8, d_currentGroupAverage8, d_flowx, d_flowy);
569  d_flowx.download(flowCurrentGroup[0]);
570  d_flowy.download(flowCurrentGroup[1]);
571  d_currentGroupAverage8.release();
572  d_flowx.release();
573  d_flowy.release();
574 #endif
575 #else // CPU version
576  int ofFlags=0;
577  // Check if we should use the flows from the previous steps
578  if (numberOfGroups==2)
579  {
580  flowxCurrentGroup=cv::Mat::zeros(Ydim, Xdim, CV_32FC1);
581  flowyCurrentGroup=cv::Mat::zeros(Ydim, Xdim, CV_32FC1);
582  flow=cv::Mat::zeros(Ydim, Xdim, CV_32FC1);
583  }
584  else
585  ofFlags=cv::OPTFLOW_USE_INITIAL_FLOW;
586 
587  merge(flowCurrentGroup,2,flow);
588 
589  calcOpticalFlowFarneback(cvCurrentReference8, cvCurrentGroupAverage8, flow, 0.5, 6, winSize, 1, 5, 1.1, ofFlags);
590  split(flow, flowCurrentGroup);
591 #endif
592 
593  // Save the flows if we are in the last step
594  if (lastLevel)
595  {
596  if (currentGroup > 0)
597  {
598  evaluateDisplacements(flowCurrentGroup,flowPreviousGroup,meanStdev);
599  size_t id=MDout.addObject();
600  MDout.setValue(MDL_OPTICALFLOW_MEANX, double(meanStdev(0)), id);
601  MDout.setValue(MDL_OPTICALFLOW_MEANY, double(meanStdev(2)), id);
602  MDout.setValue(MDL_OPTICALFLOW_STDX, double(meanStdev(1)), id);
603  MDout.setValue(MDL_OPTICALFLOW_STDY, double(meanStdev(3)), id);
604  }
605  flowCurrentGroup[0].copyTo(flowPreviousGroup[0]);
606  flowCurrentGroup[1].copyTo(flowPreviousGroup[1]);
607  }
608  else
609  {
610  FileName flowXFileName=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowx_%d_%d.flow",levelCounter,currentGroup);
611  FileName flowYFileName=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowy_%d_%d.flow",levelCounter,currentGroup);
612  saveMat(flowXFileName.c_str(), flowCurrentGroup[0]);
613  saveMat(flowYFileName.c_str(), flowCurrentGroup[1]);
614 // flowXFileName=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowx_%d_%d.mrc",levelCounter,currentGroup);
615 // flowYFileName=fnmovieRoot+fnBaseOut.removeLastExtension()+formatString("flowy_%d_%d.mrc",levelCounter,currentGroup);
616 // std::cout << "Saving flows " << flowXFileName << " " << flowYFileName << std::endl;
617 // Image<float> save;
618 // opencv2Xmipp(flowCurrentGroup[0],save());
619 // save.write(flowXFileName);
620 // opencv2Xmipp(flowCurrentGroup[1],save());
621 // save.write(flowYFileName);
622  }
623 
624  // Update cvNewReference
625  for (float row = 0; row < flowCurrentGroup[0].rows; row++ )
626  for (float col = 0; col < flowCurrentGroup[0].cols; col++ )
627  {
628  flowCurrentGroup[0].at<float>(row,col) += col;
629  flowCurrentGroup[1].at<float>(row,col) += row;
630  }
631  cv::remap(cvCurrentGroupAverage, cvUndeformedGroupAverage, flowCurrentGroup[0], flowCurrentGroup[1], cv::INTER_CUBIC);
632 // Image<float> save;
633 // opencv2Xmipp(cvUndeformedGroupAverage,save());
634 // std::cout << "cvUndeformedGroupAverage stats "; save().printStats(); std::cout << std::endl;
635 // opencv2Xmipp(flowCurrentGroup[0],save());
636 // std::cout << "flowCurrentGroup[0] stats "; save().printStats(); std::cout << std::endl;
637 // opencv2Xmipp(flowCurrentGroup[1],save());
638 // std::cout << "flowCurrentGroup[1] stats "; save().printStats(); std::cout << std::endl;
639  if (lastLevel)
640  {
642  {
646  opencv2Xmipp(cvUndeformedGroupAverage,If);
647  typeCast(If,Id);
648  transformer.FourierTransform(Id, fId, false);
650  dose0+currentGroup*doseStep, dose0+(currentGroup+1)*doseStep);
652  typeCast(Id,If);
653  xmipp2Opencv(If,cvUndeformedGroupAverage);
654  }
655  if (!fnMovieOut.isEmpty())
656  {
657  opencv2Xmipp(cvUndeformedGroupAverage,undeformedGroupAverage());
658  // std::cout << "Writing frame " << fnMovieOut << " " << currentGroup+1 << std::endl;
659  undeformedGroupAverage.write(fnMovieOut, currentGroup+1, true, WRITE_REPLACE);
660  }
661  if (!fnMovieUncOut.isEmpty())
662  {
663  Image<float> frame;
664  cv::Mat cvFrame, cvUndeformedFrame;
665  frame.read(formatString("%d@%s",currentGroup+1,fnMovieUncOut.c_str()));
666  xmipp2Opencv(frame(), cvFrame);
667  cv::remap(cvFrame, cvUndeformedFrame, flowCurrentGroup[0], flowCurrentGroup[1], cv::INTER_CUBIC);
668  opencv2Xmipp(cvUndeformedFrame,frame());
669  frame.write(fnMovieUncOut, currentGroup+1, true, WRITE_REPLACE);
670 
671  if (currentGroup==0)
672  uncompensatedMic()=frame();
673  else
674  uncompensatedMic()+=frame();
675  }
676  }
677  cvNewReference+=cvUndeformedGroupAverage;
678  }
679 #ifdef GPU
680  d_currentReference8.release();
681 #endif
682  cvCurrentReference=cvNewReference;
683  cvCurrentReference*=1.0/numberOfGroups;
684 // Image<float> save;
685 // opencv2Xmipp(cvCurrentReference,save());
686 // std::cout << "cvCurrentReference stats "; save().printStats(); std::cout << std::endl;
687  printf("Processing time: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
688  numberOfGroups=std::min(2*numberOfGroups,numberOfFrames);
689  levelCounter++;
690  if (levelCounter>1)
691  removeFlows(levelCounter-2);
692  }
693  MDout.write(fnOut, MD_APPEND);
694  removeFlows(levelNum-1);
695  removeFlows(levelNum);
696 
697  if (!fnMicOut.isEmpty())
698  {
699  opencv2Xmipp(cvCurrentReference, tempAvg());
701  }
702 
703  if (!fnMicUncOut.isEmpty())
704  {
705  uncompensatedMic.write(fnMicUncOut);
706 // std::cout << "Writing " << fnMicUncOut << std::endl;
707  }
708 
709  if (!inMemory)
711  }
#define YSIZE(v)
void min(Image< double > &op1, const Image< double > &op2)
void applyDoseFilterToImage(int Ydim, int Xdim, const MultidimArray< std::complex< double > > &FFT1, const double dose_start, const double dose_finish)
Apply a dose filter to the image Fourier transform.
FileName removeLastExtension() const
void inverseFourierTransform()
Definition: xmipp_fftw.cpp:329
void write(const FileName &name="", size_t select_img=ALL_IMAGES, bool isStack=false, int mode=WRITE_OVERWRITE, CastWriteMode castMode=CW_CAST, int _swapWrite=0)
void convert2Uint8(cv::Mat opencvDoubleMat, cv::Mat &opencvUintMat)
void write(const FileName &outFile, WriteModeMetaData mode=MD_OVERWRITE) const
ProgMovieFilterDose * filterDose
void evaluateDisplacements(const cv::Mat *flowCurrentGroup, const cv::Mat *flowPreviousGroup, Matrix1D< double > &meanStdDev)
void deleteFile(const char *line)
Definition: tools.cpp:280
Mean of the movement in y direction of the motion map> (double)
void log(Image< double > &op)
Standard deviation of the movement in y direction of the motion map> (double)
bool setValue(const MDObject &mdValueIn, size_t id)
size_t addObject() override
void saveMat(const FileName &fnOut, const cv::Mat &M)
void readMat(const FileName &fnIn, cv::Mat &M)
#define XSIZE(v)
void initZeros()
Definition: matrix1d.h:592
void FourierTransform(T &v, T1 &V, bool getCopy=true)
Definition: xmipp_fftw.h:166
Standatd deviation of the movement in x direction of the motion map> (double)
void opencv2Xmipp(const cv::Mat &opencvMat, MultidimArray< float > &xmippArray)
bool isEmpty() const
void typeCast(const Matrix1D< T1 > &v1, Matrix1D< T2 > &v2)
Definition: matrix1d.h:1227
Mean of the movement in x direction of the motion map> (double)
void xmipp2Opencv(const MultidimArray< float > &xmippArray, cv::Mat &opencvMat)
#define POSTCOMPENSATION
String formatString(const char *format,...)
int read(const FileName &name, DataMode datamode=DATA, size_t select_img=ALL_IMAGES, bool mapData=false, int mode=WRITE_READONLY)
int computeAvg(size_t begin, size_t end, cv::Mat &cvAvgImg)

◆ saveMat()

void ProgOpticalAligment::saveMat ( const FileName fnOut,
const cv::Mat &  M 
)
inline

Definition at line 169 of file movie_optical_alignment_cpu.cpp.

170  {
171  std::ofstream ofp(fnOut.c_str(), std::ios::out | std::ios::binary);
172  ofp.write(reinterpret_cast<const char*>(&M.rows), sizeof(int));
173  ofp.write(reinterpret_cast<const char*>(&M.cols), sizeof(int));
174 // ofp << M.rows;
175 // ofp << M.cols;
176  for (int row=0; row<M.rows; ++row) {
177  ofp.write(reinterpret_cast<const char*>(&M.at<float>(row,0)), M.cols * sizeof(float));
178  }
179  ofp.close();
180  }

◆ xmipp2Opencv()

void ProgOpticalAligment::xmipp2Opencv ( const MultidimArray< float > &  xmippArray,
cv::Mat &  opencvMat 
)
inline

Definition at line 196 of file movie_optical_alignment_cpu.cpp.

197  {
198  int h = YSIZE(xmippArray);
199  int w = XSIZE(xmippArray);
200  opencvMat = cv::Mat::zeros(h, w,CV_32FC1);
201  for (int row=0; row<h; ++row)
202  memcpy(&opencvMat.at<float>(row,0),&DIRECT_A2D_ELEM(xmippArray,row,0),XSIZE(xmippArray)*sizeof(float));
203  }
#define YSIZE(v)
#define DIRECT_A2D_ELEM(v, i, j)
doublereal * w
#define XSIZE(v)

Member Data Documentation

◆ accelerationVoltage

double ProgOpticalAligment::accelerationVoltage

Definition at line 72 of file movie_optical_alignment_cpu.cpp.

◆ compensationMode

int ProgOpticalAligment::compensationMode

Definition at line 73 of file movie_optical_alignment_cpu.cpp.

◆ dose0

double ProgOpticalAligment::dose0

Definition at line 72 of file movie_optical_alignment_cpu.cpp.

◆ doseStep

double ProgOpticalAligment::doseStep

Definition at line 72 of file movie_optical_alignment_cpu.cpp.

◆ filterDose

ProgMovieFilterDose* ProgOpticalAligment::filterDose

Definition at line 93 of file movie_optical_alignment_cpu.cpp.

◆ finalGroupSize

int ProgOpticalAligment::finalGroupSize

Definition at line 70 of file movie_optical_alignment_cpu.cpp.

◆ fnBaseOut

FileName ProgOpticalAligment::fnBaseOut

Definition at line 88 of file movie_optical_alignment_cpu.cpp.

◆ fnDark

FileName ProgOpticalAligment::fnDark

Definition at line 65 of file movie_optical_alignment_cpu.cpp.

◆ fnGain

FileName ProgOpticalAligment::fnGain

Definition at line 65 of file movie_optical_alignment_cpu.cpp.

◆ fnMicInitial

FileName ProgOpticalAligment::fnMicInitial

Definition at line 67 of file movie_optical_alignment_cpu.cpp.

◆ fnMicOut

FileName ProgOpticalAligment::fnMicOut

Definition at line 66 of file movie_optical_alignment_cpu.cpp.

◆ fnMicUncOut

FileName ProgOpticalAligment::fnMicUncOut

Definition at line 66 of file movie_optical_alignment_cpu.cpp.

◆ fnMovie

FileName ProgOpticalAligment::fnMovie

Definition at line 65 of file movie_optical_alignment_cpu.cpp.

◆ fnMovieOut

FileName ProgOpticalAligment::fnMovieOut

Definition at line 66 of file movie_optical_alignment_cpu.cpp.

◆ fnmovieRoot

FileName ProgOpticalAligment::fnmovieRoot

Definition at line 88 of file movie_optical_alignment_cpu.cpp.

◆ fnMovieUncOut

FileName ProgOpticalAligment::fnMovieUncOut

Definition at line 66 of file movie_optical_alignment_cpu.cpp.

◆ fnOut

FileName ProgOpticalAligment::fnOut

Definition at line 65 of file movie_optical_alignment_cpu.cpp.

◆ fnTempStack

FileName ProgOpticalAligment::fnTempStack

Definition at line 88 of file movie_optical_alignment_cpu.cpp.

◆ globalShiftCorr

bool ProgOpticalAligment::globalShiftCorr

Definition at line 71 of file movie_optical_alignment_cpu.cpp.

◆ gpuDevice

int ProgOpticalAligment::gpuDevice

Definition at line 69 of file movie_optical_alignment_cpu.cpp.

◆ inMemory

bool ProgOpticalAligment::inMemory

Definition at line 71 of file movie_optical_alignment_cpu.cpp.

◆ movie

MetaDataVec ProgOpticalAligment::movie

Definition at line 68 of file movie_optical_alignment_cpu.cpp.

◆ Ndim

size_t ProgOpticalAligment::Ndim

Definition at line 89 of file movie_optical_alignment_cpu.cpp.

◆ nfirst

int ProgOpticalAligment::nfirst

Definition at line 69 of file movie_optical_alignment_cpu.cpp.

◆ nlast

int ProgOpticalAligment::nlast

Definition at line 69 of file movie_optical_alignment_cpu.cpp.

◆ numberOfFrames

int ProgOpticalAligment::numberOfFrames

Definition at line 69 of file movie_optical_alignment_cpu.cpp.

◆ sampling

double ProgOpticalAligment::sampling

Definition at line 72 of file movie_optical_alignment_cpu.cpp.

◆ tempAvg

Image<float> ProgOpticalAligment::tempAvg

Definition at line 91 of file movie_optical_alignment_cpu.cpp.

◆ tempStack

MultidimArray<float> ProgOpticalAligment::tempStack

Definition at line 90 of file movie_optical_alignment_cpu.cpp.

◆ transformer

FourierTransformer ProgOpticalAligment::transformer

Definition at line 92 of file movie_optical_alignment_cpu.cpp.

◆ winSize

int ProgOpticalAligment::winSize

Definition at line 69 of file movie_optical_alignment_cpu.cpp.

◆ Xdim

size_t ProgOpticalAligment::Xdim

Definition at line 89 of file movie_optical_alignment_cpu.cpp.

◆ xDRcorner

int ProgOpticalAligment::xDRcorner

x right down corner

Definition at line 83 of file movie_optical_alignment_cpu.cpp.

◆ xLTcorner

int ProgOpticalAligment::xLTcorner

crop corner x left top corner

Definition at line 79 of file movie_optical_alignment_cpu.cpp.

◆ Ydim

size_t ProgOpticalAligment::Ydim

Definition at line 89 of file movie_optical_alignment_cpu.cpp.

◆ yDRcorner

int ProgOpticalAligment::yDRcorner

y right down corner

Definition at line 85 of file movie_optical_alignment_cpu.cpp.

◆ yLTcorner

int ProgOpticalAligment::yLTcorner

y left top corner

Definition at line 81 of file movie_optical_alignment_cpu.cpp.

◆ Zdim

size_t ProgOpticalAligment::Zdim

Definition at line 89 of file movie_optical_alignment_cpu.cpp.


The documentation for this class was generated from the following file: