lsst.afw  13.0-91-g2a3e2ee
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
FootprintSet.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
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 /*
26  * Utilities to detect sets of Footprint%s
27  *
28  * Create and use an lsst::afw::detection::FootprintSet, a collection of pixels above (or below) a threshold
29  * in an Image
30  *
31  * The "collections of pixels" are represented as lsst::afw::detection::Footprint%s, so an example application
32  * would be:
33  *
34  namespace image = lsst::afw::image; namespace detection = lsst::afw::detection;
35 
36  image::MaskedImage<float> img(10,20);
37  *img.getImage() = 100;
38 
39  detection::FootprintSet<float> sources(img, 10);
40  cout << "Found " << sources.getFootprints()->size() << " sources" << std::endl;
41  */
42 #include <cstdint>
43 #include <memory>
44 #include <algorithm>
45 #include <cassert>
46 #include <set>
47 #include <string>
48 #include <typeinfo>
49 #include "boost/format.hpp"
50 #include "lsst/pex/exceptions.h"
57 
58 namespace lsst {
59 namespace afw {
60 namespace detection {
61 
62 namespace {
64 
65 typedef std::uint64_t IdPixelT; // Type of temporary Images used in merging Footprints
66 
67 struct Threshold_traits {};
68 struct ThresholdLevel_traits : public Threshold_traits { // Threshold is a single number
69 };
70 struct ThresholdPixelLevel_traits : public Threshold_traits { // Threshold varies from pixel to pixel
71 };
72 struct ThresholdBitmask_traits : public Threshold_traits { // Threshold ORs with a bitmask
73 };
74 
75 template <typename PixelT>
76 class setIdImage {
77 public:
78  explicit setIdImage(std::uint64_t const id, bool overwriteId = false, long const idMask = 0x0)
79  : _id(id),
80  _idMask(idMask),
81  _withSetReplace(false),
82  _overwriteId(overwriteId),
83  _oldIds(NULL),
84  _pos() {
85  if (_id & _idMask) {
86  throw LSST_EXCEPT(
87  pex::exceptions::InvalidParameterError,
88  str(boost::format("Id 0x%x sets bits in the protected mask 0x%x") % _id % _idMask));
89  }
90  }
91 
92  setIdImage(std::uint64_t const id, typename std::set<std::uint64_t> *oldIds, bool overwriteId = false,
93  long const idMask = 0x0)
94  : _id(id),
95  _idMask(idMask),
96  _withSetReplace(true),
97  _overwriteId(overwriteId),
98  _oldIds(oldIds),
99  _pos(oldIds->begin()) {
100  if (_id & _idMask) {
101  throw LSST_EXCEPT(
102  pex::exceptions::InvalidParameterError,
103  str(boost::format("Id 0x%x sets bits in the protected mask 0x%x") % _id % _idMask));
104  }
105  }
106 
107  void operator()(geom::Point2I const &point, PixelT &input) {
108  if (_overwriteId) {
109  auto val = input & ~_idMask;
110 
111  if (val != 0 && _withSetReplace) {
112  _pos = _oldIds->insert(_pos, val);
113  }
114 
115  input = (input & _idMask) + _id;
116  } else {
117  input += _id;
118  }
119  }
120 
121 private:
122  std::uint64_t const _id;
123  long const _idMask;
124  bool _withSetReplace;
125  bool _overwriteId;
126  typename std::set<std::uint64_t> *_oldIds;
127  typename std::set<std::uint64_t>::const_iterator _pos;
128 };
129 
130 //
131 // Define our own functions to handle NaN tests; this gives us the
132 // option to define a value for e.g. image::MaskPixel or int
133 //
134 template <typename T>
135 inline bool isBadPixel(T) {
136  return false;
137 }
138 
139 template <>
140 inline bool isBadPixel(float val) {
141  return std::isnan(val);
142 }
143 
144 template <>
145 inline bool isBadPixel(double val) {
146  return std::isnan(val);
147 }
148 
149 /*
150  * Return the number of bits required to represent a unsigned long
151  */
152 int nbit(unsigned long i) {
153  int n = 0;
154  while (i > 0) {
155  ++n;
156  i >>= 1;
157  }
158 
159  return n;
160 }
161 /*
162  * Find the list of pixel values that lie in a Footprint
163  *
164  * Used when the Footprints are constructed from an Image containing Footprint indices
165  */
166 template <typename T>
167 class FindIdsInFootprint {
168 public:
169  explicit FindIdsInFootprint() : _ids(), _old(0) {}
170 
171  // Reset everything for a new Footprint
172  void reset() {
173  _ids.clear();
174  _old = 0;
175  }
176 
177  // Take by copy and not be reference on purpose
178  void operator()(geom::Point2I const &point, T val) {
179  if (val != _old) {
180  _ids.insert(val);
181  _old = val;
182  }
183  }
184 
185  std::set<T> const &getIds() const { return _ids; }
186 
187 private:
188  std::set<T> _ids;
189  T _old;
190 };
191 
192 /*
193  * Sort peaks by decreasing pixel value. N.b. -ve peaks are sorted the same way as +ve ones
194  */
195 struct SortPeaks {
196  bool operator()(std::shared_ptr<PeakRecord const> a, std::shared_ptr<PeakRecord const> b) {
197  if (a->getPeakValue() != b->getPeakValue()) {
198  return (a->getPeakValue() > b->getPeakValue());
199  }
200 
201  if (a->getIx() != b->getIx()) {
202  return (a->getIx() < b->getIx());
203  }
204 
205  return (a->getIy() < b->getIy());
206  }
207 };
208 /*
209  * Worker routine for merging two FootprintSets, possibly growing them as we proceed
210  */
211 FootprintSet mergeFootprintSets(FootprintSet const &lhs, // the FootprintSet to be merged to
212  int rLhs, // Grow lhs Footprints by this many pixels
213  FootprintSet const &rhs, // the FootprintSet to be merged into lhs
214  int rRhs, // Grow rhs Footprints by this many pixels
215  FootprintControl const &ctrl // Control how the grow is done
216  ) {
217  typedef FootprintSet::FootprintList FootprintList;
218  // The isXXX routines return <isset, value>
219  bool const circular = ctrl.isCircular().first && ctrl.isCircular().second;
220  bool const isotropic = ctrl.isIsotropic().second; // isotropic grow as opposed to a Manhattan metric
221  // n.b. Isotropic grows are significantly slower
222  bool const left = ctrl.isLeft().first && ctrl.isLeft().second;
223  bool const right = ctrl.isRight().first && ctrl.isRight().second;
224  bool const up = ctrl.isUp().first && ctrl.isUp().second;
225  bool const down = ctrl.isDown().first && ctrl.isDown().second;
226 
227  geom::Box2I const region = lhs.getRegion();
228  if (region != rhs.getRegion()) {
229  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
230  boost::format("The two FootprintSets must have the same region").str());
231  }
232 
233  auto idImage = std::make_shared<image::Image<IdPixelT>>(region);
234  idImage->setXY0(region.getMinX(), region.getMinY());
235  *idImage = 0;
236 
237  FootprintList const &lhsFootprints = *lhs.getFootprints();
238  FootprintList const &rhsFootprints = *rhs.getFootprints();
239  int const nLhs = lhsFootprints.size();
240  int const nRhs = rhsFootprints.size();
241  /*
242  * In general the lists of Footprints overlap, so we need to make sure that the IDs can be
243  * uniquely recovered from the idImage. We do this by allocating a range of bits to the lhs IDs
244  */
245  int const lhsIdNbit = nbit(nLhs);
246  int const lhsIdMask = (lhsIdNbit == 0) ? 0x0 : (1 << lhsIdNbit) - 1;
247 
248  if (std::size_t(nRhs << lhsIdNbit) > std::numeric_limits<IdPixelT>::max() - 1) {
249  throw LSST_EXCEPT(
250  pex::exceptions::OverflowError,
251  (boost::format("%d + %d footprints need too many bits; change IdPixelT typedef") % nLhs %
252  nRhs).str());
253  }
254  /*
255  * When we insert grown Footprints into the idImage we can potentially overwrite an entire Footprint,
256  * losing any peaks that it might contain. We'll preserve the overwritten Ids in case we need to
257  * get them back (n.b. Footprints that overlap, but both if which survive, will appear in this list)
258  */
259  typedef std::map<int, std::set<std::uint64_t>> OldIdMap;
260  OldIdMap overwrittenIds; // here's a map from id -> overwritten IDs
261 
262  auto grower = [&circular, &up, &down, &left, &right, &isotropic](
263  std::shared_ptr<Footprint> const &foot, int amount) -> std::shared_ptr<Footprint> {
264  if (circular) {
265  auto element = isotropic ? geom::Stencil::CIRCLE : geom::Stencil::MANHATTAN;
266  auto tmpFoot = std::make_shared<Footprint>(foot->getSpans()->dilated(amount, element),
267  foot->getRegion());
268  return tmpFoot;
269  } else {
270  int top = up ? amount : 0;
271  int bottom = down ? amount : 0;
272  int lLimit = left ? amount : 0;
273  int rLimit = right ? amount : 0;
274 
275  auto yRange = top + bottom + 1;
276  std::vector<geom::Span> spanList;
277  spanList.reserve(yRange);
278 
279  for (auto dy = 1; dy <= top; ++dy) {
280  spanList.push_back(geom::Span(dy, 0, 0));
281  }
282  for (auto dy = -1; dy >= -bottom; --dy) {
283  spanList.push_back(geom::Span(dy, 0, 0));
284  }
285  spanList.push_back(geom::Span(0, -lLimit, rLimit));
286  geom::SpanSet structure(std::move(spanList));
287  auto tmpFoot =
288  std::make_shared<Footprint>(foot->getSpans()->dilated(structure), foot->getRegion());
289  return tmpFoot;
290  }
291  };
292 
293  IdPixelT id = 1; // the ID inserted into the image
294  for (FootprintList::const_iterator ptr = lhsFootprints.begin(), end = lhsFootprints.end(); ptr != end;
295  ++ptr, ++id) {
296  std::shared_ptr<Footprint> foot = *ptr;
297 
298  if (rLhs > 0 && foot->getArea() > 0) {
299  foot = grower(foot, rLhs);
300  }
301 
302  std::set<std::uint64_t> overwritten;
303  foot->getSpans()
304  ->clippedTo(idImage->getBBox())
305  ->applyFunctor(setIdImage<IdPixelT>(id, &overwritten, true), *idImage);
306 
307  if (!overwritten.empty()) {
308  overwrittenIds.insert(overwrittenIds.end(), std::make_pair(id, overwritten));
309  }
310  }
311 
312  assert(id <= std::size_t(1 << lhsIdNbit));
313  id = (1 << lhsIdNbit);
314  for (FootprintList::const_iterator ptr = rhsFootprints.begin(), end = rhsFootprints.end(); ptr != end;
315  ++ptr, id += (1 << lhsIdNbit)) {
316  std::shared_ptr<Footprint> foot = *ptr;
317 
318  if (rRhs > 0 && foot->getArea() > 0) {
319  foot = grower(foot, rRhs);
320  }
321 
322  std::set<std::uint64_t> overwritten;
323  foot->getSpans()
324  ->clippedTo(idImage->getBBox())
325  ->applyFunctor(setIdImage<IdPixelT>(id, &overwritten, true, lhsIdMask), *idImage);
326 
327  if (!overwritten.empty()) {
328  overwrittenIds.insert(overwrittenIds.end(), std::make_pair(id, overwritten));
329  }
330  }
331 
332  FootprintSet fs(*idImage, Threshold(1), 1, false); // detect all pixels in rhs + lhs
333  /*
334  * Now go through the new Footprints looking up and remembering their progenitor's IDs; we'll use
335  * these IDs to merge the peaks in a moment
336  *
337  * We can't do this as we go through the idFinder as the IDs it returns are
338  * (lhsId + 1) | ((rhsId + 1) << nbit)
339  * and, depending on the geometry, values of lhsId and/or rhsId can appear multiple times
340  * (e.g. if nbit is 2, idFinder IDs 0x5 and 0x6 both contain lhsId = 0) so we get duplicates
341  * of peaks. This is not too bad, but it's a bit of a pain to make the lists unique again,
342  * and we avoid this by this two-step process.
343  */
344  FindIdsInFootprint<IdPixelT> idFinder;
345  for (FootprintList::iterator ptr = fs.getFootprints()->begin(), end = fs.getFootprints()->end();
346  ptr != end; ++ptr) {
347  std::shared_ptr<Footprint> foot = *ptr;
348 
349  // find the (mangled) [lr]hsFootprint IDs that contribute to foot
350  foot->getSpans()->applyFunctor(idFinder, *idImage);
351 
352  std::set<std::uint64_t> lhsFootprintIndxs, rhsFootprintIndxs; // indexes into [lr]hsFootprints
353 
354  for (std::set<IdPixelT>::iterator idptr = idFinder.getIds().begin(), idend = idFinder.getIds().end();
355  idptr != idend; ++idptr) {
356  unsigned int indx = *idptr;
357  if ((indx & lhsIdMask) > 0) {
358  std::uint64_t i = (indx & lhsIdMask) - 1;
359  lhsFootprintIndxs.insert(i);
360  /*
361  * Now allow for Footprints that vanished beneath this one
362  */
363  OldIdMap::iterator mapPtr = overwrittenIds.find(indx);
364  if (mapPtr != overwrittenIds.end()) {
365  std::set<std::uint64_t> &overwritten = mapPtr->second;
366 
367  for (std::set<std::uint64_t>::iterator ptr = overwritten.begin(), end = overwritten.end();
368  ptr != end; ++ptr) {
369  lhsFootprintIndxs.insert((*ptr & lhsIdMask) - 1);
370  }
371  }
372  }
373  indx >>= lhsIdNbit;
374 
375  if (indx > 0) {
376  std::uint64_t i = indx - 1;
377  rhsFootprintIndxs.insert(i);
378  /*
379  * Now allow for Footprints that vanished beneath this one
380  */
381  OldIdMap::iterator mapPtr = overwrittenIds.find(indx);
382  if (mapPtr != overwrittenIds.end()) {
383  std::set<std::uint64_t> &overwritten = mapPtr->second;
384 
385  for (std::set<std::uint64_t>::iterator ptr = overwritten.begin(), end = overwritten.end();
386  ptr != end; ++ptr) {
387  rhsFootprintIndxs.insert(*ptr - 1);
388  }
389  }
390  }
391  }
392  /*
393  * We now have a complete set of Footprints that contributed to this one, so merge
394  * all their Peaks into the new one
395  */
396  PeakCatalog &peaks = foot->getPeaks();
397 
398  for (std::set<std::uint64_t>::iterator ptr = lhsFootprintIndxs.begin(), end = lhsFootprintIndxs.end();
399  ptr != end; ++ptr) {
400  std::uint64_t i = *ptr;
401  assert(i < lhsFootprints.size());
402  PeakCatalog const &oldPeaks = lhsFootprints[i]->getPeaks();
403 
404  int const nold = peaks.size();
405  peaks.insert(peaks.end(), oldPeaks.begin(), oldPeaks.end());
406  // We use getInternal() here to get the vector of shared_ptr that Catalog uses internally,
407  // which causes the STL algorithm to copy pointers instead of PeakRecords (which is what
408  // it'd try to do if we passed Catalog's own iterators).
409  std::inplace_merge(peaks.getInternal().begin(), peaks.getInternal().begin() + nold,
410  peaks.getInternal().end(), SortPeaks());
411  }
412 
413  for (std::set<std::uint64_t>::iterator ptr = rhsFootprintIndxs.begin(), end = rhsFootprintIndxs.end();
414  ptr != end; ++ptr) {
415  std::uint64_t i = *ptr;
416  assert(i < rhsFootprints.size());
417  PeakCatalog const &oldPeaks = rhsFootprints[i]->getPeaks();
418 
419  int const nold = peaks.size();
420  peaks.insert(peaks.end(), oldPeaks.begin(), oldPeaks.end());
421  // See note above on why we're using getInternal() here.
422  std::inplace_merge(peaks.getInternal().begin(), peaks.getInternal().begin() + nold,
423  peaks.getInternal().end(), SortPeaks());
424  }
425  idFinder.reset();
426  }
427 
428  return fs;
429 }
430 /*
431  * run-length code for part of object
432  */
433 class IdSpan {
434 public:
435  explicit IdSpan(int id, int y, int x0, int x1, double good) : id(id), y(y), x0(x0), x1(x1), good(good) {}
436  int id; /* ID for object */
437  int y; /* Row wherein IdSpan dwells */
438  int x0, x1; /* inclusive range of columns */
439  bool good; /* includes a value over the desired threshold? */
440 };
441 /*
442  * comparison functor; sort by ID then row
443  */
444 struct IdSpanCompar
445  : public std::binary_function<const std::shared_ptr<IdSpan>, const std::shared_ptr<IdSpan>, bool> {
446  bool operator()(std::shared_ptr<IdSpan> const a, std::shared_ptr<IdSpan> const b) {
447  if (a->id < b->id) {
448  return true;
449  } else if (a->id > b->id) {
450  return false;
451  } else {
452  return (a->y < b->y) ? true : false;
453  }
454  }
455 };
456 /*
457  * Follow a chain of aliases, returning the final resolved value.
458  */
459 int resolve_alias(std::vector<int> const &aliases, /* list of aliases */
460  int id) { /* alias to look up */
461  int resolved = id; /* resolved alias */
462 
463  while (id != aliases[id]) {
464  resolved = id = aliases[id];
465  }
466 
467  return (resolved);
468 }
470 }
471 
472 namespace {
473 template <typename ImageT>
474 void findPeaksInFootprint(ImageT const &image, bool polarity, PeakCatalog &peaks, Footprint &foot,
475  std::size_t const margin = 0) {
476  auto spanSet = foot.getSpans();
477  if (spanSet->size() == 0) {
478  return;
479  }
480  auto bbox = image.getBBox();
481  for (auto const &spanIter : *spanSet) {
482  auto y = spanIter.getY() - image.getY0();
483  if (static_cast<std::size_t>(y + image.getY0()) < bbox.getMinY() + margin ||
484  static_cast<std::size_t>(y + image.getY0()) > bbox.getMaxY() - margin) {
485  continue;
486  }
487  for (auto x = spanIter.getMinX() - image.getX0(); x <= spanIter.getMaxX() - image.getX0(); ++x) {
488  if (static_cast<std::size_t>(x + image.getX0()) < (bbox.getMinX() + margin) ||
489  static_cast<std::size_t>(x + image.getX0()) > (bbox.getMaxX() - margin)) {
490  continue;
491  }
492  auto val = image(x, y);
493  if (polarity) { // look for +ve peaks
494  if (image(x - 1, y + 1) > val || image(x, y + 1) > val || image(x + 1, y + 1) > val ||
495  image(x - 1, y) > val || image(x + 1, y) > val || image(x - 1, y - 1) > val ||
496  image(x, y - 1) > val || image(x + 1, y - 1) > val) {
497  continue;
498  }
499  } else { // look for -ve "peaks" (pits)
500  if (image(x - 1, y + 1) < val || image(x, y + 1) < val || image(x + 1, y + 1) < val ||
501  image(x - 1, y) < val || image(x + 1, y) < val || image(x - 1, y - 1) < val ||
502  image(x, y - 1) < val || image(x + 1, y - 1) < val) {
503  continue;
504  }
505  }
506 
507  foot.addPeak(x + image.getX0(), y + image.getY0(), val);
508  }
509  }
510 }
511 
512 template <typename ImageT>
513 class FindMaxInFootprint {
514 public:
515  explicit FindMaxInFootprint(bool polarity)
516  : _polarity(polarity),
517  _x(0),
518  _y(0),
519  _min(std::numeric_limits<double>::max()),
520  _max(-std::numeric_limits<double>::max()) {}
521 
522  void operator()(geom::Point2I const &point, ImageT const &val) {
523  if (_polarity) {
524  if (val > _max) {
525  _max = val;
526  _x = point.getX();
527  _y = point.getY();
528  }
529  } else {
530  if (val < _min) {
531  _min = val;
532  _x = point.getX();
533  _y = point.getY();
534  }
535  }
536  }
537 
538  void addRecord(Footprint &foot) const { foot.addPeak(_x, _y, _polarity ? _max : _min); }
539 
540 private:
541  bool _polarity;
542  int _x, _y;
543  double _min, _max;
544 };
545 
546 template <typename ImageT, typename ThresholdT>
547 void findPeaks(std::shared_ptr<Footprint> foot, ImageT const &img, bool polarity, ThresholdT) {
548  findPeaksInFootprint(img, polarity, foot->getPeaks(), *foot, 1);
549 
550  // We use getInternal() here to get the vector of shared_ptr that Catalog uses internally,
551  // which causes the STL algorithm to copy pointers instead of PeakRecords (which is what
552  // it'd try to do if we passed Catalog's own iterators).
553  std::stable_sort(foot->getPeaks().getInternal().begin(), foot->getPeaks().getInternal().end(),
554  SortPeaks());
555 
556  if (foot->getPeaks().empty()) {
557  FindMaxInFootprint<typename ImageT::Pixel> maxFinder(polarity);
558  foot->getSpans()->applyFunctor(maxFinder, ndarray::ndImage(img.getArray(), img.getXY0()));
559  maxFinder.addRecord(*foot);
560  }
561 }
562 
563 // No need to search for peaks when processing a Mask
564 template <typename ImageT>
565 void findPeaks(std::shared_ptr<Footprint>, ImageT const &, bool, ThresholdBitmask_traits) {
566  ;
567 }
568 }
569 
570 /*
571  * Functions to determine if a pixel's in a Footprint
572  */
573 template <typename ImagePixelT, typename IterT>
574 static inline bool inFootprint(ImagePixelT pixVal, IterT, bool polarity, double thresholdVal,
575  ThresholdLevel_traits) {
576  return (polarity ? pixVal : -pixVal) >= thresholdVal;
577 }
578 
579 template <typename ImagePixelT, typename IterT>
580 static inline bool inFootprint(ImagePixelT pixVal, IterT var, bool polarity, double thresholdVal,
581  ThresholdPixelLevel_traits) {
582  return (polarity ? pixVal : -pixVal) >= thresholdVal * ::sqrt(*var);
583 }
584 
585 template <typename ImagePixelT, typename IterT>
586 static inline bool inFootprint(ImagePixelT pixVal, IterT, bool, double thresholdVal,
587  ThresholdBitmask_traits) {
588  return (pixVal & static_cast<long>(thresholdVal));
589 }
590 
591 /*
592  * Advance the x_iterator to the variance image, when relevant (it may be NULL otherwise)
593  */
594 template <typename IterT>
595 static inline IterT advancePtr(IterT varPtr, Threshold_traits) {
596  return varPtr;
597 }
598 
599 template <typename IterT>
600 static inline IterT advancePtr(IterT varPtr, ThresholdPixelLevel_traits) {
601  return varPtr + 1;
602 }
603 
604 /*
605  * Here's the working routine for the FootprintSet constructors; see documentation
606  * of the constructors themselves
607  */
608 template <typename ImagePixelT, typename MaskPixelT, typename VariancePixelT, typename ThresholdTraitT>
609 static void findFootprints(
610  typename FootprintSet::FootprintList *_footprints, // Footprints
611  geom::Box2I const &_region, // BBox of pixels that are being searched
612  image::ImageBase<ImagePixelT> const &img, // Image to search for objects
613  image::Image<VariancePixelT> const *var, // img's variance
614  double const footprintThreshold, // threshold value for footprint
615  double const includeThresholdMultiplier, // threshold (relative to footprintThreshold) for inclusion
616  bool const polarity, // if false, search _below_ thresholdVal
617  int const npixMin, // minimum number of pixels in an object
618  bool const setPeaks // should I set the Peaks list?
619  ) {
620  int id; /* object ID */
621  int in_span; /* object ID of current IdSpan */
622  int nobj = 0; /* number of objects found */
623  int x0 = 0; /* unpacked from a IdSpan */
624 
625  double includeThreshold = footprintThreshold * includeThresholdMultiplier; // Threshold for inclusion
626 
627  int const row0 = img.getY0();
628  int const col0 = img.getX0();
629  int const height = img.getHeight();
630  int const width = img.getWidth();
631  /*
632  * Storage for arrays that identify objects by ID. We want to be able to
633  * refer to idp[-1] and idp[width], hence the (width + 2)
634  */
635  std::vector<int> id1(width + 2);
636  std::fill(id1.begin(), id1.end(), 0);
637  std::vector<int> id2(width + 2);
638  std::fill(id2.begin(), id2.end(), 0);
639  std::vector<int>::iterator idc = id1.begin() + 1; // object IDs in current/
640  std::vector<int>::iterator idp = id2.begin() + 1; // previous row
641 
642  std::vector<int> aliases; // aliases for initially disjoint parts of Footprints
643  aliases.reserve(1 + height / 20); // initial size of aliases
644 
645  std::vector<std::shared_ptr<IdSpan>> spans; // y:x0,x1 for objects
646  spans.reserve(aliases.capacity()); // initial size of spans
647 
648  aliases.push_back(0); // 0 --> 0
649  /*
650  * Go through image identifying objects
651  */
652  typedef typename image::Image<ImagePixelT>::x_iterator x_iterator;
653  typedef typename image::Image<VariancePixelT>::x_iterator x_var_iterator;
654 
655  in_span = 0; // not in a span
656  for (int y = 0; y != height; ++y) {
657  if (idc == id1.begin() + 1) {
658  idc = id2.begin() + 1;
659  idp = id1.begin() + 1;
660  } else {
661  idc = id1.begin() + 1;
662  idp = id2.begin() + 1;
663  }
664  std::fill_n(idc - 1, width + 2, 0);
665 
666  in_span = 0; /* not in a span */
667  bool good = (includeThresholdMultiplier == 1.0); /* Span exceeds the threshold? */
668 
669  x_iterator pixPtr = img.row_begin(y);
670  x_var_iterator varPtr = (var == NULL) ? NULL : var->row_begin(y);
671  for (int x = 0; x < width; ++x, ++pixPtr, varPtr = advancePtr(varPtr, ThresholdTraitT())) {
672  ImagePixelT const pixVal = *pixPtr;
673 
674  if (isBadPixel(pixVal) ||
675  !inFootprint(pixVal, varPtr, polarity, footprintThreshold, ThresholdTraitT())) {
676  if (in_span) {
677  auto sp = std::make_shared<IdSpan>(in_span, y, x0, x - 1, good);
678  spans.push_back(sp);
679 
680  in_span = 0;
681  good = false;
682  }
683  } else { /* a pixel to fix */
684  if (idc[x - 1] != 0) {
685  id = idc[x - 1];
686  } else if (idp[x - 1] != 0) {
687  id = idp[x - 1];
688  } else if (idp[x] != 0) {
689  id = idp[x];
690  } else if (idp[x + 1] != 0) {
691  id = idp[x + 1];
692  } else {
693  id = ++nobj;
694  aliases.push_back(id);
695  }
696 
697  idc[x] = id;
698  if (!in_span) {
699  x0 = x;
700  in_span = id;
701  }
702  /*
703  * Do we need to merge ID numbers? If so, make suitable entries in aliases[]
704  */
705  if (idp[x + 1] != 0 && idp[x + 1] != id) {
706  aliases[resolve_alias(aliases, idp[x + 1])] = resolve_alias(aliases, id);
707 
708  idc[x] = id = idp[x + 1];
709  }
710 
711  if (!good && inFootprint(pixVal, varPtr, polarity, includeThreshold, ThresholdTraitT())) {
712  good = true;
713  }
714  }
715  }
716 
717  if (in_span) {
718  auto sp = std::make_shared<IdSpan>(in_span, y, x0, width - 1, good);
719  spans.push_back(sp);
720  }
721  }
722  /*
723  * Resolve aliases; first alias chains, then the IDs in the spans
724  */
725  for (unsigned int i = 0; i < spans.size(); i++) {
726  spans[i]->id = resolve_alias(aliases, spans[i]->id);
727  }
728  /*
729  * Sort spans by ID, so we can sweep through them once
730  */
731  if (spans.size() > 0) {
732  std::sort(spans.begin(), spans.end(), IdSpanCompar());
733  }
734  /*
735  * Build Footprints from spans
736  */
737  unsigned int i0; // initial value of i
738  if (spans.size() > 0) {
739  id = spans[0]->id;
740  i0 = 0;
741  for (unsigned int i = 0; i <= spans.size(); i++) { // <= size to catch the last object
742  if (i == spans.size() || spans[i]->id != id) {
743  bool good = false; // Span includes pixel sufficient to include footprint in set?
744  std::vector<geom::Span> tempSpanList;
745  for (; i0 < i; i0++) {
746  good |= spans[i0]->good;
747  tempSpanList.push_back(
748  geom::Span(spans[i0]->y + row0, spans[i0]->x0 + col0, spans[i0]->x1 + col0));
749  }
750  auto tempSpanSet = std::make_shared<geom::SpanSet>(std::move(tempSpanList));
751  auto fp = std::make_shared<Footprint>(tempSpanSet, _region);
752 
753  if (good && fp->getArea() >= static_cast<std::size_t>(npixMin)) {
754  _footprints->push_back(fp);
755  }
756  }
757 
758  if (i < spans.size()) {
759  id = spans[i]->id;
760  }
761  }
762  }
763  /*
764  * Find all peaks within those Footprints
765  */
766  if (setPeaks) {
767  typedef FootprintSet::FootprintList::iterator fiterator;
768  for (fiterator ptr = _footprints->begin(), end = _footprints->end(); ptr != end; ++ptr) {
769  findPeaks(*ptr, img, polarity, ThresholdTraitT());
770  }
771  }
772 }
773 
774 template <typename ImagePixelT>
775 FootprintSet::FootprintSet(image::Image<ImagePixelT> const &img, Threshold const &threshold,
776  int const npixMin, bool const setPeaks)
777  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList()), _region(img.getBBox()) {
778  typedef float VariancePixelT;
779 
780  findFootprints<ImagePixelT, image::MaskPixel, VariancePixelT, ThresholdLevel_traits>(
781  _footprints.get(), _region, img, NULL, threshold.getValue(img), threshold.getIncludeMultiplier(),
782  threshold.getPolarity(), npixMin, setPeaks);
783 }
784 
785 // NOTE: not a template to appease swig (see note by instantiations at bottom)
786 
787 template <typename MaskPixelT>
788 FootprintSet::FootprintSet(image::Mask<MaskPixelT> const &msk, Threshold const &threshold, int const npixMin)
789  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList()), _region(msk.getBBox()) {
790  switch (threshold.getType()) {
791  case Threshold::BITMASK:
792  findFootprints<MaskPixelT, MaskPixelT, float, ThresholdBitmask_traits>(
793  _footprints.get(), _region, msk, NULL, threshold.getValue(),
794  threshold.getIncludeMultiplier(), threshold.getPolarity(), npixMin, false);
795  break;
796 
797  case Threshold::VALUE:
798  findFootprints<MaskPixelT, MaskPixelT, float, ThresholdLevel_traits>(
799  _footprints.get(), _region, msk, NULL, threshold.getValue(),
800  threshold.getIncludeMultiplier(), threshold.getPolarity(), npixMin, false);
801  break;
802 
803  default:
804  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
805  "You must specify a numerical threshold value with a Mask");
806  }
807 }
808 
809 template <typename ImagePixelT, typename MaskPixelT>
810 FootprintSet::FootprintSet(const image::MaskedImage<ImagePixelT, MaskPixelT> &maskedImg,
811  Threshold const &threshold, std::string const &planeName, int const npixMin,
812  bool const setPeaks)
813  : daf::base::Citizen(typeid(this)),
814  _footprints(new FootprintList()),
815  _region(geom::Point2I(maskedImg.getX0(), maskedImg.getY0()),
816  geom::Extent2I(maskedImg.getWidth(), maskedImg.getHeight())) {
817  typedef typename image::MaskedImage<ImagePixelT, MaskPixelT>::Variance::Pixel VariancePixelT;
818  // Find the Footprints
819  switch (threshold.getType()) {
821  findFootprints<ImagePixelT, MaskPixelT, VariancePixelT, ThresholdPixelLevel_traits>(
822  _footprints.get(), _region, *maskedImg.getImage(), maskedImg.getVariance().get(),
823  threshold.getValue(maskedImg), threshold.getIncludeMultiplier(), threshold.getPolarity(),
824  npixMin, setPeaks);
825  break;
826  default:
827  findFootprints<ImagePixelT, MaskPixelT, VariancePixelT, ThresholdLevel_traits>(
828  _footprints.get(), _region, *maskedImg.getImage(), maskedImg.getVariance().get(),
829  threshold.getValue(maskedImg), threshold.getIncludeMultiplier(), threshold.getPolarity(),
830  npixMin, setPeaks);
831  break;
832  }
833  // Set Mask if requested
834  if (planeName == "") {
835  return;
836  }
837  //
838  // Define the maskPlane
839  //
840  const std::shared_ptr<image::Mask<MaskPixelT>> mask = maskedImg.getMask();
841  mask->addMaskPlane(planeName);
842 
843  MaskPixelT const bitPlane = mask->getPlaneBitMask(planeName);
844  //
845  // Set the bits where objects are detected
846  //
847  for (auto const &fIter : *_footprints) {
848  fIter->getSpans()->setMask(*(maskedImg.getMask()), bitPlane);
849  }
850 }
851 
852 namespace {
854 /*
855  * A data structure to hold the starting point for a search for pixels above threshold,
856  * used by pmFindFootprintAtPoint
857  *
858  * We don't want to find this span again --- it's already part of the footprint ---
859  * so we set appropriate mask bits
860  */
861 //
862 // An enum for what we should do with a Startspan
863 //
864 enum DIRECTION {
865  DOWN = 0, // scan down from this span
866  UP, // scan up from this span
867  RESTART, // restart scanning from this span
868  DONE // this span is processed
869 };
870 //
871 // A Class that remembers how to [re-]start scanning the image for pixels
872 //
873 template <typename MaskPixelT>
874 class Startspan {
875 public:
876  Startspan(geom::Span const *span, image::Mask<MaskPixelT> *mask, DIRECTION const dir);
877  ~Startspan() { delete _span; }
878 
879  bool getSpan() { return _span; }
880  bool Stop() { return _stop; }
881  DIRECTION getDirection() { return _direction; }
882 
883  static int detectedPlane; // The MaskPlane to use for detected pixels
884  static int stopPlane; // The MaskPlane to use for pixels that signal us to stop searching
885 private:
886  std::shared_ptr<geom::Span const> _span; // The initial Span
887  DIRECTION _direction; // How to continue searching for further pixels
888  bool _stop; // should we stop searching?
889 };
890 
891 template <typename MaskPixelT>
892 Startspan<MaskPixelT>::Startspan(
893  geom::Span const *span, // The span in question
894  image::Mask<MaskPixelT> *mask, // Pixels that we've already detected
895  DIRECTION const dir // Should we continue searching towards the top of the image?
896  )
897  : _span(span), _direction(dir), _stop(false) {
898  if (mask != NULL) { // remember that we've detected these pixels
899  mask->setMaskPlaneValues(detectedPlane, span->getX0(), span->getX1(), span->getY());
900 
901  int const y = span->getY() - mask->getY0();
902  for (int x = span->getX0() - mask->getX0(); x <= span->getX1() - mask->getX0(); x++) {
903  if (mask(x, y, stopPlane)) {
904  _stop = true;
905  break;
906  }
907  }
908  }
909 }
910 
911 template <typename ImagePixelT, typename MaskPixelT>
912 class StartspanSet {
913 public:
915  : _image(image->getImage()), _mask(image->getMask()) {}
916  ~StartspanSet() {}
917 
918  bool add(geom::Span *span, DIRECTION const dir, bool addToMask = true);
919  bool process(Footprint *fp, // the footprint that we're building
920  Threshold const &threshold, // Threshold
921  double const param = -1); // parameter that Threshold may need
922 private:
923  image::Image<ImagePixelT> const *_image; // the Image we're searching
924  image::Mask<MaskPixelT> *_mask; // the mask that tells us where we've got to
925  std::vector<std::shared_ptr<Startspan<MaskPixelT>>> _spans; // list of Startspans
926 };
927 
928 //
929 // Add a new Startspan to a StartspansSet. Iff we see a stop bit, return true
930 //
931 template <typename ImagePixelT, typename MaskPixelT>
932 bool StartspanSet<ImagePixelT, MaskPixelT>::add(geom::Span *span, // the span in question
933  DIRECTION const dir, // the desired direction to search
934  bool addToMask) { // should I add the Span to the mask?
935  if (dir == RESTART) {
936  if (add(span, UP) || add(span, DOWN, false)) {
937  return true;
938  }
939  } else {
940  auto sspan = std::make_shared<MaskPixelT>(span, dir);
941  if (sspan->stop()) { // we detected a stop bit
942  return true;
943  } else {
944  _spans.push_back(sspan);
945  }
946  }
947 
948  return false;
949 }
950 
951 /*
952  * Search the image for pixels above threshold, starting at a single Startspan.
953  * We search the array looking for one to process; it'd be better to move the
954  * ones that we're done with to the end, but it probably isn't worth it for
955  * the anticipated uses of this routine.
956  *
957  * This is the guts of pmFindFootprintAtPoint
958  */
959 template <typename ImagePixelT, typename MaskPixelT>
960 bool StartspanSet<ImagePixelT, MaskPixelT>::process(Footprint *fp, // the footprint that we're building
961  Threshold const &threshold, // Threshold
962  double const param // parameter that Threshold may need
963  ) {
964  int const row0 = _image->getY0();
965  int const col0 = _image->getOffsetCols();
966  int const height = _image->getHeight();
967 
968  Startspan<MaskPixelT> *sspan = NULL;
969  for (auto iter = _spans.begin(); iter != _spans.end(); iter++) {
970  *sspan = *iter;
971  if (sspan->getDirection() != DONE) {
972  break;
973  }
974  if (sspan->Stop()) {
975  break;
976  }
977  }
978  if (sspan == NULL || sspan->getDirection() == DONE) { // no more Startspans to process
979  return false;
980  }
981  if (sspan->Stop()) { // they don't want any more spans processed
982  return false;
983  }
984  /*
985  * Work
986  */
987  DIRECTION const dir = sspan->getDirection();
988  /*
989  * Set initial span to the startspan
990  */
991  int x0 = sspan->getSpan()->getX0() - col0;
992  /*
993  * Go through image identifying objects
994  */
995  int nx0 = -1; // new value of x0
996  int const di = (dir == UP) ? 1 : -1; // how much i changes to get to the next row
997  bool stop = false; // should I stop searching for spans?
998 
999  typedef typename image::Image<ImagePixelT>::pixel_accessor pixAccessT;
1000  double const thresholdVal = threshold.getValue(param);
1001  bool const polarity = threshold.getPolarity();
1002 
1003  for (int i = sspan->span->y - row0 + di; i < height && i >= 0; i += di) {
1004  pixAccessT imgRow = _image->origin().advance(0, i); // row pointer
1005  // maskPixAccessT maskRow = _mask->origin.advance(0, i); // masks's row pointer
1006  //
1007  // Search left from the pixel diagonally to the left of (i - di, x0). If there's
1008  // a connected span there it may need to grow up and/or down, so push it onto
1009  // the stack for later consideration
1010  //
1011  nx0 = -1;
1012  for (int j = x0 - 1; j >= -1; j--) {
1013  ImagePixelT pixVal = (j < 0) ? thresholdVal - 100 : (polarity ? imgRow[j] : -imgRow[j]);
1014  if (_mask(j, i, Startspan<MaskPixelT>::detectedPlane) || pixVal < threshold) {
1015  if (j < x0 - 1) { // we found some pixels above threshold
1016  nx0 = j + 1;
1017  }
1018  break;
1019  }
1020  }
1021 #if 0
1022  if (nx0 < 0) { // no span to the left
1023  nx1 = x0 - 1; // we're going to resume searching at nx1 + 1
1024  } else {
1025  //
1026  // Search right in leftmost span
1027  //
1028  //nx1 = 0; // make gcc happy
1029  for (int j = nx0 + 1; j <= width; j++) {
1030  ImagePixelT pixVal = (j >= width) ? threshold - 100 :
1031  (polarity ? (F32 ? imgRowF32[j] : imgRowS32[j]) :
1032  (F32 ? -imgRowF32[j] : -imgRowS32[j]));
1033  if ((maskRow[j] & DETECTED) || pixVal < threshold) {
1034  nx1 = j - 1;
1035  break;
1036  }
1037  }
1038 
1039  pmSpan const *sp = pmFootprintAddSpan(fp, i + row0, nx0 + col0, nx1 + col0);
1040 
1041  if (add_startspan(startspans, sp, mask, RESTART)) {
1042  stop = true;
1043  break;
1044  }
1045  }
1046  //
1047  // Now look for spans connected to the old span. The first of these we'll
1048  // simply process, but others will have to be deferred for later consideration.
1049  //
1050  // In fact, if the span overhangs to the right we'll have to defer the overhang
1051  // until later too, as it too can grow in both directions
1052  //
1053  // Note that column width exists virtually, and always ends the last span; this
1054  // is why we claim below that sx1 is always set
1055  //
1056  bool first = false; // is this the first new span detected?
1057  for (int j = nx1 + 1; j <= x1 + 1; j++) {
1058  ImagePixelT pixVal = (j >= width) ? threshold - 100 :
1059  (polarity ? (F32 ? imgRowF32[j] : imgRowS32[j]) : (F32 ? -imgRowF32[j] : -imgRowS32[j]));
1060  if (!(maskRow[j] & DETECTED) && pixVal >= threshold) {
1061  int sx0 = j++; // span that we're working on is sx0:sx1
1062  int sx1 = -1; // We know that if we got here, we'll also set sx1
1063  for (; j <= width; j++) {
1064  ImagePixelT pixVal = (j >= width) ? threshold - 100 :
1065  (polarity ? (F32 ? imgRowF32[j] : imgRowS32[j]) :
1066  (F32 ? -imgRowF32[j] : -imgRowS32[j]));
1067  if ((maskRow[j] & DETECTED) || pixVal < threshold) { // end of span
1068  sx1 = j;
1069  break;
1070  }
1071  }
1072  assert (sx1 >= 0);
1073 
1074  pmSpan const *sp;
1075  if (first) {
1076  if (sx1 <= x1) {
1077  sp = pmFootprintAddSpan(fp, i + row0, sx0 + col0, sx1 + col0 - 1);
1078  if (add_startspan(startspans, sp, mask, DONE)) {
1079  stop = true;
1080  break;
1081  }
1082  } else { // overhangs to right
1083  sp = pmFootprintAddSpan(fp, i + row0, sx0 + col0, x1 + col0);
1084  if (add_startspan(startspans, sp, mask, DONE)) {
1085  stop = true;
1086  break;
1087  }
1088  sp = pmFootprintAddSpan(fp, i + row0, x1 + 1 + col0, sx1 + col0 - 1);
1089  if (add_startspan(startspans, sp, mask, RESTART)) {
1090  stop = true;
1091  break;
1092  }
1093  }
1094  first = false;
1095  } else {
1096  sp = pmFootprintAddSpan(fp, i + row0, sx0 + col0, sx1 + col0 - 1);
1097  if (add_startspan(startspans, sp, mask, RESTART)) {
1098  stop = true;
1099  break;
1100  }
1101  }
1102  }
1103  }
1104 
1105  if (stop || first == false) { // we're done
1106  break;
1107  }
1108 
1109  x0 = nx0;
1110  x1 = nx1;
1111 #endif
1112  }
1113  /*
1114  * Cleanup
1115  */
1116 
1117  sspan->_direction = DONE;
1118  return stop ? false : true;
1119 }
1121 }
1122 #if 0
1123 
1124 
1125 /*
1126  * Go through an image, starting at (row, col) and assembling all the pixels
1127  * that are connected to that point (in a chess kings-move sort of way) into
1128  * a pmFootprint.
1129  *
1130  * This is much slower than pmFindFootprints if you want to find lots of
1131  * footprints, but if you only want a small region about a given point it
1132  * can be much faster
1133  *
1134  * N.b. The returned pmFootprint is not in "normal form"; that is the pmSpans
1135  * are not sorted by increasing y, x0, x1. If this matters to you, call
1136  * pmFootprintNormalize()
1137  */
1138 pmFootprint *
1139 pmFindFootprintAtPoint(psImage const *img, // image to search
1140  Threshold const &threshold, // Threshold
1141  psArray const *peaks, // array of peaks; finding one terminates search for footprint
1142  int row, int col) { // starting position (in img's parent's coordinate system)
1143  assert(img != NULL);
1144 
1145  bool F32 = false; // is this an F32 image?
1146  if (img->type.type == PS_TYPE_F32) {
1147  F32 = true;
1148  } else if (img->type.type == PS_TYPE_S32) {
1149  F32 = false;
1150  } else { // N.b. You can't trivially add more cases here; F32 is just a bool
1151  psError(PS_ERR_UNKNOWN, true, "Unsupported psImage type: %d", img->type.type);
1152  return NULL;
1153  }
1154  psF32 *imgRowF32 = NULL; // row pointer if F32
1155  psS32 *imgRowS32 = NULL; // " " " " !F32
1156 
1157  int const row0 = img->row0;
1158  int const col0 = img->col0;
1159  int const height = img->getHeight();
1160  int const width = img->getWidth();
1161 /*
1162  * Is point in image, and above threshold?
1163  */
1164  row -= row0;
1165  col -= col0;
1166  if (row < 0 || row >= height ||
1167  col < 0 || col >= width) {
1168  psError(PS_ERR_BAD_PARAMETER_VALUE, true,
1169  "row/col == (%d, %d) are out of bounds [%d--%d, %d--%d]",
1170  row + row0, col + col0, row0, row0 + height - 1, col0, col0 + width - 1);
1171  return NULL;
1172  }
1173 
1174  ImagePixelT pixVal = F32 ? img->data.F32[row][col] : img->data.S32[row][col];
1175  if (pixVal < threshold) {
1176  return pmFootprintAlloc(0, img);
1177  }
1178 
1179  pmFootprint *fp = pmFootprintAlloc(1 + img->getHeight()/10, img);
1180 /*
1181  * We need a mask for two purposes; to indicate which pixels are already detected,
1182  * and to store the "stop" pixels --- those that, once reached, should stop us
1183  * looking for the rest of the pmFootprint. These are generally set from peaks.
1184  */
1185  psImage *mask = psImageAlloc(width, height, PS_TYPE_MASK);
1186  P_PSIMAGE_SET_ROW0(mask, row0);
1187  P_PSIMAGE_SET_COL0(mask, col0);
1188  psImageInit(mask, INITIAL);
1189  //
1190  // Set stop bits from peaks list
1191  //
1192  assert (peaks == NULL || peaks->n == 0 || pmIsPeak(peaks->data[0]));
1193  if (peaks != NULL) {
1194  for (int i = 0; i < peaks->n; i++) {
1195  pmPeak *peak = peaks->data[i];
1196  mask->data.PS_TYPE_MASK_DATA[peak->y - mask->row0][peak->x - mask->col0] |= STOP;
1197  }
1198  }
1199 /*
1200  * Find starting span passing through (row, col)
1201  */
1202  psArray *startspans = psArrayAllocEmpty(1); // spans where we have to restart the search
1203 
1204  imgRowF32 = img->data.F32[row]; // only one of
1205  imgRowS32 = img->data.S32[row]; // these is valid!
1206  psMaskType *maskRow = mask->data.PS_TYPE_MASK_DATA[row];
1207  {
1208  int i;
1209  for (i = col; i >= 0; i--) {
1210  pixVal = F32 ? imgRowF32[i] : imgRowS32[i];
1211  if ((maskRow[i] & DETECTED) || pixVal < threshold) {
1212  break;
1213  }
1214  }
1215  int i0 = i;
1216  for (i = col; i < width; i++) {
1217  pixVal = F32 ? imgRowF32[i] : imgRowS32[i];
1218  if ((maskRow[i] & DETECTED) || pixVal < threshold) {
1219  break;
1220  }
1221  }
1222  int i1 = i;
1223  pmSpan const *sp = pmFootprintAddSpan(fp, row + row0, i0 + col0 + 1, i1 + col0 - 1);
1224 
1225  (void)add_startspan(startspans, sp, mask, RESTART);
1226  }
1227  /*
1228  * Now workout from those Startspans, searching for pixels above threshold
1229  */
1230  while (do_startspan(fp, img, mask, threshold, startspans)) continue;
1231  /*
1232  * Cleanup
1233  */
1234  psFree(mask);
1235  psFree(startspans); // restores the image pixel
1236 
1237  return fp; // pmFootprint really
1238 }
1239 #endif
1240 
1241 FootprintSet::FootprintSet(geom::Box2I region)
1242  : daf::base::Citizen(typeid(this)), _footprints(std::make_shared<FootprintList>()), _region(region) {}
1243 
1244 FootprintSet::FootprintSet(FootprintSet const &rhs)
1245  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList), _region(rhs._region) {
1246  _footprints->reserve(rhs._footprints->size());
1247  for (FootprintSet::FootprintList::const_iterator ptr = rhs._footprints->begin(),
1248  end = rhs._footprints->end();
1249  ptr != end; ++ptr) {
1250  _footprints->push_back(std::make_shared<Footprint>(**ptr));
1251  }
1252 }
1253 
1254 FootprintSet &FootprintSet::operator=(FootprintSet const &rhs) {
1255  FootprintSet tmp(rhs);
1256  swap(tmp); // See Meyers, Effective C++, Item 11
1257  return *this;
1258 }
1259 
1260 void FootprintSet::merge(FootprintSet const &rhs, int tGrow, int rGrow, bool isotropic) {
1261  FootprintControl const ctrl(true, isotropic);
1262  FootprintSet fs = mergeFootprintSets(*this, tGrow, rhs, rGrow, ctrl);
1263  swap(fs); // Swap the new FootprintSet into place
1264 }
1265 
1266 void FootprintSet::setRegion(geom::Box2I const &region) {
1267  _region = region;
1268 
1269  for (FootprintSet::FootprintList::iterator ptr = _footprints->begin(), end = _footprints->end();
1270  ptr != end; ++ptr) {
1271  (*ptr)->setRegion(region);
1272  }
1273 }
1274 
1275 FootprintSet::FootprintSet(FootprintSet const &rhs, int r, bool isotropic)
1276  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList), _region(rhs._region) {
1277  if (r == 0) {
1278  FootprintSet fs = rhs;
1279  swap(fs); // Swap the new FootprintSet into place
1280  return;
1281  } else if (r < 0) {
1282  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
1283  (boost::format("I cannot grow by negative numbers: %d") % r).str());
1284  }
1285 
1286  FootprintControl const ctrl(true, isotropic);
1287  FootprintSet fs = mergeFootprintSets(FootprintSet(rhs.getRegion()), 0, rhs, r, ctrl);
1288  swap(fs); // Swap the new FootprintSet into place
1289 }
1290 
1291 FootprintSet::FootprintSet(FootprintSet const &rhs, int ngrow, FootprintControl const &ctrl)
1292  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList), _region(rhs._region) {
1293  if (ngrow == 0) {
1294  FootprintSet fs = rhs;
1295  swap(fs); // Swap the new FootprintSet into place
1296  return;
1297  } else if (ngrow < 0) {
1298  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
1299  str(boost::format("I cannot grow by negative numbers: %d") % ngrow));
1300  }
1301 
1302  FootprintSet fs = mergeFootprintSets(FootprintSet(rhs.getRegion()), 0, rhs, ngrow, ctrl);
1303  swap(fs); // Swap the new FootprintSet into place
1304 }
1305 
1306 FootprintSet::FootprintSet(FootprintSet const &fs1, FootprintSet const &fs2, bool const)
1307  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList()), _region(fs1._region) {
1308  _region.include(fs2._region);
1309  throw LSST_EXCEPT(pex::exceptions::LogicError, "NOT IMPLEMENTED");
1310 }
1311 
1312 std::shared_ptr<image::Image<FootprintIdPixel>> FootprintSet::insertIntoImage(bool const relativeIDs) const {
1313  auto im = std::make_shared<image::Image<FootprintIdPixel>>(_region);
1314  *im = 0;
1315 
1316  FootprintIdPixel id = 0;
1317  for (auto const &fIter : *_footprints) {
1318  if (relativeIDs) {
1319  id++;
1320  } else {
1321  id = fIter->getId();
1322  }
1323 
1324  fIter->getSpans()->applyFunctor(setIdImage<FootprintIdPixel>(id), *im);
1325  }
1326 
1327  return im;
1328 }
1329 
1330 template <typename ImagePixelT, typename MaskPixelT>
1331 void FootprintSet::makeHeavy(image::MaskedImage<ImagePixelT, MaskPixelT> const &mimg,
1332  HeavyFootprintCtrl const *ctrl) {
1333  HeavyFootprintCtrl ctrl_s = HeavyFootprintCtrl();
1334 
1335  if (!ctrl) {
1336  ctrl = &ctrl_s;
1337  }
1338 
1339  for (FootprintList::iterator ptr = _footprints->begin(), end = _footprints->end(); ptr != end; ++ptr) {
1340  ptr->reset(new HeavyFootprint<ImagePixelT, MaskPixelT>(**ptr, mimg, ctrl));
1341  }
1342 }
1343 
1344 void FootprintSet::makeSources(afw::table::SourceCatalog &cat) const {
1345  for (FootprintList::const_iterator i = _footprints->begin(); i != _footprints->end(); ++i) {
1346  std::shared_ptr<afw::table::SourceRecord> r = cat.addNew();
1347  r->setFootprint(*i);
1348  }
1349 }
1350 
1351 //
1352 // Explicit instantiations
1353 //
1354 
1355 #ifndef DOXYGEN
1356 
1357 #define INSTANTIATE(PIXEL) \
1358  template FootprintSet::FootprintSet(image::Image<PIXEL> const &, Threshold const &, int const, \
1359  bool const); \
1360  template FootprintSet::FootprintSet(image::MaskedImage<PIXEL, image::MaskPixel> const &, \
1361  Threshold const &, std::string const &, int const, bool const); \
1362  template void FootprintSet::makeHeavy(image::MaskedImage<PIXEL, image::MaskPixel> const &, \
1363  HeavyFootprintCtrl const *)
1364 
1365 template FootprintSet::FootprintSet(image::Mask<image::MaskPixel> const &, Threshold const &, int const);
1366 
1367 template void FootprintSet::setMask(image::Mask<image::MaskPixel> *, std::string const &);
1368 template void FootprintSet::setMask(std::shared_ptr<image::Mask<image::MaskPixel>>, std::string const &);
1369 
1370 INSTANTIATE(std::uint16_t);
1371 INSTANTIATE(int);
1372 INSTANTIATE(float);
1373 INSTANTIATE(double);
1374 }
1375 }
1376 } // end lsst::afw::detection
1377 
1378 #endif // !DOXYGEN
iterator begin() const
Return an STL compliant iterator to the start of the image.
Definition: Image.cc:250
void swap(ImageBase< PixelT > &a, ImageBase< PixelT > &b)
Definition: Image.cc:227
std::vector< std::shared_ptr< Footprint > > FootprintList
The FootprintSet&#39;s set of Footprints.
Definition: FootprintSet.h:56
VariancePtr getVariance() const
Return a (shared_ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:993
#define INSTANTIATE(TYPE)
Use (pixels &amp; (given mask))
Definition: Threshold.h:48
Extent< int, 2 > Extent2I
Definition: Extent.h:341
ImagePtr getImage() const
Return a (shared_ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:960
The base class for all image classed (Image, Mask, MaskedImage, ...)
Definition: Image.h:116
size_type size() const
Return the number of elements in the catalog.
Definition: Catalog.h:399
int getX0() const
Return the image&#39;s column-origin.
Definition: Image.h:317
MaskPtr getMask() const
Return a (shared_ptr to) the MaskedImage&#39;s mask.
Definition: MaskedImage.h:972
FootprintSet(image::Image< ImagePixelT > const &img, Threshold const &threshold, int const npixMin=1, bool const setPeaks=true)
Find a FootprintSet given an Image and a threshold.
Bounds _x
afw::table::CatalogT< PeakRecord > PeakCatalog
Definition: Peak.h:223
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:83
A class to manipulate images, masks, and variance as a single object.
Definition: MaskedImage.h:81
void setMaskPlaneValues(const int plane, const int x0, const int x1, const int y)
Set the bit specified by &quot;planeId&quot; for pixels (x0, y) ...
Definition: Mask.cc:867
int max
Definition: BoundedField.cc:99
int getHeight() const
Return the number of rows in the image.
Definition: Image.h:309
double x
details::ImageNdGetter< T, inA, inB > ndImage(ndarray::Array< T, inA, inB > const &array, afwGeom::Point2I xy0=afwGeom::Point2I())
Marks a ndarray to be interpreted as an image when applying a functor from a SpanSet.
int _id
Definition: Mask.cc:547
afw::table::Key< afw::table::Array< MaskPixelT > > mask
Bounds _y
SortedCatalogT< SourceRecord > SourceCatalog
Definition: fwd.h:85
lsst::afw::detection::Footprint Footprint
Definition: Source.h:60
afw::table::Key< afw::table::Array< ImagePixelT > > image
x_iterator row_begin(int y) const
Return an x_iterator to the start of the y&#39;th row.
Definition: Image.h:412
Point< int, 2 > Point2I
Definition: Point.h:270
Use number of sigma given per-pixel s.d.
Definition: Threshold.h:51
geom::Box2I const * _region
int getWidth() const
Return the number of columns in the image.
Definition: Image.h:307
A class to represent a 2-dimensional array of pixels.
Definition: Image.h:486
int end
std::uint64_t FootprintIdPixel
Pixel type for FootprintSet::insertIntoImage()
Definition: FootprintSet.h:48
int getY0() const
Return the image&#39;s row-origin.
Definition: Image.h:325