lsst.afw  14.0-40-g0271be365
warpExposure.cc
Go to the documentation of this file.
1 // -*- LSST-C++ -*- // fixed format comment for emacs
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008, 2009, 2010 LSST Corporation.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program 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 General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 /*
25  * Support for warping an %image to a new Wcs.
26  */
27 
28 #include <cassert>
29 #include <cmath>
30 #include <cstdint>
31 #include <limits>
32 #include <memory>
33 #include <sstream>
34 #include <string>
35 #include <vector>
36 #include <utility>
37 #include <ctime>
38 
39 #include <memory>
40 #include "boost/pointer_cast.hpp"
41 #include "boost/regex.hpp"
42 #include "astshim.h"
43 
44 #include "lsst/log/Log.h"
45 #include "lsst/pex/exceptions.h"
47 #include "lsst/afw/geom.h"
48 #include "lsst/afw/math/Kernel.h"
49 #include "lsst/afw/coord/Coord.h"
50 #include "lsst/afw/image/Calib.h"
51 #include "lsst/afw/image/Wcs.h"
54 
56 
57 using std::swap;
58 
59 namespace lsst {
60 namespace afw {
61 namespace math {
62 
63 //
64 // A helper function for the warping kernels which provides error-checking:
65 // the warping kernels are designed to work in two cases
66 // 0 < x < 1 and ctrX=(size-1)/2
67 // -1 < x < 0 and ctrX=(size+1)/2
68 // (and analogously for y). Note that to get the second case, Kernel::setCtrX(1) must be
69 // called before calling Kernel::setKernelParameter(). [see afw::math::offsetImage() for
70 // an example]
71 //
72 // FIXME eventually the 3 warping kernels will inherit from a common base class WarpingKernel
73 // and this routine can be eliminated by putting the code in WarpingKernel::setKernelParameter()
74 //
75 static inline void checkWarpingKernelParameter(const SeparableKernel *p, unsigned int ind, double value) {
76  if (ind > 1) {
78  "bad ind argument in WarpingKernel::setKernelParameter()");
79  }
80  int ctr = p->getCtr()[ind];
81  int size = p->getDimensions()[ind];
82 
83  if (ctr == (size - 1) / 2) {
84  if (value < -1e-6 || value > 1 + 1e-6) {
86  "bad coordinate in WarpingKernel::setKernelParameter()");
87  }
88  } else if (ctr == (size + 1) / 2) {
89  if (value < -1 - 1e-6 || value > 1e-6) {
91  "bad coordinate in WarpingKernel::setKernelParameter()");
92  }
93  } else {
95  "bad ctr value in WarpingKernel::setKernelParameter()");
96  }
97 }
98 
101 }
102 
103 int LanczosWarpingKernel::getOrder() const { return this->getWidth() / 2; }
104 
105 void LanczosWarpingKernel::setKernelParameter(unsigned int ind, double value) const {
106  checkWarpingKernelParameter(this, ind, value);
108 }
109 
112 }
113 
115  //
116  // this->_params[0] = value of x where we want to interpolate the function
117  // x = integer value of x where we evaluate the function in the interpolation
118  //
119  // The following weird-looking expression has no if/else statements, is roundoff-tolerant,
120  // and works in the following two cases:
121  // 0 < this->_params[0] < 1, x \in {0,1}
122  // -1 < this->_params[0] < 0, x \in {-1,0}
123  //
124  // The checks in BilinearWarpingKernel::setKernelParameter() ensure that one of these
125  // conditions is satisfied
126  //
127  return 0.5 + (1.0 - (2.0 * fabs(this->_params[0]))) * (0.5 - fabs(x));
128 }
129 
130 void BilinearWarpingKernel::setKernelParameter(unsigned int ind, double value) const {
131  checkWarpingKernelParameter(this, ind, value);
133 }
134 
137  os << "_BilinearFunction1: ";
138  os << Function1<Kernel::Pixel>::toString(prefix);
139  return os.str();
140 }
141 
143  return std::make_shared<NearestWarpingKernel>();
144 }
145 
147  // this expression is faster than using conditionals, but offers no sanity checking
148  return static_cast<double>((fabs(this->_params[0]) < 0.5) == (fabs(x) < 0.5));
149 }
150 
151 void NearestWarpingKernel::setKernelParameter(unsigned int ind, double value) const {
152  checkWarpingKernelParameter(this, ind, value);
154 }
155 
158  os << "_NearestFunction1: ";
159  os << Function1<Kernel::Pixel>::toString(prefix);
160  return os.str();
161 }
162 
164  typedef std::shared_ptr<SeparableKernel> KernelPtr;
165  boost::cmatch matches;
166  static const boost::regex LanczosRE("lanczos(\\d+)");
167  if (name == "bilinear") {
168  return KernelPtr(new BilinearWarpingKernel());
169  } else if (boost::regex_match(name.c_str(), matches, LanczosRE)) {
170  std::string orderStr(matches[1].first, matches[1].second);
171  int order;
172  std::istringstream(orderStr) >> order;
173  return KernelPtr(new LanczosWarpingKernel(order));
174  } else if (name == "nearest") {
175  return KernelPtr(new NearestWarpingKernel());
176  } else {
177  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "unknown warping kernel name: \"" + name + "\"");
178  }
179 }
180 
182  if (_warpingKernelPtr->getCacheSize() != _cacheSize) {
183  _warpingKernelPtr->computeCache(_cacheSize);
184  }
185  return _warpingKernelPtr;
186 };
187 
188 void WarpingControl::setWarpingKernelName(std::string const &warpingKernelName) {
189  std::shared_ptr<SeparableKernel> warpingKernelPtr(makeWarpingKernel(warpingKernelName));
190  setWarpingKernel(*warpingKernelPtr);
191 }
192 
194  if (_maskWarpingKernelPtr) {
195  _testWarpingKernels(warpingKernel, *_maskWarpingKernelPtr);
196  }
197  std::shared_ptr<SeparableKernel> warpingKernelPtr(
198  std::static_pointer_cast<SeparableKernel>(warpingKernel.clone()));
199  _warpingKernelPtr = warpingKernelPtr;
200 }
201 
203  if (_maskWarpingKernelPtr) { // lazily update kernel cache
204  if (_maskWarpingKernelPtr->getCacheSize() != _cacheSize) {
205  _maskWarpingKernelPtr->computeCache(_cacheSize);
206  }
207  }
208  return _maskWarpingKernelPtr;
209 }
210 
211 void WarpingControl::setMaskWarpingKernelName(std::string const &maskWarpingKernelName) {
212  if (!maskWarpingKernelName.empty()) {
213  std::shared_ptr<SeparableKernel> maskWarpingKernelPtr(makeWarpingKernel(maskWarpingKernelName));
214  setMaskWarpingKernel(*maskWarpingKernelPtr);
215  } else {
216  _maskWarpingKernelPtr.reset();
217  }
218 }
219 
221  _testWarpingKernels(*_warpingKernelPtr, maskWarpingKernel);
222  _maskWarpingKernelPtr = std::static_pointer_cast<SeparableKernel>(maskWarpingKernel.clone());
223 }
224 
225 void WarpingControl::_testWarpingKernels(SeparableKernel const &warpingKernel,
226  SeparableKernel const &maskWarpingKernel) const {
227  geom::Box2I kernelBBox = geom::Box2I(geom::Point2I(0, 0) - geom::Extent2I(warpingKernel.getCtr()),
228  warpingKernel.getDimensions());
229  geom::Box2I maskKernelBBox = geom::Box2I(geom::Point2I(0, 0) - geom::Extent2I(maskWarpingKernel.getCtr()),
230  maskWarpingKernel.getDimensions());
231  if (!kernelBBox.contains(maskKernelBBox)) {
233  "warping kernel is smaller than mask warping kernel");
234  }
235 }
236 
237 template <typename DestExposureT, typename SrcExposureT>
238 int warpExposure(DestExposureT &destExposure, SrcExposureT const &srcExposure, WarpingControl const &control,
239  typename DestExposureT::MaskedImageT::SinglePixel padValue) {
240  if (!destExposure.hasWcs()) {
241  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "destExposure has no Wcs");
242  }
243  if (!srcExposure.hasWcs()) {
244  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "srcExposure has no Wcs");
245  }
246  typename DestExposureT::MaskedImageT mi = destExposure.getMaskedImage();
247  std::shared_ptr<image::Calib> calibCopy(new image::Calib(*srcExposure.getCalib()));
248  destExposure.setCalib(calibCopy);
249  destExposure.setFilter(srcExposure.getFilter());
250  destExposure.getInfo()->setVisitInfo(srcExposure.getInfo()->getVisitInfo());
251  return warpImage(mi, *destExposure.getWcs(), srcExposure.getMaskedImage(), *srcExposure.getWcs(), control,
252  padValue);
253 }
254 
255 namespace {
256 
257 inline geom::Point2D computeSrcPos(int destCol,
258  int destRow,
259  geom::Point2D const &destXY0,
260  image::Wcs const &destWcs,
261  image::Wcs const &srcWcs)
262 {
263  double const col = image::indexToPosition(destCol + destXY0[0]);
264  double const row = image::indexToPosition(destRow + destXY0[1]);
265  geom::Angle sky1, sky2;
266  destWcs.pixelToSky(col, row, sky1, sky2);
267  return srcWcs.skyToPixel(sky1, sky2);
268 }
269 
270 inline double computeRelativeArea(
271  geom::Point2D const &srcPos,
272  geom::Point2D const &leftSrcPos,
273  geom::Point2D const &upSrcPos)
274 {
275  geom::Extent2D dSrcA = srcPos - leftSrcPos;
276  geom::Extent2D dSrcB = srcPos - upSrcPos;
277 
278  return std::abs(dSrcA.getX() * dSrcB.getY() - dSrcA.getY() * dSrcB.getX());
279 }
280 
290 template <typename DestImageT, typename SrcImageT>
291 int doWarpImage(DestImageT &destImage, SrcImageT const &srcImage,
292  detail::PositionFunctor const &computeSrcPos, WarpingControl const &control,
293  typename DestImageT::SinglePixel padValue) {
294  if (details::isSameObject(destImage, srcImage)) {
295  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "destImage is srcImage; cannot warp in place");
296  }
297  if (destImage.getBBox(image::LOCAL).isEmpty()) {
298  return 0;
299  }
300  // if src image is too small then don't try to warp
301  try {
302  std::shared_ptr<SeparableKernel> warpingKernelPtr = control.getWarpingKernel();
303  warpingKernelPtr->shrinkBBox(srcImage.getBBox(image::LOCAL));
304  } catch (...) {
305  for (int y = 0, height = destImage.getHeight(); y < height; ++y) {
306  for (typename DestImageT::x_iterator destPtr = destImage.row_begin(y), end = destImage.row_end(y);
307  destPtr != end; ++destPtr) {
308  *destPtr = padValue;
309  }
310  }
311  return 0;
312  }
313  std::shared_ptr<SeparableKernel> warpingKernelPtr = control.getWarpingKernel();
314  int interpLength = control.getInterpLength();
315 
316  std::shared_ptr<LanczosWarpingKernel const> const lanczosKernelPtr =
318 
319  int numGoodPixels = 0;
320 
321  // Get the source MaskedImage and a pixel accessor to it.
322  int const srcWidth = srcImage.getWidth();
323  int const srcHeight = srcImage.getHeight();
324  LOGL_DEBUG("TRACE2.afw.math.warp", "source image width=%d; height=%d", srcWidth, srcHeight);
325 
326  int const destWidth = destImage.getWidth();
327  int const destHeight = destImage.getHeight();
328 
329  LOGL_DEBUG("TRACE2.afw.math.warp", "remap image width=%d; height=%d", destWidth, destHeight);
330 
331  // Set each pixel of destExposure's MaskedImage
332  LOGL_DEBUG("TRACE3.afw.math.warp", "Remapping masked image");
333 
334  // A cache of pixel positions on the source corresponding to the previous or current row
335  // of the destination image.
336  // The first value is for column -1 because the previous source position is used to compute relative area
337  // To simplify the indexing, use an iterator that starts at begin+1, thus:
338  // srcPosView = _srcPosList.begin() + 1
339  // srcPosView[col-1] and lower indices are for this row
340  // srcPosView[col] and higher indices are for the previous row
341  std::vector<geom::Point2D> _srcPosList(1 + destWidth);
342  std::vector<geom::Point2D>::iterator const srcPosView = _srcPosList.begin() + 1;
343 
344  int const maxCol = destWidth - 1;
345  int const maxRow = destHeight - 1;
346 
347  detail::WarpAtOnePoint<DestImageT, SrcImageT> warpAtOnePoint(srcImage, control, padValue);
348 
349  if (interpLength > 0) {
350  // Use interpolation. Note that 1 produces the same result as no interpolation
351  // but uses this code branch, thus providing an easy way to compare the two branches.
352 
353  // Estimate for number of horizontal interpolation band edges, to reserve memory in vectors
354  int const numColEdges = 2 + ((destWidth - 1) / interpLength);
355 
356  // A list of edge column indices for interpolation bands;
357  // starts at -1, increments by interpLen (except the final interval), and ends at destWidth-1
358  std::vector<int> edgeColList;
359  edgeColList.reserve(numColEdges);
360 
361  // A list of 1/column width for horizontal interpolation bands; the first value is garbage.
362  // The inverse is used for speed because the values is always multiplied.
363  std::vector<double> invWidthList;
364  invWidthList.reserve(numColEdges);
365 
366  // Compute edgeColList and invWidthList
367  edgeColList.push_back(-1);
368  invWidthList.push_back(0.0);
369  for (int prevEndCol = -1; prevEndCol < maxCol; prevEndCol += interpLength) {
370  int endCol = prevEndCol + interpLength;
371  if (endCol > maxCol) {
372  endCol = maxCol;
373  }
374  edgeColList.push_back(endCol);
375  assert(endCol - prevEndCol > 0);
376  invWidthList.push_back(1.0 / static_cast<double>(endCol - prevEndCol));
377  }
378  assert(edgeColList.back() == maxCol);
379 
380  // A list of delta source positions along the edge columns of the horizontal interpolation bands
381  std::vector<geom::Extent2D> yDeltaSrcPosList(edgeColList.size());
382 
383  // Initialize _srcPosList for row -1
384  // srcPosView[-1] = computeSrcPos(-1, -1, destXY0, destWcs, srcWcs);
385  srcPosView[-1] = computeSrcPos(-1, -1);
386  for (int colBand = 1, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
387  int const prevEndCol = edgeColList[colBand - 1];
388  int const endCol = edgeColList[colBand];
389  geom::Point2D leftSrcPos = srcPosView[prevEndCol];
390  geom::Point2D rightSrcPos = computeSrcPos(endCol, -1);
391  geom::Extent2D xDeltaSrcPos = (rightSrcPos - leftSrcPos) * invWidthList[colBand];
392 
393  for (int col = prevEndCol + 1; col <= endCol; ++col) {
394  srcPosView[col] = srcPosView[col - 1] + xDeltaSrcPos;
395  }
396  }
397 
398  int endRow = -1;
399  while (endRow < maxRow) {
400  // Next horizontal interpolation band
401 
402  int prevEndRow = endRow;
403  endRow = prevEndRow + interpLength;
404  if (endRow > maxRow) {
405  endRow = maxRow;
406  }
407  assert(endRow - prevEndRow > 0);
408  double interpInvHeight = 1.0 / static_cast<double>(endRow - prevEndRow);
409 
410  // Set yDeltaSrcPosList for this horizontal interpolation band
411  for (int colBand = 0, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
412  int endCol = edgeColList[colBand];
413  geom::Point2D bottomSrcPos = computeSrcPos(endCol, endRow);
414  yDeltaSrcPosList[colBand] = (bottomSrcPos - srcPosView[endCol]) * interpInvHeight;
415  }
416 
417  for (int row = prevEndRow + 1; row <= endRow; ++row) {
418  typename DestImageT::x_iterator destXIter = destImage.row_begin(row);
419  srcPosView[-1] += yDeltaSrcPosList[0];
420  for (int colBand = 1, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
421  // Next vertical interpolation band
422 
423  int const prevEndCol = edgeColList[colBand - 1];
424  int const endCol = edgeColList[colBand];
425 
426  // Compute xDeltaSrcPos; remember that srcPosView contains
427  // positions for this row in prevEndCol and smaller indices,
428  // and positions for the previous row for larger indices (including endCol)
429  geom::Point2D leftSrcPos = srcPosView[prevEndCol];
430  geom::Point2D rightSrcPos = srcPosView[endCol] + yDeltaSrcPosList[colBand];
431  geom::Extent2D xDeltaSrcPos = (rightSrcPos - leftSrcPos) * invWidthList[colBand];
432 
433  for (int col = prevEndCol + 1; col <= endCol; ++col, ++destXIter) {
434  geom::Point2D leftSrcPos = srcPosView[col - 1];
435  geom::Point2D srcPos = leftSrcPos + xDeltaSrcPos;
436  double relativeArea = computeRelativeArea(srcPos, leftSrcPos, srcPosView[col]);
437 
438  srcPosView[col] = srcPos;
439 
440  if (warpAtOnePoint(
441  destXIter, srcPos, relativeArea,
443  ++numGoodPixels;
444  }
445  } // for col
446  } // for col band
447  } // for row
448  } // while next row band
449 
450  } else {
451  // No interpolation
452 
453  // initialize _srcPosList for row -1;
454  // the first value is not needed, but it's safer to compute it
455  std::vector<geom::Point2D>::iterator srcPosView = _srcPosList.begin() + 1;
456  for (int col = -1; col < destWidth; ++col) {
457  srcPosView[col] = computeSrcPos(col, -1);
458  }
459 
460  for (int row = 0; row < destHeight; ++row) {
461  typename DestImageT::x_iterator destXIter = destImage.row_begin(row);
462 
463  srcPosView[-1] = computeSrcPos(-1, row);
464 
465  for (int col = 0; col < destWidth; ++col, ++destXIter) {
466  geom::Point2D srcPos = computeSrcPos(col, row);
467  double relativeArea = computeRelativeArea(srcPos, srcPosView[col - 1], srcPosView[col]);
468  srcPosView[col] = srcPos;
469 
470  if (warpAtOnePoint(destXIter, srcPos, relativeArea,
472  ++numGoodPixels;
473  }
474  } // for col
475  } // for row
476  } // if interp
477 
478  return numGoodPixels;
479 }
480 
481 } // namespace
482 
483 template <typename DestImageT, typename SrcImageT>
484 int warpImage(DestImageT &destImage, image::Wcs const &destWcs, SrcImageT const &srcImage,
485  image::Wcs const &srcWcs, WarpingControl const &control,
486  typename DestImageT::SinglePixel padValue) {
487  geom::Point2D const destXY0(destImage.getXY0());
489  detail::XYTransformPositionFunctor const computeSrcPos{destXY0, xyTransform};
490  return doWarpImage(destImage, srcImage, computeSrcPos, control, padValue);
491 }
492 
493 template <typename DestImageT, typename SrcImageT>
494 int warpImage(DestImageT &destImage, SrcImageT const &srcImage, geom::XYTransform const &xyTransform,
495  WarpingControl const &control, typename DestImageT::SinglePixel padValue) {
496  geom::Point2D const destXY0(destImage.getXY0());
497  detail::XYTransformPositionFunctor const computeSrcPos(destXY0, xyTransform);
498  return doWarpImage(destImage, srcImage, computeSrcPos, control, padValue);
499 }
500 
501 template <typename DestImageT, typename SrcImageT>
502 int warpImage(DestImageT &destImage, SrcImageT const &srcImage,
504  WarpingControl const &control, typename DestImageT::SinglePixel padValue) {
505  if (details::isSameObject(destImage, srcImage)) {
506  throw LSST_EXCEPT(pexExcept::InvalidParameterError, "destImage is srcImage; cannot warp in place");
507  }
508  if (destImage.getBBox(image::LOCAL).isEmpty()) {
509  return 0;
510  }
511  // if src image is too small then don't try to warp
512  std::shared_ptr<SeparableKernel> warpingKernelPtr = control.getWarpingKernel();
513  try {
514  warpingKernelPtr->shrinkBBox(srcImage.getBBox(image::LOCAL));
516  for (int y = 0, height = destImage.getHeight(); y < height; ++y) {
517  for (typename DestImageT::x_iterator destPtr = destImage.row_begin(y), end = destImage.row_end(y);
518  destPtr != end; ++destPtr) {
519  *destPtr = padValue;
520  }
521  }
522  return 0;
523  }
524  int interpLength = control.getInterpLength();
525 
526  std::shared_ptr<LanczosWarpingKernel const> const lanczosKernelPtr =
528 
529  int numGoodPixels = 0;
530 
531  // transformDestToSrc transforms from parent to parent
532  // but for warping we want local to local coordinates so make a new transform
533  std::vector<double> const destLocalToParentVec = {static_cast<double>(destImage.getX0()),
534  static_cast<double>(destImage.getY0())};
535  auto const destLocalToParentMap = ast::ShiftMap(destLocalToParentVec);
536  std::vector<double> const srcParentToLocalVec = {static_cast<double>(-srcImage.getX0()),
537  static_cast<double>(-srcImage.getY0())};
538  auto const srcParentToLocalMap = ast::ShiftMap(srcParentToLocalVec);
539  auto const localDestToSrcMap =
540  destLocalToParentMap.then(*(destToSrc.getFrameSet())).then(srcParentToLocalMap);
541  auto localDestToSrc = geom::Transform<geom::Point2Endpoint, geom::Point2Endpoint>(localDestToSrcMap);
542 
543  // Get the source MaskedImage and a pixel accessor to it.
544  int const srcWidth = srcImage.getWidth();
545  int const srcHeight = srcImage.getHeight();
546  LOGL_DEBUG("TRACE2.afw.math.warp", "source image width=%d; height=%d", srcWidth, srcHeight);
547 
548  int const destWidth = destImage.getWidth();
549  int const destHeight = destImage.getHeight();
550  LOGL_DEBUG("TRACE2.afw.math.warp", "remap image width=%d; height=%d", destWidth, destHeight);
551 
552  // Set each pixel of destExposure's MaskedImage
553  LOGL_DEBUG("TRACE3.afw.math.warp", "Remapping masked image");
554 
555  int const maxCol = destWidth - 1;
556  int const maxRow = destHeight - 1;
557 
558  detail::WarpAtOnePoint<DestImageT, SrcImageT> warpAtOnePoint(srcImage, control, padValue);
559 
560  if (interpLength > 0) {
561  // Use interpolation. Note that 1 produces the same result as no interpolation
562  // but uses this code branch, thus providing an easy way to compare the two branches.
563 
564  // Estimate for number of horizontal interpolation band edges, to reserve memory in vectors
565  int const numColEdges = 2 + ((destWidth - 1) / interpLength);
566 
567  // A list of edge column indices for interpolation bands;
568  // starts at -1, increments by interpLen (except the final interval), and ends at destWidth-1
569  std::vector<int> edgeColList;
570  edgeColList.reserve(numColEdges);
571 
572  // A list of 1/column width for horizontal interpolation bands; the first value is garbage.
573  // The inverse is used for speed because the values are always multiplied.
574  std::vector<double> invWidthList;
575  invWidthList.reserve(numColEdges);
576 
577  // Compute edgeColList and invWidthList
578  edgeColList.push_back(-1);
579  invWidthList.push_back(0.0);
580  for (int prevEndCol = -1; prevEndCol < maxCol; prevEndCol += interpLength) {
581  int endCol = prevEndCol + interpLength;
582  if (endCol > maxCol) {
583  endCol = maxCol;
584  }
585  edgeColList.push_back(endCol);
586  assert(endCol - prevEndCol > 0);
587  invWidthList.push_back(1.0 / static_cast<double>(endCol - prevEndCol));
588  }
589  assert(edgeColList.back() == maxCol);
590 
591  // A list of delta source positions along the edge columns of the horizontal interpolation bands
592  std::vector<geom::Extent2D> yDeltaSrcPosList(edgeColList.size());
593 
594  // A cache of pixel positions on the source corresponding to the previous or current row
595  // of the destination image.
596  // The first value is for column -1 because the previous source position is used to compute relative
597  // area To simplify the indexing, use an iterator that starts at begin+1, thus: srcPosView =
598  // srcPosList.begin() + 1 srcPosView[col-1] and lower indices are for this row srcPosView[col] and
599  // higher indices are for the previous row
600  std::vector<geom::Point2D> srcPosList(1 + destWidth);
601  std::vector<geom::Point2D>::iterator const srcPosView = srcPosList.begin() + 1;
602 
603  std::vector<geom::Point2D> endColPosList;
604  endColPosList.reserve(numColEdges);
605 
606  // Initialize srcPosList for row -1
607  for (int colBand = 0, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
608  int const endCol = edgeColList[colBand];
609  endColPosList.emplace_back(geom::Point2D(endCol, -1));
610  }
611  auto rightSrcPosList = localDestToSrc.applyForward(endColPosList);
612  srcPosView[-1] = rightSrcPosList[0];
613  for (int colBand = 1, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
614  int const prevEndCol = edgeColList[colBand - 1];
615  int const endCol = edgeColList[colBand];
616  geom::Point2D leftSrcPos = srcPosView[prevEndCol];
617 
618  geom::Extent2D xDeltaSrcPos = (rightSrcPosList[colBand] - leftSrcPos) * invWidthList[colBand];
619 
620  for (int col = prevEndCol + 1; col <= endCol; ++col) {
621  srcPosView[col] = srcPosView[col - 1] + xDeltaSrcPos;
622  }
623  }
624 
625  int endRow = -1;
626  while (endRow < maxRow) {
627  // Next horizontal interpolation band
628 
629  int prevEndRow = endRow;
630  endRow = prevEndRow + interpLength;
631  if (endRow > maxRow) {
632  endRow = maxRow;
633  }
634  assert(endRow - prevEndRow > 0);
635  double interpInvHeight = 1.0 / static_cast<double>(endRow - prevEndRow);
636 
637  // Set yDeltaSrcPosList for this horizontal interpolation band
638  std::vector<geom::Point2D> destRowPosList;
639  destRowPosList.reserve(edgeColList.size());
640  for (int colBand = 0, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
641  int endCol = edgeColList[colBand];
642  destRowPosList.emplace_back(geom::Point2D(endCol, endRow));
643  }
644  auto bottomSrcPosList = localDestToSrc.applyForward(destRowPosList);
645  for (int colBand = 0, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
646  int endCol = edgeColList[colBand];
647  yDeltaSrcPosList[colBand] =
648  (bottomSrcPosList[colBand] - srcPosView[endCol]) * interpInvHeight;
649  }
650 
651  for (int row = prevEndRow + 1; row <= endRow; ++row) {
652  typename DestImageT::x_iterator destXIter = destImage.row_begin(row);
653  srcPosView[-1] += yDeltaSrcPosList[0];
654  for (int colBand = 1, endBand = edgeColList.size(); colBand < endBand; ++colBand) {
655  // Next vertical interpolation band
656 
657  int const prevEndCol = edgeColList[colBand - 1];
658  int const endCol = edgeColList[colBand];
659 
660  // Compute xDeltaSrcPos; remember that srcPosView contains
661  // positions for this row in prevEndCol and smaller indices,
662  // and positions for the previous row for larger indices (including endCol)
663  geom::Point2D leftSrcPos = srcPosView[prevEndCol];
664  geom::Point2D rightSrcPos = srcPosView[endCol] + yDeltaSrcPosList[colBand];
665  geom::Extent2D xDeltaSrcPos = (rightSrcPos - leftSrcPos) * invWidthList[colBand];
666 
667  for (int col = prevEndCol + 1; col <= endCol; ++col, ++destXIter) {
668  geom::Point2D leftSrcPos = srcPosView[col - 1];
669  geom::Point2D srcPos = leftSrcPos + xDeltaSrcPos;
670  double relativeArea = computeRelativeArea(srcPos, leftSrcPos, srcPosView[col]);
671 
672  srcPosView[col] = srcPos;
673 
674  if (warpAtOnePoint(
675  destXIter, srcPos, relativeArea,
677  ++numGoodPixels;
678  }
679  } // for col
680  } // for col band
681  } // for row
682  } // while next row band
683 
684  } else {
685  // No interpolation
686 
687  // prevSrcPosList = source positions from the previous row; these are used to compute pixel area;
688  // to begin, compute sources positions corresponding to destination row = -1
689  std::vector<geom::Point2D> destPosList;
690  destPosList.reserve(1 + destWidth);
691  for (int col = -1; col < destWidth; ++col) {
692  destPosList.emplace_back(geom::Point2D(col, -1));
693  }
694  auto prevSrcPosList = localDestToSrc.applyForward(destPosList);
695 
696  for (int row = 0; row < destHeight; ++row) {
697  destPosList.clear();
698  for (int col = -1; col < destWidth; ++col) {
699  destPosList.emplace_back(geom::Point2D(col, row));
700  }
701  auto srcPosList = localDestToSrc.applyForward(destPosList);
702 
703  typename DestImageT::x_iterator destXIter = destImage.row_begin(row);
704  for (int col = 0; col < destWidth; ++col, ++destXIter) {
705  // column index = column + 1 because the first entry in srcPosList is for column -1
706  auto srcPos = srcPosList[col + 1];
707  double relativeArea =
708  computeRelativeArea(srcPos, prevSrcPosList[col], prevSrcPosList[col + 1]);
709 
710  if (warpAtOnePoint(destXIter, srcPos, relativeArea,
712  ++numGoodPixels;
713  }
714  } // for col
715  // move points from srcPosList to prevSrcPosList (we don't care about what ends up in srcPosList
716  // because it will be reallocated anyway)
717  swap(srcPosList, prevSrcPosList);
718  } // for row
719  } // if interp
720 
721  return numGoodPixels;
722 }
723 
724 template <typename DestImageT, typename SrcImageT>
725 int warpCenteredImage(DestImageT &destImage, SrcImageT const &srcImage,
726  geom::LinearTransform const &linearTransform, geom::Point2D const &centerPosition,
727  WarpingControl const &control, typename DestImageT::SinglePixel padValue) {
728  // force src and dest to be the same size and xy0
729  if ((destImage.getWidth() != srcImage.getWidth()) || (destImage.getHeight() != srcImage.getHeight()) ||
730  (destImage.getXY0() != srcImage.getXY0())) {
731  std::ostringstream errStream;
732  errStream << "src and dest images must have same size and xy0.";
734  }
735 
736  // set the xy0 coords to 0,0 to make life easier
737  SrcImageT srcImageCopy(srcImage, true);
738  srcImageCopy.setXY0(0, 0);
739  destImage.setXY0(0, 0);
740  geom::Extent2D cLocal = geom::Extent2D(centerPosition) - geom::Extent2D(srcImage.getXY0());
741 
742  // for the affine transform, the centerPosition will not only get sheared, but also
743  // moved slightly. So we'll include a translation to move it back by an amount
744  // centerPosition - translatedCenterPosition
745  geom::AffineTransform affTran(linearTransform, cLocal - linearTransform(cLocal));
746  geom::AffineXYTransform affXYTransform(affTran);
747 
748 // now warp
749 #if 0
750  static float t = 0.0;
751  float t_before = 1.0*clock()/CLOCKS_PER_SEC;
752  int n = warpImage(destImage, srcImageCopy, affTran, control, padValue);
753  float t_after = 1.0*clock()/CLOCKS_PER_SEC;
754  float dt = t_after - t_before;
755  t += dt;
756  std::cout <<srcImage.getWidth()<<"x"<<srcImage.getHeight()<<": "<< dt <<" "<< t <<std::endl;
757 #else
758  int n = warpImage(destImage, srcImageCopy, affXYTransform, control, padValue);
759 #endif
760 
761  // fix the origin and we're done.
762  destImage.setXY0(srcImage.getXY0());
763 
764  return n;
765 }
766 
767 //
768 // Explicit instantiations
769 //
771 // may need to omit default params for EXPOSURE -- original code did that and it worked
772 #define EXPOSURE(PIXTYPE) image::Exposure<PIXTYPE, image::MaskPixel, image::VariancePixel>
773 #define MASKEDIMAGE(PIXTYPE) image::MaskedImage<PIXTYPE, image::MaskPixel, image::VariancePixel>
774 #define IMAGE(PIXTYPE) image::Image<PIXTYPE>
775 #define NL /* */
776 
777 #define INSTANTIATE(DESTIMAGEPIXELT, SRCIMAGEPIXELT) \
778  template int warpCenteredImage( \
779  IMAGE(DESTIMAGEPIXELT) & destImage, IMAGE(SRCIMAGEPIXELT) const &srcImage, \
780  geom::LinearTransform const &linearTransform, geom::Point2D const &centerPosition, \
781  WarpingControl const &control, IMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
782  NL template int warpCenteredImage( \
783  MASKEDIMAGE(DESTIMAGEPIXELT) & destImage, MASKEDIMAGE(SRCIMAGEPIXELT) const &srcImage, \
784  geom::LinearTransform const &linearTransform, geom::Point2D const &centerPosition, \
785  WarpingControl const &control, MASKEDIMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
786  NL template int warpImage(IMAGE(DESTIMAGEPIXELT) & destImage, IMAGE(SRCIMAGEPIXELT) const &srcImage, \
787  geom::XYTransform const &xyTransform, WarpingControl const &control, \
788  IMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
789  NL template int warpImage(MASKEDIMAGE(DESTIMAGEPIXELT) & destImage, \
790  MASKEDIMAGE(SRCIMAGEPIXELT) const &srcImage, \
791  geom::XYTransform const &xyTransform, WarpingControl const &control, \
792  MASKEDIMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
793  NL template int warpImage(IMAGE(DESTIMAGEPIXELT) & destImage, IMAGE(SRCIMAGEPIXELT) const &srcImage, \
794  geom::Transform<geom::Point2Endpoint, geom::Point2Endpoint> const &destToSrc, \
795  WarpingControl const &control, IMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
796  NL template int warpImage( \
797  MASKEDIMAGE(DESTIMAGEPIXELT) & destImage, MASKEDIMAGE(SRCIMAGEPIXELT) const &srcImage, \
798  geom::Transform<geom::Point2Endpoint, geom::Point2Endpoint> const &destToSrc, \
799  WarpingControl const &control, MASKEDIMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
800  NL template int warpImage(IMAGE(DESTIMAGEPIXELT) & destImage, image::Wcs const &destWcs, \
801  IMAGE(SRCIMAGEPIXELT) const &srcImage, image::Wcs const &srcWcs, \
802  WarpingControl const &control, IMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
803  NL template int warpImage(MASKEDIMAGE(DESTIMAGEPIXELT) & destImage, image::Wcs const &destWcs, \
804  MASKEDIMAGE(SRCIMAGEPIXELT) const &srcImage, image::Wcs const &srcWcs, \
805  WarpingControl const &control, \
806  MASKEDIMAGE(DESTIMAGEPIXELT)::SinglePixel padValue); \
807  NL template int warpExposure(EXPOSURE(DESTIMAGEPIXELT) & destExposure, \
808  EXPOSURE(SRCIMAGEPIXELT) const &srcExposure, WarpingControl const &control, \
809  EXPOSURE(DESTIMAGEPIXELT)::MaskedImageT::SinglePixel padValue);
810 
811 INSTANTIATE(double, double)
812 INSTANTIATE(double, float)
813 INSTANTIATE(double, int)
814 INSTANTIATE(double, std::uint16_t)
815 INSTANTIATE(float, float)
816 INSTANTIATE(float, int)
818 INSTANTIATE(int, int)
821 } // namespace math
822 } // namespace afw
823 } // namespace lsst
T empty(T... args)
Functor class that wraps an XYTransform.
virtual std::string toString(std::string const &="") const
Return string representation.
double indexToPosition(double ind)
Convert image index to image position.
Definition: ImageUtils.h:55
table::Key< std::string > name
Definition: ApCorrMap.cc:71
Extent< double, 2 > Extent2D
Definition: Extent.h:344
T swap(T... args)
geom::Point2D skyToPixel(geom::Angle sky1, geom::Angle sky2) const
Convert from sky coordinates (e.g.
Definition: Wcs.cc:740
std::shared_ptr< const ast::FrameSet > getFrameSet() const
Get the contained frameset.
Definition: Transform.h:143
virtual void setKernelParameter(unsigned int ind, double value) const
Set one kernel parameter.
T endl(T... args)
lsst::afw::geom::Point2I getCtr() const
Return index of kernel&#39;s center.
Definition: Kernel.h:244
A kernel described by a pair of functions: func(x, y) = colFunc(x) * rowFunc(y)
Definition: Kernel.h:927
void setWarpingKernelName(std::string const &warpingKernelName)
set the warping kernel by name
XYTransformFromWcsPair: An XYTransform obtained by putting two Wcs objects "back to back"...
Definition: Wcs.h:506
A functor that computes one warped pixel.
Parameters to control convolution.
Definition: warpExposure.h:234
Implementation of the WCS standard for a any projection.
Definition: Wcs.h:104
std::shared_ptr< SeparableKernel > getWarpingKernel() const
get the warping kernel
int warpCenteredImage(DestImageT &destImage, SrcImageT const &srcImage, lsst::afw::geom::LinearTransform const &linearTransform, lsst::afw::geom::Point2D const &centerPosition, WarpingControl const &control, typename DestImageT::SinglePixel padValue=lsst::afw::math::edgePixel< DestImageT >(typename lsst::afw::image::detail::image_traits< DestImageT >::image_category()))
Warp an image with a LinearTranform about a specified point.
#define LOGL_DEBUG(logger, message...)
virtual std::shared_ptr< Kernel > clone() const
Return a pointer to a deep copy of this kernel.
Describe an exposure&#39;s calibration.
Definition: Calib.h:96
std::shared_ptr< SeparableKernel > makeWarpingKernel(std::string name)
Return a warping kernel given its name.
void setMaskWarpingKernel(SeparableKernel const &maskWarpingKernel)
set the mask warping kernel
An integer coordinate rectangle.
Definition: Box.h:55
int warpImage(DestImageT &destImage, lsst::afw::image::Wcs const &destWcs, SrcImageT const &srcImage, lsst::afw::image::Wcs const &srcWcs, WarpingControl const &control, typename DestImageT::SinglePixel padValue=lsst::afw::math::edgePixel< DestImageT >(typename lsst::afw::image::detail::image_traits< DestImageT >::image_category()))
Warp an Image or MaskedImage to a new Wcs.
STL class.
virtual std::shared_ptr< Kernel > clone() const
Return a pointer to a deep copy of this kernel.
Definition: warpExposure.cc:99
A 2D linear coordinate transformation.
T push_back(T... args)
int warpExposure(DestExposureT &destExposure, SrcExposureT const &srcExposure, WarpingControl const &control, typename DestExposureT::MaskedImageT::SinglePixel padValue=lsst::afw::math::edgePixel< typename DestExposureT::MaskedImageT >(typename lsst::afw::image::detail::image_traits< typename DestExposureT::MaskedImageT >::image_category()))
Warp (remap) one exposure to another.
A class representing an angle.
Definition: Angle.h:102
Base class to transform pixel position for a destination image to its position in the original source...
int getOrder() const
get the order of the kernel
A base class for image defects.
std::shared_ptr< coord::Coord > pixelToSky(double pix1, double pix2) const
Convert from pixel position to sky coordinates (e.g.
Definition: Wcs.cc:822
int end
int getInterpLength() const
get the interpolation length (pixels)
Definition: warpExposure.h:287
An affine coordinate transformation consisting of a linear transformation and an offset.
void setMaskWarpingKernelName(std::string const &maskWarpingKernelName)
set or clear the mask warping kernel by name
bool isSameObject(A const &, B const &)
Definition: warpExposure.h:502
#define INSTANTIATE(FROMSYS, TOSYS)
Definition: Detector.cc:139
void setWarpingKernel(SeparableKernel const &warpingKernel)
set the warping kernel
T str(T... args)
virtual std::string toString(std::string const &="") const
Return string representation.
T static_pointer_cast(T... args)
double x
T clear(T... args)
bool contains(Point2I const &point) const
Return true if the box contains the point.
Bilinear warping: fast; good for undersampled data.
Definition: warpExposure.h:93
int getWidth() const
Return the Kernel&#39;s width.
Definition: Kernel.h:234
virtual Kernel::Pixel operator()(double x) const
Solve bilinear equation.
void swap(Image< PixelT > &a, Image< PixelT > &b)
Definition: Image.cc:442
T size(T... args)
std::shared_ptr< SeparableKernel > getMaskWarpingKernel() const
get the mask warping kernel
#define LSST_EXCEPT(type,...)
STL class.
virtual void setKernelParameter(unsigned int ind, double value) const
Set one kernel parameter.
T begin(T... args)
virtual std::shared_ptr< Kernel > clone() const
Return a pointer to a deep copy of this kernel.
virtual void setKernelParameter(unsigned int ind, double value) const
Set one kernel parameter.
T c_str(T... args)
Virtual base class for 2D transforms.
Definition: XYTransform.h:49
virtual std::shared_ptr< Kernel > clone() const
Return a pointer to a deep copy of this kernel.
Nearest neighbor warping: fast; good for undersampled data.
Definition: warpExposure.h:152
T back(T... args)
Lanczos warping: accurate but slow and can introduce ringing artifacts.
Definition: warpExposure.h:64
ImageT::image_category image_category
Definition: ImageBase.h:71
virtual Kernel::Pixel operator()(double x) const
Solve nearest neighbor equation.
Wrap an AffineTransform.
Definition: XYTransform.h:165
virtual void setKernelParameter(unsigned int ind, double value) const
Set one kernel parameter.
geom::Extent2I const getDimensions() const
Return the Kernel&#39;s dimensions (width, height)
Definition: Kernel.h:222
virtual std::shared_ptr< Wcs > clone(void) const
Definition: Wcs.cc:526
Transform LSST spatial data, such as Point2D and IcrsCoord, using an AST transform.
Definition: Transform.h:69
T reserve(T... args)
T emplace_back(T... args)