lsst.afw  13.0-39-g3deb52d
 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  typedef typename image::Image<ImagePixelT> ImageT;
626  double includeThreshold = footprintThreshold * includeThresholdMultiplier; // Threshold for inclusion
627 
628  int const row0 = img.getY0();
629  int const col0 = img.getX0();
630  int const height = img.getHeight();
631  int const width = img.getWidth();
632  /*
633  * Storage for arrays that identify objects by ID. We want to be able to
634  * refer to idp[-1] and idp[width], hence the (width + 2)
635  */
636  std::vector<int> id1(width + 2);
637  std::fill(id1.begin(), id1.end(), 0);
638  std::vector<int> id2(width + 2);
639  std::fill(id2.begin(), id2.end(), 0);
640  std::vector<int>::iterator idc = id1.begin() + 1; // object IDs in current/
641  std::vector<int>::iterator idp = id2.begin() + 1; // previous row
642 
643  std::vector<int> aliases; // aliases for initially disjoint parts of Footprints
644  aliases.reserve(1 + height / 20); // initial size of aliases
645 
646  std::vector<std::shared_ptr<IdSpan>> spans; // y:x0,x1 for objects
647  spans.reserve(aliases.capacity()); // initial size of spans
648 
649  aliases.push_back(0); // 0 --> 0
650  /*
651  * Go through image identifying objects
652  */
653  typedef typename image::Image<ImagePixelT>::x_iterator x_iterator;
654  typedef typename image::Image<VariancePixelT>::x_iterator x_var_iterator;
655 
656  in_span = 0; // not in a span
657  for (int y = 0; y != height; ++y) {
658  if (idc == id1.begin() + 1) {
659  idc = id2.begin() + 1;
660  idp = id1.begin() + 1;
661  } else {
662  idc = id1.begin() + 1;
663  idp = id2.begin() + 1;
664  }
665  std::fill_n(idc - 1, width + 2, 0);
666 
667  in_span = 0; /* not in a span */
668  bool good = (includeThresholdMultiplier == 1.0); /* Span exceeds the threshold? */
669 
670  x_iterator pixPtr = img.row_begin(y);
671  x_var_iterator varPtr = (var == NULL) ? NULL : var->row_begin(y);
672  for (int x = 0; x < width; ++x, ++pixPtr, varPtr = advancePtr(varPtr, ThresholdTraitT())) {
673  ImagePixelT const pixVal = *pixPtr;
674 
675  if (isBadPixel(pixVal) ||
676  !inFootprint(pixVal, varPtr, polarity, footprintThreshold, ThresholdTraitT())) {
677  if (in_span) {
678  auto sp = std::make_shared<IdSpan>(in_span, y, x0, x - 1, good);
679  spans.push_back(sp);
680 
681  in_span = 0;
682  good = false;
683  }
684  } else { /* a pixel to fix */
685  if (idc[x - 1] != 0) {
686  id = idc[x - 1];
687  } else if (idp[x - 1] != 0) {
688  id = idp[x - 1];
689  } else if (idp[x] != 0) {
690  id = idp[x];
691  } else if (idp[x + 1] != 0) {
692  id = idp[x + 1];
693  } else {
694  id = ++nobj;
695  aliases.push_back(id);
696  }
697 
698  idc[x] = id;
699  if (!in_span) {
700  x0 = x;
701  in_span = id;
702  }
703  /*
704  * Do we need to merge ID numbers? If so, make suitable entries in aliases[]
705  */
706  if (idp[x + 1] != 0 && idp[x + 1] != id) {
707  aliases[resolve_alias(aliases, idp[x + 1])] = resolve_alias(aliases, id);
708 
709  idc[x] = id = idp[x + 1];
710  }
711 
712  if (!good && inFootprint(pixVal, varPtr, polarity, includeThreshold, ThresholdTraitT())) {
713  good = true;
714  }
715  }
716  }
717 
718  if (in_span) {
719  auto sp = std::make_shared<IdSpan>(in_span, y, x0, width - 1, good);
720  spans.push_back(sp);
721  }
722  }
723  /*
724  * Resolve aliases; first alias chains, then the IDs in the spans
725  */
726  for (unsigned int i = 0; i < spans.size(); i++) {
727  spans[i]->id = resolve_alias(aliases, spans[i]->id);
728  }
729  /*
730  * Sort spans by ID, so we can sweep through them once
731  */
732  if (spans.size() > 0) {
733  std::sort(spans.begin(), spans.end(), IdSpanCompar());
734  }
735  /*
736  * Build Footprints from spans
737  */
738  unsigned int i0; // initial value of i
739  if (spans.size() > 0) {
740  id = spans[0]->id;
741  i0 = 0;
742  for (unsigned int i = 0; i <= spans.size(); i++) { // <= size to catch the last object
743  if (i == spans.size() || spans[i]->id != id) {
744  bool good = false; // Span includes pixel sufficient to include footprint in set?
745  std::vector<geom::Span> tempSpanList;
746  for (; i0 < i; i0++) {
747  good |= spans[i0]->good;
748  tempSpanList.push_back(
749  geom::Span(spans[i0]->y + row0, spans[i0]->x0 + col0, spans[i0]->x1 + col0));
750  }
751  auto tempSpanSet = std::make_shared<geom::SpanSet>(std::move(tempSpanList));
752  auto fp = std::make_shared<Footprint>(tempSpanSet, _region);
753 
754  if (good && fp->getArea() >= static_cast<std::size_t>(npixMin)) {
755  _footprints->push_back(fp);
756  }
757  }
758 
759  if (i < spans.size()) {
760  id = spans[i]->id;
761  }
762  }
763  }
764  /*
765  * Find all peaks within those Footprints
766  */
767  if (setPeaks) {
768  typedef FootprintSet::FootprintList::iterator fiterator;
769  for (fiterator ptr = _footprints->begin(), end = _footprints->end(); ptr != end; ++ptr) {
770  findPeaks(*ptr, img, polarity, ThresholdTraitT());
771  }
772  }
773 }
774 
775 template <typename ImagePixelT>
776 FootprintSet::FootprintSet(image::Image<ImagePixelT> const &img, Threshold const &threshold,
777  int const npixMin, bool const setPeaks)
778  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList()), _region(img.getBBox()) {
779  typedef float VariancePixelT;
780 
781  findFootprints<ImagePixelT, image::MaskPixel, VariancePixelT, ThresholdLevel_traits>(
782  _footprints.get(), _region, img, NULL, threshold.getValue(img), threshold.getIncludeMultiplier(),
783  threshold.getPolarity(), npixMin, setPeaks);
784 }
785 
786 // NOTE: not a template to appease swig (see note by instantiations at bottom)
787 
788 template <typename MaskPixelT>
789 FootprintSet::FootprintSet(image::Mask<MaskPixelT> const &msk, Threshold const &threshold, int const npixMin)
790  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList()), _region(msk.getBBox()) {
791  switch (threshold.getType()) {
792  case Threshold::BITMASK:
793  findFootprints<MaskPixelT, MaskPixelT, float, ThresholdBitmask_traits>(
794  _footprints.get(), _region, msk, NULL, threshold.getValue(),
795  threshold.getIncludeMultiplier(), threshold.getPolarity(), npixMin, false);
796  break;
797 
798  case Threshold::VALUE:
799  findFootprints<MaskPixelT, MaskPixelT, float, ThresholdLevel_traits>(
800  _footprints.get(), _region, msk, NULL, threshold.getValue(),
801  threshold.getIncludeMultiplier(), threshold.getPolarity(), npixMin, false);
802  break;
803 
804  default:
805  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
806  "You must specify a numerical threshold value with a Mask");
807  }
808 }
809 
810 template <typename ImagePixelT, typename MaskPixelT>
811 FootprintSet::FootprintSet(const image::MaskedImage<ImagePixelT, MaskPixelT> &maskedImg,
812  Threshold const &threshold, std::string const &planeName, int const npixMin,
813  bool const setPeaks)
814  : daf::base::Citizen(typeid(this)),
815  _footprints(new FootprintList()),
816  _region(geom::Point2I(maskedImg.getX0(), maskedImg.getY0()),
817  geom::Extent2I(maskedImg.getWidth(), maskedImg.getHeight())) {
818  typedef typename image::MaskedImage<ImagePixelT, MaskPixelT>::Variance::Pixel VariancePixelT;
819  // Find the Footprints
820  switch (threshold.getType()) {
822  findFootprints<ImagePixelT, MaskPixelT, VariancePixelT, ThresholdPixelLevel_traits>(
823  _footprints.get(), _region, *maskedImg.getImage(), maskedImg.getVariance().get(),
824  threshold.getValue(maskedImg), threshold.getIncludeMultiplier(), threshold.getPolarity(),
825  npixMin, setPeaks);
826  break;
827  default:
828  findFootprints<ImagePixelT, MaskPixelT, VariancePixelT, ThresholdLevel_traits>(
829  _footprints.get(), _region, *maskedImg.getImage(), maskedImg.getVariance().get(),
830  threshold.getValue(maskedImg), threshold.getIncludeMultiplier(), threshold.getPolarity(),
831  npixMin, setPeaks);
832  break;
833  }
834  // Set Mask if requested
835  if (planeName == "") {
836  return;
837  }
838  //
839  // Define the maskPlane
840  //
841  const std::shared_ptr<image::Mask<MaskPixelT>> mask = maskedImg.getMask();
842  mask->addMaskPlane(planeName);
843 
844  MaskPixelT const bitPlane = mask->getPlaneBitMask(planeName);
845  //
846  // Set the bits where objects are detected
847  //
848  for (auto const &fIter : *_footprints) {
849  fIter->getSpans()->setMask(*(maskedImg.getMask()), bitPlane);
850  }
851 }
852 
853 namespace {
855 /*
856  * A data structure to hold the starting point for a search for pixels above threshold,
857  * used by pmFindFootprintAtPoint
858  *
859  * We don't want to find this span again --- it's already part of the footprint ---
860  * so we set appropriate mask bits
861  */
862 //
863 // An enum for what we should do with a Startspan
864 //
865 enum DIRECTION {
866  DOWN = 0, // scan down from this span
867  UP, // scan up from this span
868  RESTART, // restart scanning from this span
869  DONE // this span is processed
870 };
871 //
872 // A Class that remembers how to [re-]start scanning the image for pixels
873 //
874 template <typename MaskPixelT>
875 class Startspan {
876 public:
877  Startspan(geom::Span const *span, image::Mask<MaskPixelT> *mask, DIRECTION const dir);
878  ~Startspan() { delete _span; }
879 
880  bool getSpan() { return _span; }
881  bool Stop() { return _stop; }
882  DIRECTION getDirection() { return _direction; }
883 
884  static int detectedPlane; // The MaskPlane to use for detected pixels
885  static int stopPlane; // The MaskPlane to use for pixels that signal us to stop searching
886 private:
887  std::shared_ptr<geom::Span const> _span; // The initial Span
888  DIRECTION _direction; // How to continue searching for further pixels
889  bool _stop; // should we stop searching?
890 };
891 
892 template <typename MaskPixelT>
893 Startspan<MaskPixelT>::Startspan(
894  geom::Span const *span, // The span in question
895  image::Mask<MaskPixelT> *mask, // Pixels that we've already detected
896  DIRECTION const dir // Should we continue searching towards the top of the image?
897  )
898  : _span(span), _direction(dir), _stop(false) {
899  if (mask != NULL) { // remember that we've detected these pixels
900  mask->setMaskPlaneValues(detectedPlane, span->getX0(), span->getX1(), span->getY());
901 
902  int const y = span->getY() - mask->getY0();
903  for (int x = span->getX0() - mask->getX0(); x <= span->getX1() - mask->getX0(); x++) {
904  if (mask(x, y, stopPlane)) {
905  _stop = true;
906  break;
907  }
908  }
909  }
910 }
911 
912 template <typename ImagePixelT, typename MaskPixelT>
913 class StartspanSet {
914 public:
916  : _image(image->getImage()), _mask(image->getMask()) {}
917  ~StartspanSet() {}
918 
919  bool add(geom::Span *span, DIRECTION const dir, bool addToMask = true);
920  bool process(Footprint *fp, // the footprint that we're building
921  Threshold const &threshold, // Threshold
922  double const param = -1); // parameter that Threshold may need
923 private:
924  image::Image<ImagePixelT> const *_image; // the Image we're searching
925  image::Mask<MaskPixelT> *_mask; // the mask that tells us where we've got to
926  std::vector<std::shared_ptr<Startspan<MaskPixelT>>> _spans; // list of Startspans
927 };
928 
929 //
930 // Add a new Startspan to a StartspansSet. Iff we see a stop bit, return true
931 //
932 template <typename ImagePixelT, typename MaskPixelT>
933 bool StartspanSet<ImagePixelT, MaskPixelT>::add(geom::Span *span, // the span in question
934  DIRECTION const dir, // the desired direction to search
935  bool addToMask) { // should I add the Span to the mask?
936  if (dir == RESTART) {
937  if (add(span, UP) || add(span, DOWN, false)) {
938  return true;
939  }
940  } else {
941  auto sspan = std::make_shared<MaskPixelT>(span, dir);
942  if (sspan->stop()) { // we detected a stop bit
943  return true;
944  } else {
945  _spans.push_back(sspan);
946  }
947  }
948 
949  return false;
950 }
951 
952 /*
953  * Search the image for pixels above threshold, starting at a single Startspan.
954  * We search the array looking for one to process; it'd be better to move the
955  * ones that we're done with to the end, but it probably isn't worth it for
956  * the anticipated uses of this routine.
957  *
958  * This is the guts of pmFindFootprintAtPoint
959  */
960 template <typename ImagePixelT, typename MaskPixelT>
961 bool StartspanSet<ImagePixelT, MaskPixelT>::process(Footprint *fp, // the footprint that we're building
962  Threshold const &threshold, // Threshold
963  double const param // parameter that Threshold may need
964  ) {
965  int const row0 = _image->getY0();
966  int const col0 = _image->getOffsetCols();
967  int const height = _image->getHeight();
968 
969  Startspan<MaskPixelT> *sspan = NULL;
970  for (auto iter = _spans.begin(); iter != _spans.end(); iter++) {
971  *sspan = *iter;
972  if (sspan->getDirection() != DONE) {
973  break;
974  }
975  if (sspan->Stop()) {
976  break;
977  }
978  }
979  if (sspan == NULL || sspan->getDirection() == DONE) { // no more Startspans to process
980  return false;
981  }
982  if (sspan->Stop()) { // they don't want any more spans processed
983  return false;
984  }
985  /*
986  * Work
987  */
988  DIRECTION const dir = sspan->getDirection();
989  /*
990  * Set initial span to the startspan
991  */
992  int x0 = sspan->getSpan()->getX0() - col0;
993  /*
994  * Go through image identifying objects
995  */
996  int nx0 = -1; // new value of x0
997  int const di = (dir == UP) ? 1 : -1; // how much i changes to get to the next row
998  bool stop = false; // should I stop searching for spans?
999 
1000  typedef typename image::Image<ImagePixelT>::pixel_accessor pixAccessT;
1001  double const thresholdVal = threshold.getValue(param);
1002  bool const polarity = threshold.getPolarity();
1003 
1004  for (int i = sspan->span->y - row0 + di; i < height && i >= 0; i += di) {
1005  pixAccessT imgRow = _image->origin().advance(0, i); // row pointer
1006  // maskPixAccessT maskRow = _mask->origin.advance(0, i); // masks's row pointer
1007  //
1008  // Search left from the pixel diagonally to the left of (i - di, x0). If there's
1009  // a connected span there it may need to grow up and/or down, so push it onto
1010  // the stack for later consideration
1011  //
1012  nx0 = -1;
1013  for (int j = x0 - 1; j >= -1; j--) {
1014  ImagePixelT pixVal = (j < 0) ? thresholdVal - 100 : (polarity ? imgRow[j] : -imgRow[j]);
1015  if (_mask(j, i, Startspan<MaskPixelT>::detectedPlane) || pixVal < threshold) {
1016  if (j < x0 - 1) { // we found some pixels above threshold
1017  nx0 = j + 1;
1018  }
1019  break;
1020  }
1021  }
1022 #if 0
1023  if (nx0 < 0) { // no span to the left
1024  nx1 = x0 - 1; // we're going to resume searching at nx1 + 1
1025  } else {
1026  //
1027  // Search right in leftmost span
1028  //
1029  //nx1 = 0; // make gcc happy
1030  for (int j = nx0 + 1; j <= width; j++) {
1031  ImagePixelT pixVal = (j >= width) ? threshold - 100 :
1032  (polarity ? (F32 ? imgRowF32[j] : imgRowS32[j]) :
1033  (F32 ? -imgRowF32[j] : -imgRowS32[j]));
1034  if ((maskRow[j] & DETECTED) || pixVal < threshold) {
1035  nx1 = j - 1;
1036  break;
1037  }
1038  }
1039 
1040  pmSpan const *sp = pmFootprintAddSpan(fp, i + row0, nx0 + col0, nx1 + col0);
1041 
1042  if (add_startspan(startspans, sp, mask, RESTART)) {
1043  stop = true;
1044  break;
1045  }
1046  }
1047  //
1048  // Now look for spans connected to the old span. The first of these we'll
1049  // simply process, but others will have to be deferred for later consideration.
1050  //
1051  // In fact, if the span overhangs to the right we'll have to defer the overhang
1052  // until later too, as it too can grow in both directions
1053  //
1054  // Note that column width exists virtually, and always ends the last span; this
1055  // is why we claim below that sx1 is always set
1056  //
1057  bool first = false; // is this the first new span detected?
1058  for (int j = nx1 + 1; j <= x1 + 1; j++) {
1059  ImagePixelT pixVal = (j >= width) ? threshold - 100 :
1060  (polarity ? (F32 ? imgRowF32[j] : imgRowS32[j]) : (F32 ? -imgRowF32[j] : -imgRowS32[j]));
1061  if (!(maskRow[j] & DETECTED) && pixVal >= threshold) {
1062  int sx0 = j++; // span that we're working on is sx0:sx1
1063  int sx1 = -1; // We know that if we got here, we'll also set sx1
1064  for (; j <= width; j++) {
1065  ImagePixelT pixVal = (j >= width) ? threshold - 100 :
1066  (polarity ? (F32 ? imgRowF32[j] : imgRowS32[j]) :
1067  (F32 ? -imgRowF32[j] : -imgRowS32[j]));
1068  if ((maskRow[j] & DETECTED) || pixVal < threshold) { // end of span
1069  sx1 = j;
1070  break;
1071  }
1072  }
1073  assert (sx1 >= 0);
1074 
1075  pmSpan const *sp;
1076  if (first) {
1077  if (sx1 <= x1) {
1078  sp = pmFootprintAddSpan(fp, i + row0, sx0 + col0, sx1 + col0 - 1);
1079  if (add_startspan(startspans, sp, mask, DONE)) {
1080  stop = true;
1081  break;
1082  }
1083  } else { // overhangs to right
1084  sp = pmFootprintAddSpan(fp, i + row0, sx0 + col0, x1 + col0);
1085  if (add_startspan(startspans, sp, mask, DONE)) {
1086  stop = true;
1087  break;
1088  }
1089  sp = pmFootprintAddSpan(fp, i + row0, x1 + 1 + col0, sx1 + col0 - 1);
1090  if (add_startspan(startspans, sp, mask, RESTART)) {
1091  stop = true;
1092  break;
1093  }
1094  }
1095  first = false;
1096  } else {
1097  sp = pmFootprintAddSpan(fp, i + row0, sx0 + col0, sx1 + col0 - 1);
1098  if (add_startspan(startspans, sp, mask, RESTART)) {
1099  stop = true;
1100  break;
1101  }
1102  }
1103  }
1104  }
1105 
1106  if (stop || first == false) { // we're done
1107  break;
1108  }
1109 
1110  x0 = nx0;
1111  x1 = nx1;
1112 #endif
1113  }
1114  /*
1115  * Cleanup
1116  */
1117 
1118  sspan->_direction = DONE;
1119  return stop ? false : true;
1120 }
1122 }
1123 #if 0
1124 
1125 
1126 /*
1127  * Go through an image, starting at (row, col) and assembling all the pixels
1128  * that are connected to that point (in a chess kings-move sort of way) into
1129  * a pmFootprint.
1130  *
1131  * This is much slower than pmFindFootprints if you want to find lots of
1132  * footprints, but if you only want a small region about a given point it
1133  * can be much faster
1134  *
1135  * N.b. The returned pmFootprint is not in "normal form"; that is the pmSpans
1136  * are not sorted by increasing y, x0, x1. If this matters to you, call
1137  * pmFootprintNormalize()
1138  */
1139 pmFootprint *
1140 pmFindFootprintAtPoint(psImage const *img, // image to search
1141  Threshold const &threshold, // Threshold
1142  psArray const *peaks, // array of peaks; finding one terminates search for footprint
1143  int row, int col) { // starting position (in img's parent's coordinate system)
1144  assert(img != NULL);
1145 
1146  bool F32 = false; // is this an F32 image?
1147  if (img->type.type == PS_TYPE_F32) {
1148  F32 = true;
1149  } else if (img->type.type == PS_TYPE_S32) {
1150  F32 = false;
1151  } else { // N.b. You can't trivially add more cases here; F32 is just a bool
1152  psError(PS_ERR_UNKNOWN, true, "Unsupported psImage type: %d", img->type.type);
1153  return NULL;
1154  }
1155  psF32 *imgRowF32 = NULL; // row pointer if F32
1156  psS32 *imgRowS32 = NULL; // " " " " !F32
1157 
1158  int const row0 = img->row0;
1159  int const col0 = img->col0;
1160  int const height = img->getHeight();
1161  int const width = img->getWidth();
1162 /*
1163  * Is point in image, and above threshold?
1164  */
1165  row -= row0;
1166  col -= col0;
1167  if (row < 0 || row >= height ||
1168  col < 0 || col >= width) {
1169  psError(PS_ERR_BAD_PARAMETER_VALUE, true,
1170  "row/col == (%d, %d) are out of bounds [%d--%d, %d--%d]",
1171  row + row0, col + col0, row0, row0 + height - 1, col0, col0 + width - 1);
1172  return NULL;
1173  }
1174 
1175  ImagePixelT pixVal = F32 ? img->data.F32[row][col] : img->data.S32[row][col];
1176  if (pixVal < threshold) {
1177  return pmFootprintAlloc(0, img);
1178  }
1179 
1180  pmFootprint *fp = pmFootprintAlloc(1 + img->getHeight()/10, img);
1181 /*
1182  * We need a mask for two purposes; to indicate which pixels are already detected,
1183  * and to store the "stop" pixels --- those that, once reached, should stop us
1184  * looking for the rest of the pmFootprint. These are generally set from peaks.
1185  */
1186  psImage *mask = psImageAlloc(width, height, PS_TYPE_MASK);
1187  P_PSIMAGE_SET_ROW0(mask, row0);
1188  P_PSIMAGE_SET_COL0(mask, col0);
1189  psImageInit(mask, INITIAL);
1190  //
1191  // Set stop bits from peaks list
1192  //
1193  assert (peaks == NULL || peaks->n == 0 || pmIsPeak(peaks->data[0]));
1194  if (peaks != NULL) {
1195  for (int i = 0; i < peaks->n; i++) {
1196  pmPeak *peak = peaks->data[i];
1197  mask->data.PS_TYPE_MASK_DATA[peak->y - mask->row0][peak->x - mask->col0] |= STOP;
1198  }
1199  }
1200 /*
1201  * Find starting span passing through (row, col)
1202  */
1203  psArray *startspans = psArrayAllocEmpty(1); // spans where we have to restart the search
1204 
1205  imgRowF32 = img->data.F32[row]; // only one of
1206  imgRowS32 = img->data.S32[row]; // these is valid!
1207  psMaskType *maskRow = mask->data.PS_TYPE_MASK_DATA[row];
1208  {
1209  int i;
1210  for (i = col; i >= 0; i--) {
1211  pixVal = F32 ? imgRowF32[i] : imgRowS32[i];
1212  if ((maskRow[i] & DETECTED) || pixVal < threshold) {
1213  break;
1214  }
1215  }
1216  int i0 = i;
1217  for (i = col; i < width; i++) {
1218  pixVal = F32 ? imgRowF32[i] : imgRowS32[i];
1219  if ((maskRow[i] & DETECTED) || pixVal < threshold) {
1220  break;
1221  }
1222  }
1223  int i1 = i;
1224  pmSpan const *sp = pmFootprintAddSpan(fp, row + row0, i0 + col0 + 1, i1 + col0 - 1);
1225 
1226  (void)add_startspan(startspans, sp, mask, RESTART);
1227  }
1228  /*
1229  * Now workout from those Startspans, searching for pixels above threshold
1230  */
1231  while (do_startspan(fp, img, mask, threshold, startspans)) continue;
1232  /*
1233  * Cleanup
1234  */
1235  psFree(mask);
1236  psFree(startspans); // restores the image pixel
1237 
1238  return fp; // pmFootprint really
1239 }
1240 #endif
1241 
1242 FootprintSet::FootprintSet(geom::Box2I region)
1243  : daf::base::Citizen(typeid(this)), _footprints(std::make_shared<FootprintList>()), _region(region) {}
1244 
1245 FootprintSet::FootprintSet(FootprintSet const &rhs)
1246  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList), _region(rhs._region) {
1247  _footprints->reserve(rhs._footprints->size());
1248  for (FootprintSet::FootprintList::const_iterator ptr = rhs._footprints->begin(),
1249  end = rhs._footprints->end();
1250  ptr != end; ++ptr) {
1251  _footprints->push_back(std::make_shared<Footprint>(**ptr));
1252  }
1253 }
1254 
1255 FootprintSet &FootprintSet::operator=(FootprintSet const &rhs) {
1256  FootprintSet tmp(rhs);
1257  swap(tmp); // See Meyers, Effective C++, Item 11
1258  return *this;
1259 }
1260 
1261 void FootprintSet::merge(FootprintSet const &rhs, int tGrow, int rGrow, bool isotropic) {
1262  FootprintControl const ctrl(true, isotropic);
1263  FootprintSet fs = mergeFootprintSets(*this, tGrow, rhs, rGrow, ctrl);
1264  swap(fs); // Swap the new FootprintSet into place
1265 }
1266 
1267 void FootprintSet::setRegion(geom::Box2I const &region) {
1268  _region = region;
1269 
1270  for (FootprintSet::FootprintList::iterator ptr = _footprints->begin(), end = _footprints->end();
1271  ptr != end; ++ptr) {
1272  (*ptr)->setRegion(region);
1273  }
1274 }
1275 
1276 FootprintSet::FootprintSet(FootprintSet const &rhs, int r, bool isotropic)
1277  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList), _region(rhs._region) {
1278  if (r == 0) {
1279  FootprintSet fs = rhs;
1280  swap(fs); // Swap the new FootprintSet into place
1281  return;
1282  } else if (r < 0) {
1283  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
1284  (boost::format("I cannot grow by negative numbers: %d") % r).str());
1285  }
1286 
1287  FootprintControl const ctrl(true, isotropic);
1288  FootprintSet fs = mergeFootprintSets(FootprintSet(rhs.getRegion()), 0, rhs, r, ctrl);
1289  swap(fs); // Swap the new FootprintSet into place
1290 }
1291 
1292 FootprintSet::FootprintSet(FootprintSet const &rhs, int ngrow, FootprintControl const &ctrl)
1293  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList), _region(rhs._region) {
1294  if (ngrow == 0) {
1295  FootprintSet fs = rhs;
1296  swap(fs); // Swap the new FootprintSet into place
1297  return;
1298  } else if (ngrow < 0) {
1299  throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
1300  str(boost::format("I cannot grow by negative numbers: %d") % ngrow));
1301  }
1302 
1303  FootprintSet fs = mergeFootprintSets(FootprintSet(rhs.getRegion()), 0, rhs, ngrow, ctrl);
1304  swap(fs); // Swap the new FootprintSet into place
1305 }
1306 
1307 FootprintSet::FootprintSet(FootprintSet const &fs1, FootprintSet const &fs2, bool const)
1308  : daf::base::Citizen(typeid(this)), _footprints(new FootprintList()), _region(fs1._region) {
1309  _region.include(fs2._region);
1310  throw LSST_EXCEPT(pex::exceptions::LogicError, "NOT IMPLEMENTED");
1311 }
1312 
1313 std::shared_ptr<image::Image<FootprintIdPixel>> FootprintSet::insertIntoImage(bool const relativeIDs) const {
1314  auto im = std::make_shared<image::Image<FootprintIdPixel>>(_region);
1315  *im = 0;
1316 
1317  FootprintIdPixel id = 0;
1318  for (auto const &fIter : *_footprints) {
1319  if (relativeIDs) {
1320  id++;
1321  } else {
1322  id = fIter->getId();
1323  }
1324 
1325  fIter->getSpans()->applyFunctor(setIdImage<FootprintIdPixel>(id), *im);
1326  }
1327 
1328  return im;
1329 }
1330 
1331 template <typename ImagePixelT, typename MaskPixelT>
1332 void FootprintSet::makeHeavy(image::MaskedImage<ImagePixelT, MaskPixelT> const &mimg,
1333  HeavyFootprintCtrl const *ctrl) {
1334  HeavyFootprintCtrl ctrl_s = HeavyFootprintCtrl();
1335 
1336  if (!ctrl) {
1337  ctrl = &ctrl_s;
1338  }
1339 
1340  for (FootprintList::iterator ptr = _footprints->begin(), end = _footprints->end(); ptr != end; ++ptr) {
1341  ptr->reset(new HeavyFootprint<ImagePixelT, MaskPixelT>(**ptr, mimg, ctrl));
1342  }
1343 }
1344 
1345 void FootprintSet::makeSources(afw::table::SourceCatalog &cat) const {
1346  for (FootprintList::const_iterator i = _footprints->begin(); i != _footprints->end(); ++i) {
1347  std::shared_ptr<afw::table::SourceRecord> r = cat.addNew();
1348  r->setFootprint(*i);
1349  }
1350 }
1351 
1352 //
1353 // Explicit instantiations
1354 //
1355 
1356 #ifndef DOXYGEN
1357 
1358 #define INSTANTIATE(PIXEL) \
1359  template FootprintSet::FootprintSet(image::Image<PIXEL> const &, Threshold const &, int const, \
1360  bool const); \
1361  template FootprintSet::FootprintSet(image::MaskedImage<PIXEL, image::MaskPixel> const &, \
1362  Threshold const &, std::string const &, int const, bool const); \
1363  template void FootprintSet::makeHeavy(image::MaskedImage<PIXEL, image::MaskPixel> const &, \
1364  HeavyFootprintCtrl const *)
1365 
1366 template FootprintSet::FootprintSet(image::Mask<image::MaskPixel> const &, Threshold const &, int const);
1367 
1368 template void FootprintSet::setMask(image::Mask<image::MaskPixel> *, std::string const &);
1369 template void FootprintSet::setMask(std::shared_ptr<image::Mask<image::MaskPixel>>, std::string const &);
1370 
1371 INSTANTIATE(std::uint16_t);
1372 INSTANTIATE(int);
1373 INSTANTIATE(float);
1374 INSTANTIATE(double);
1375 }
1376 }
1377 } // end lsst::afw::detection
1378 
1379 #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
#define INSTANTIATE(TYPE)
Use (pixels &amp; (given mask))
Definition: Threshold.h:48
Extent< int, 2 > Extent2I
Definition: Extent.h:341
ImagePtr getImage(bool const noThrow=false) const
Return a (Ptr to) the MaskedImage&#39;s image.
Definition: MaskedImage.h:959
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:397
int getX0() const
Return the image&#39;s column-origin.
Definition: Image.h:317
VariancePtr getVariance(bool const noThrow=false) const
Return a (Ptr to) the MaskedImage&#39;s variance.
Definition: MaskedImage.h:974
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.
afw::table::CatalogT< PeakRecord > PeakCatalog
Definition: Peak.h:223
Represent a 2-dimensional array of bitmask pixels.
Definition: Mask.h:83
MaskPtr getMask(bool const noThrow=false) const
Return a (Ptr to) the MaskedImage&#39;s mask.
Definition: MaskedImage.h:966
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 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
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
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
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