24__all__ = (
"PsfGenerationError",
"SourceDetectionConfig",
"SourceDetectionTask",
"addExposures")
26from contextlib
import contextmanager
34import lsst.afw.image
as afwImage
39from lsst.utils.timer
import timeMethod
40from .subtractBackground
import SubtractBackgroundTask, backgroundFlatContext
44 """Raised when we cannot generate a PSF for detection
50 **kwargs : `dict`, optional
51 Additional keyword arguments to initialize the Exception base class.
60 return f
"{self.msg}: {self.metadata}"
65 if not isinstance(value, (int, float, str)):
66 raise TypeError(f
"{key} is of type {type(value)}, but only (int, float, str) are allowed.")
71 """Configuration parameters for the SourceDetectionTask
73 minPixels = pexConfig.RangeField(
74 doc=
"detected sources with fewer than the specified number of pixels will be ignored",
75 dtype=int, optional=
False, default=1, min=0,
77 isotropicGrow = pexConfig.Field(
78 doc=
"Grow pixels as isotropically as possible? If False, use a Manhattan metric instead.",
79 dtype=bool, default=
True,
81 combinedGrow = pexConfig.Field(
82 doc=
"Grow all footprints at the same time? This allows disconnected footprints to merge.",
83 dtype=bool, default=
True,
85 nSigmaToGrow = pexConfig.Field(
86 doc=
"Grow detections by nSigmaToGrow * [PSF RMS width]; if 0 then do not grow",
87 dtype=float, default=2.4,
89 returnOriginalFootprints = pexConfig.Field(
90 doc=
"Grow detections to set the image mask bits, but return the original (not-grown) footprints",
91 dtype=bool, optional=
False, default=
False,
93 thresholdValue = pexConfig.RangeField(
94 doc=
"Threshold for detecting footprints; exact meaning and units depend on thresholdType.",
95 dtype=float, optional=
False, default=5.0, min=0.0,
97 includeThresholdMultiplier = pexConfig.RangeField(
98 doc=
"Multiplier on thresholdValue for whether a source is included in the output catalog."
99 " For example, thresholdValue=5, includeThresholdMultiplier=10, thresholdType='pixel_stdev' "
100 "results in a catalog of sources at >50 sigma with the detection mask and footprints "
101 "including pixels >5 sigma.",
102 dtype=float, default=1.0, min=0.0,
104 thresholdType = pexConfig.ChoiceField(
105 doc=
"Specifies the meaning of thresholdValue.",
106 dtype=str, optional=
False, default=
"pixel_stdev",
108 "variance":
"threshold applied to image variance",
109 "stdev":
"threshold applied to image std deviation",
110 "value":
"threshold applied to image value",
111 "pixel_stdev":
"threshold applied to per-pixel std deviation",
114 thresholdPolarity = pexConfig.ChoiceField(
115 doc=
"Specifies whether to detect positive, or negative sources, or both.",
116 dtype=str, optional=
False, default=
"positive",
118 "positive":
"detect only positive sources",
119 "negative":
"detect only negative sources",
120 "both":
"detect both positive and negative sources",
123 adjustBackground = pexConfig.Field(
125 doc=
"Fiddle factor to add to the background; debugging only",
128 reEstimateBackground = pexConfig.Field(
130 doc=
"Estimate the background again after final source detection?",
131 default=
True, optional=
False,
133 doApplyFlatBackgroundRatio = pexConfig.Field(
134 doc=
"Convert from a photometrically flat image to one suitable for background subtraction? "
135 "Only used if reEstimateBackground is True."
136 "If True, then a backgroundToPhotometricRatio must be supplied to the task run method.",
140 background = pexConfig.ConfigurableField(
141 doc=
"Background re-estimation; ignored if reEstimateBackground false",
142 target=SubtractBackgroundTask,
144 tempLocalBackground = pexConfig.ConfigurableField(
145 doc=(
"A local (small-scale), temporary background estimation step run between "
146 "detecting above-threshold regions and detecting the peaks within "
147 "them; used to avoid detecting spuerious peaks in the wings."),
148 target=SubtractBackgroundTask,
150 doTempLocalBackground = pexConfig.Field(
152 doc=
"Enable temporary local background subtraction? (see tempLocalBackground)",
155 tempWideBackground = pexConfig.ConfigurableField(
156 doc=(
"A wide (large-scale) background estimation and removal before footprint and peak detection. "
157 "It is added back into the image after detection. The purpose is to suppress very large "
158 "footprints (e.g., from large artifacts) that the deblender may choke on."),
159 target=SubtractBackgroundTask,
161 doTempWideBackground = pexConfig.Field(
163 doc=
"Do temporary wide (large-scale) background subtraction before footprint detection?",
166 nPeaksMaxSimple = pexConfig.Field(
168 doc=(
"The maximum number of peaks in a Footprint before trying to "
169 "replace its peaks using the temporary local background"),
172 nSigmaForKernel = pexConfig.Field(
174 doc=(
"Multiple of PSF RMS size to use for convolution kernel bounding box size; "
175 "note that this is not a half-size. The size will be rounded up to the nearest odd integer"),
178 statsMask = pexConfig.ListField(
180 doc=
"Mask planes to ignore when calculating statistics of image (for thresholdType=stdev)",
181 default=[
'BAD',
'SAT',
'EDGE',
'NO_DATA'],
186 doc=
"Mask planes to exclude when detecting sources."
199 for maskPlane
in (
"DETECTED",
"DETECTED_NEGATIVE"):
205 """Detect peaks and footprints of sources in an image.
207 This task expects the image to have been background subtracted first.
208 Running detection on images with a non-zero-centered background may result
209 in a single source detected on the entire image containing thousands of
210 peaks, or other pathological outputs.
214 schema : `lsst.afw.table.Schema`
215 Schema object used to create the output `lsst.afw.table.SourceCatalog`
217 Keyword arguments passed to `lsst.pipe.base.Task.__init__`
219 If schema is not None and configured for 'both' detections,
220 a 'flags.negative' field will be added to label detections made with a
225 This task convolves the image with a Gaussian approximation to the PSF,
226 matched to the sigma of the input exposure, because this is separable and
227 fast. The PSF would have to be very non-Gaussian or non-circular for this
228 approximation to have a significant impact on the signal-to-noise of the
231 ConfigClass = SourceDetectionConfig
232 _DefaultName =
"sourceDetection"
235 pipeBase.Task.__init__(self, **kwds)
236 if schema
is not None and self.config.thresholdPolarity ==
"both":
238 "is_negative", type=
"Flag",
239 doc=
"Set if source peak was detected as negative."
242 if self.config.thresholdPolarity ==
"both":
243 self.log.warning(
"Detection polarity set to 'both', but no flag will be "
244 "set to distinguish between positive and negative detections")
246 if self.config.reEstimateBackground:
247 self.makeSubtask(
"background")
248 if self.config.doTempLocalBackground:
249 self.makeSubtask(
"tempLocalBackground")
250 if self.config.doTempWideBackground:
251 self.makeSubtask(
"tempWideBackground")
254 def run(self, table, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None,
255 background=None, backgroundToPhotometricRatio=None):
256 r"""Detect sources and return catalog(s) of detections.
260 table : `lsst.afw.table.SourceTable`
261 Table object that will be used to create the SourceCatalog.
262 exposure : `lsst.afw.image.Exposure`
263 Exposure to process; DETECTED mask plane will be set in-place.
264 doSmooth : `bool`, optional
265 If True, smooth the image before detection using a Gaussian of width
266 ``sigma``, or the measured PSF width. Set to False when running on
267 e.g. a pre-convolved image, or a mask plane.
268 sigma : `float`, optional
269 Sigma of PSF (pixels); used for smoothing and to grow detections;
270 if None then measure the sigma of the PSF of the exposure
271 clearMask : `bool`, optional
272 Clear DETECTED{,_NEGATIVE} planes before running detection.
273 expId : `int`, optional
274 Exposure identifier; unused by this implementation, but used for
275 RNG seed by subclasses.
276 background : `lsst.afw.math.BackgroundList`, optional
277 Background that was already subtracted from the exposure; will be
278 modified in-place if ``reEstimateBackground=True``.
279 backgroundToPhotometricRatio : `lsst.afw.image.Image`, optional
280 Image to convert photometric-flattened image to
281 background-flattened image if ``reEstimateBackground=True`` and
282 exposure has been photometric-flattened.
286 result : `lsst.pipe.base.Struct`
287 The `~lsst.pipe.base.Struct` contains:
290 Detected sources on the exposure.
291 (`lsst.afw.table.SourceCatalog`)
293 Positive polarity footprints.
294 (`lsst.afw.detection.FootprintSet` or `None`)
296 Negative polarity footprints.
297 (`lsst.afw.detection.FootprintSet` or `None`)
299 Number of footprints in positive or 0 if detection polarity was
302 Number of footprints in negative or 0 if detection polarity was
305 Re-estimated background. `None` if
306 ``reEstimateBackground==False``.
307 (`lsst.afw.math.BackgroundList`)
309 Multiplication factor applied to the configured detection
315 Raised if flags.negative is needed, but isn't in table's schema.
316 lsst.pipe.base.TaskError
317 Raised if sigma=None, doSmooth=True and the exposure has no PSF.
321 If you want to avoid dealing with Sources and Tables, you can use
322 `detectFootprints()` to just get the
323 `~lsst.afw.detection.FootprintSet`\s.
326 raise ValueError(
"Table has incorrect Schema")
327 results = self.
detectFootprints(exposure=exposure, doSmooth=doSmooth, sigma=sigma,
328 clearMask=clearMask, expId=expId, background=background,
329 backgroundToPhotometricRatio=backgroundToPhotometricRatio)
331 sources.reserve(results.numPos + results.numNeg)
333 results.negative.makeSources(sources)
335 for record
in sources:
338 results.positive.makeSources(sources)
339 results.sources = sources
342 def display(self, exposure, results, convolvedImage=None):
343 """Display detections if so configured
345 Displays the ``exposure`` in frame 0, overlays the detection peaks.
347 Requires that ``lsstDebug`` has been set up correctly, so that
348 ``lsstDebug.Info("lsst.meas.algorithms.detection")`` evaluates `True`.
350 If the ``convolvedImage`` is non-`None` and
351 ``lsstDebug.Info("lsst.meas.algorithms.detection") > 1``, the
352 ``convolvedImage`` will be displayed in frame 1.
356 exposure : `lsst.afw.image.Exposure`
357 Exposure to display, on which will be plotted the detections.
358 results : `lsst.pipe.base.Struct`
359 Results of the 'detectFootprints' method, containing positive and
360 negative footprints (which contain the peak positions that we will
361 plot). This is a `Struct` with ``positive`` and ``negative``
362 elements that are of type `lsst.afw.detection.FootprintSet`.
363 convolvedImage : `lsst.afw.image.Image`, optional
364 Convolved image used for thresholding.
377 afwDisplay.setDefaultMaskTransparency(75)
379 disp0 = afwDisplay.Display(frame=0)
380 disp0.mtv(exposure, title=
"detection")
382 def plotPeaks(fps, ctype):
385 with disp0.Buffering():
386 for fp
in fps.getFootprints():
387 for pp
in fp.getPeaks():
388 disp0.dot(
"+", pp.getFx(), pp.getFy(), ctype=ctype)
389 plotPeaks(results.positive,
"yellow")
390 plotPeaks(results.negative,
"red")
392 if convolvedImage
and display > 1:
393 disp1 = afwDisplay.Display(frame=1)
394 disp1.mtv(convolvedImage, title=
"PSF smoothed")
396 disp2 = afwDisplay.Display(frame=2)
397 disp2.mtv(afwImage.ImageF(np.sqrt(exposure.variance.array)), title=
"stddev")
400 """Apply a temporary local background subtraction
402 This temporary local background serves to suppress noise fluctuations
403 in the wings of bright objects.
405 Peaks in the footprints will be updated.
409 exposure : `lsst.afw.image.Exposure`
410 Exposure for which to fit local background.
411 middle : `lsst.afw.image.MaskedImage`
412 Convolved image on which detection will be performed
413 (typically smaller than ``exposure`` because the
414 half-kernel has been removed around the edges).
415 results : `lsst.pipe.base.Struct`
416 Results of the 'detectFootprints' method, containing positive and
417 negative footprints (which contain the peak positions that we will
418 plot). This is a `Struct` with ``positive`` and ``negative``
419 elements that are of type `lsst.afw.detection.FootprintSet`.
424 bg = self.tempLocalBackground.fitBackground(exposure.getMaskedImage())
425 bgImage = bg.getImageF(self.tempLocalBackground.config.algorithm,
426 self.tempLocalBackground.config.undersampleStyle)
427 middle -= bgImage.Factory(bgImage, middle.getBBox())
428 if self.config.thresholdPolarity !=
"negative":
429 results.positiveThreshold = self.
makeThreshold(middle,
"positive")
430 self.
updatePeaks(results.positive, middle, results.positiveThreshold)
431 if self.config.thresholdPolarity !=
"positive":
432 results.negativeThreshold = self.
makeThreshold(middle,
"negative")
433 self.
updatePeaks(results.negative, middle, results.negativeThreshold)
436 """Clear the DETECTED and DETECTED_NEGATIVE mask planes.
438 Removes any previous detection mask in preparation for a new
443 mask : `lsst.afw.image.Mask`
446 mask &= ~(mask.getPlaneBitMask(
"DETECTED") | mask.getPlaneBitMask(
"DETECTED_NEGATIVE"))
449 """Calculate the size of the smoothing kernel.
451 Uses the ``nSigmaForKernel`` configuration parameter. Note
452 that that is the full width of the kernel bounding box
453 (so a value of 7 means 3.5 sigma on either side of center).
454 The value will be rounded up to the nearest odd integer.
459 Gaussian sigma of smoothing kernel.
464 Size of the smoothing kernel.
466 return (int(sigma * self.config.nSigmaForKernel + 0.5)//2)*2 + 1
469 """Create a single Gaussian PSF for an exposure.
471 If ``sigma`` is provided, we make a `~lsst.afw.detection.GaussianPsf`
472 with that, otherwise use the sigma from the psf of the ``exposure`` to
473 make the `~lsst.afw.detection.GaussianPsf`.
477 exposure : `lsst.afw.image.Exposure`
478 Exposure from which to retrieve the PSF.
479 sigma : `float`, optional
480 Gaussian sigma to use if provided.
484 psf : `lsst.afw.detection.GaussianPsf`
485 PSF to use for detection.
490 Raised if ``sigma`` is not provided and ``exposure`` does not
491 contain a ``Psf`` object.
494 psf = exposure.getPsf()
496 raise PsfGenerationError(
"Unable to determine PSF to use for detection: no sigma provided")
497 sigma = psf.computeShape(psf.getAveragePosition()).getDeterminantRadius()
498 if not np.isfinite(sigma)
or sigma <= 0.0:
505 """Convolve the image with the PSF.
507 We convolve the image with a Gaussian approximation to the PSF,
508 because this is separable and therefore fast. It's technically a
509 correlation rather than a convolution, but since we use a symmetric
510 Gaussian there's no difference.
512 The convolution can be disabled with ``doSmooth=False``. If we do
513 convolve, we mask the edges as ``EDGE`` and return the convolved image
514 with the edges removed. This is because we can't convolve the edges
515 because the kernel would extend off the image.
519 maskedImage : `lsst.afw.image.MaskedImage`
521 psf : `lsst.afw.detection.Psf`
522 PSF to convolve with (actually with a Gaussian approximation
525 Actually do the convolution? Set to False when running on
526 e.g. a pre-convolved image, or a mask plane.
530 results : `lsst.pipe.base.Struct`
531 The `~lsst.pipe.base.Struct` contains:
534 Convolved image, without the edges. (`lsst.afw.image.MaskedImage`)
536 Gaussian sigma used for the convolution. (`float`)
538 self.metadata[
"doSmooth"] = doSmooth
539 sigma = psf.computeShape(psf.getAveragePosition()).getDeterminantRadius()
540 self.metadata[
"sigma"] = sigma
543 middle = maskedImage.Factory(maskedImage, deep=
True)
544 return pipeBase.Struct(middle=middle, sigma=sigma)
549 self.metadata[
"smoothingKernelWidth"] = kWidth
550 gaussFunc = afwMath.GaussianFunction1D(sigma)
553 convolvedImage = maskedImage.Factory(maskedImage.getBBox())
558 goodBBox = gaussKernel.shrinkBBox(convolvedImage.getBBox())
559 middle = convolvedImage.Factory(convolvedImage, goodBBox, afwImage.PARENT,
False)
562 self.
setEdgeBits(maskedImage, goodBBox, maskedImage.getMask().getPlaneBitMask(
"EDGE"))
564 return pipeBase.Struct(middle=middle, sigma=sigma)
567 r"""Apply thresholds to the convolved image
569 Identifies `~lsst.afw.detection.Footprint`\s, both positive and negative.
570 The threshold can be modified by the provided multiplication
575 middle : `lsst.afw.image.MaskedImage`
576 Convolved image to threshold.
577 bbox : `lsst.geom.Box2I`
578 Bounding box of unconvolved image.
580 Multiplier for the configured threshold.
581 factorNeg : `float` or `None`
582 Multiplier for the configured threshold for negative detection polarity.
583 If `None`, will be set equal to ``factor`` (i.e. equal to the factor used
584 for positive detection polarity).
588 results : `lsst.pipe.base.Struct`
589 The `~lsst.pipe.base.Struct` contains:
592 Positive detection footprints, if configured.
593 (`lsst.afw.detection.FootprintSet` or `None`)
595 Negative detection footprints, if configured.
596 (`lsst.afw.detection.FootprintSet` or `None`)
598 Multiplier for the configured threshold.
601 Multiplier for the configured threshold for negative detection polarity.
604 if factorNeg
is None:
606 self.log.info(
"Setting factor for negative detections equal to that for positive "
607 "detections: %f", factor)
608 results = pipeBase.Struct(positive=
None, negative=
None, factor=factor, factorNeg=factorNeg,
609 positiveThreshold=
None, negativeThreshold=
None)
611 if self.config.reEstimateBackground
or self.config.thresholdPolarity !=
"negative":
612 results.positiveThreshold = self.
makeThreshold(middle,
"positive", factor=factor)
615 results.positiveThreshold,
617 self.config.minPixels
619 results.positive.setRegion(bbox)
620 if self.config.reEstimateBackground
or self.config.thresholdPolarity !=
"positive":
621 results.negativeThreshold = self.
makeThreshold(middle,
"negative", factor=factorNeg)
624 results.negativeThreshold,
626 self.config.minPixels
628 results.negative.setRegion(bbox)
633 """Finalize the detected footprints.
635 Grow the footprints, set the ``DETECTED`` and ``DETECTED_NEGATIVE``
636 mask planes, and log the results.
638 ``numPos`` (number of positive footprints), ``numPosPeaks`` (number
639 of positive peaks), ``numNeg`` (number of negative footprints),
640 ``numNegPeaks`` (number of negative peaks) entries are added to the
645 mask : `lsst.afw.image.Mask`
646 Mask image on which to flag detected pixels.
647 results : `lsst.pipe.base.Struct`
648 Struct of detection results, including ``positive`` and
649 ``negative`` entries; modified.
651 Gaussian sigma of PSF.
653 Multiplier for the configured threshold. Note that this is only
654 used here for logging purposes.
655 factorNeg : `float` or `None`
656 Multiplier used for the negative detection polarity threshold.
657 If `None`, a factor equal to ``factor`` (i.e. equal to the one used
658 for positive detection polarity) is assumed. Note that this is only
659 used here for logging purposes.
661 if growOverride
is not None:
662 self.log.warning(
"config.nSigmaToGrow is set to %.2f, but the caller has set "
663 "growOverride to %.2f, so the footprints will be grown by "
664 "%.2f sigma.", self.config.nSigmaToGrow, growOverride, growOverride)
665 factorNeg = factor
if factorNeg
is None else factorNeg
666 for polarity, maskName
in ((
"positive",
"DETECTED"), (
"negative",
"DETECTED_NEGATIVE")):
667 fpSet = getattr(results, polarity)
670 if self.config.nSigmaToGrow > 0:
671 nGrow = int((self.config.nSigmaToGrow * sigma) + 0.5)
672 self.metadata[
"nGrow"] = nGrow
673 if self.config.combinedGrow:
676 stencil = (afwGeom.Stencil.CIRCLE
if self.config.isotropicGrow
else
677 afwGeom.Stencil.MANHATTAN)
679 fp.dilate(nGrow, stencil)
680 fpSet.setMask(mask, maskName)
681 if not self.config.returnOriginalFootprints:
682 setattr(results, polarity, fpSet)
685 results.numPosPeaks = 0
687 results.numNegPeaks = 0
691 if results.positive
is not None:
692 results.numPos = len(results.positive.getFootprints())
693 results.numPosPeaks = sum(len(fp.getPeaks())
for fp
in results.positive.getFootprints())
694 positive =
" %d positive peaks in %d footprints" % (results.numPosPeaks, results.numPos)
695 if results.negative
is not None:
696 results.numNeg = len(results.negative.getFootprints())
697 results.numNegPeaks = sum(len(fp.getPeaks())
for fp
in results.negative.getFootprints())
698 negative =
" %d negative peaks in %d footprints" % (results.numNegPeaks, results.numNeg)
700 self.log.info(
"Detected%s%s%s to %g +ve and %g -ve %s",
701 positive,
" and" if positive
and negative
else "", negative,
702 self.config.thresholdValue*self.config.includeThresholdMultiplier*factor,
703 self.config.thresholdValue*self.config.includeThresholdMultiplier*factorNeg,
704 "DN" if self.config.thresholdType ==
"value" else "sigma")
707 """Estimate the background after detection
711 maskedImage : `lsst.afw.image.MaskedImage`
712 Image on which to estimate the background.
713 backgrounds : `lsst.afw.math.BackgroundList`
714 List of backgrounds; modified.
715 backgroundToPhotometricRatio : `lsst.afw.image.Image`, optional
716 Image to multiply a photometrically-flattened image by to obtain a
717 background-flattened image.
718 Only used if ``config.doApplyFlatBackgroundRatio`` is ``True``.
722 bg : `lsst.afw.math.backgroundMI`
723 Empirical background model.
727 self.config.doApplyFlatBackgroundRatio,
728 backgroundToPhotometricRatio=backgroundToPhotometricRatio,
730 bg = self.background.fitBackground(maskedImage)
731 if self.config.adjustBackground:
732 self.log.warning(
"Fiddling the background by %g", self.config.adjustBackground)
733 bg += self.config.adjustBackground
734 self.log.info(
"Resubtracting the background after object detection")
735 maskedImage -= bg.getImageF(self.background.config.algorithm,
736 self.background.config.undersampleStyle)
738 actrl = bg.getBackgroundControl().getApproximateControl()
740 bg.getAsUsedUndersampleStyle(), actrl.getStyle(), actrl.getOrderX(),
741 actrl.getOrderY(), actrl.getWeighting()))
745 """Clear unwanted results from the Struct of results
747 If we specifically want only positive or only negative detections,
748 drop the ones we don't want, and its associated mask plane.
752 mask : `lsst.afw.image.Mask`
754 results : `lsst.pipe.base.Struct`
755 Detection results, with ``positive`` and ``negative`` elements;
758 if self.config.thresholdPolarity ==
"positive":
759 if self.config.reEstimateBackground:
760 mask &= ~mask.getPlaneBitMask(
"DETECTED_NEGATIVE")
761 results.negative =
None
762 elif self.config.thresholdPolarity ==
"negative":
763 if self.config.reEstimateBackground:
764 mask &= ~mask.getPlaneBitMask(
"DETECTED")
765 results.positive =
None
768 def detectFootprints(self, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None,
769 background=None, backgroundToPhotometricRatio=None):
770 """Detect footprints on an exposure.
774 exposure : `lsst.afw.image.Exposure`
775 Exposure to process; DETECTED{,_NEGATIVE} mask plane will be
777 doSmooth : `bool`, optional
778 If True, smooth the image before detection using a Gaussian
779 of width ``sigma``, or the measured PSF width of ``exposure``.
780 Set to False when running on e.g. a pre-convolved image, or a mask
782 sigma : `float`, optional
783 Gaussian Sigma of PSF (pixels); used for smoothing and to grow
784 detections; if `None` then measure the sigma of the PSF of the
786 clearMask : `bool`, optional
787 Clear both DETECTED and DETECTED_NEGATIVE planes before running
789 expId : `dict`, optional
790 Exposure identifier; unused by this implementation, but used for
791 RNG seed by subclasses.
792 background : `lsst.afw.math.BackgroundList`, optional
793 Background that was already subtracted from the exposure; will be
794 modified in-place if ``reEstimateBackground=True``.
795 backgroundToPhotometricRatio : `lsst.afw.image.Image`, optional
796 Image to convert photometric-flattened image to
797 background-flattened image if ``reEstimateBackground=True`` and
798 exposure has been photometric-flattened.
802 results : `lsst.pipe.base.Struct`
803 A `~lsst.pipe.base.Struct` containing:
806 Positive polarity footprints.
807 (`lsst.afw.detection.FootprintSet` or `None`)
809 Negative polarity footprints.
810 (`lsst.afw.detection.FootprintSet` or `None`)
812 Number of footprints in positive or 0 if detection polarity was
815 Number of footprints in negative or 0 if detection polarity was
818 Re-estimated background. `None` or the input ``background``
819 if ``reEstimateBackground==False``.
820 (`lsst.afw.math.BackgroundList`)
822 Multiplication factor applied to the configured detection
825 maskedImage = exposure.maskedImage
830 psf = self.
getPsf(exposure, sigma=sigma)
832 convolveResults = self.
convolveImage(maskedImage, psf, doSmooth=doSmooth)
833 middle = convolveResults.middle
834 sigma = convolveResults.sigma
840 if self.config.doTempLocalBackground:
847 results.positive = self.
setPeakSignificance(middle, results.positive, results.positiveThreshold)
848 results.negative = self.
setPeakSignificance(middle, results.negative, results.negativeThreshold,
851 if self.config.reEstimateBackground:
855 backgroundToPhotometricRatio=backgroundToPhotometricRatio,
860 self.
display(exposure, results, middle)
865 """Set the significance of flagged pixels to zero.
869 middle : `lsst.afw.image.Exposure`
870 Score or maximum likelihood difference image.
871 The image plane will be modified in place.
873 badPixelMask = middle.mask.getPlaneBitMask(self.config.excludeMaskPlanes)
874 badPixels = middle.mask.array & badPixelMask > 0
875 middle.image.array[badPixels] = 0
878 """Set the significance of each detected peak to the pixel value divided
879 by the appropriate standard-deviation for ``config.thresholdType``.
881 Only sets significance for "stdev" and "pixel_stdev" thresholdTypes;
882 we leave it undefined for "value" and "variance" as it does not have a
883 well-defined meaning in those cases.
887 exposure : `lsst.afw.image.Exposure`
888 Exposure that footprints were detected on, likely the convolved,
889 local background-subtracted image.
890 footprints : `lsst.afw.detection.FootprintSet`
891 Footprints detected on the image.
892 threshold : `lsst.afw.detection.Threshold`
893 Threshold used to find footprints.
894 negative : `bool`, optional
895 Are we calculating for negative sources?
897 if footprints
is None or footprints.getFootprints() == []:
899 polarity = -1
if negative
else 1
903 mapper.addMinimalSchema(footprints.getFootprints()[0].peaks.schema)
904 mapper.addOutputField(
"significance", type=float,
905 doc=
"Ratio of peak value to configured standard deviation.")
911 for old, new
in zip(footprints.getFootprints(), newFootprints.getFootprints()):
913 newPeaks.extend(old.peaks, mapper=mapper)
914 new.getPeaks().clear()
915 new.setPeakCatalog(newPeaks)
918 if self.config.thresholdType ==
"pixel_stdev":
919 for footprint
in newFootprints.getFootprints():
920 footprint.updatePeakSignificance(exposure.variance, polarity)
921 elif self.config.thresholdType ==
"stdev":
922 sigma = threshold.getValue() / self.config.thresholdValue
923 for footprint
in newFootprints.getFootprints():
924 footprint.updatePeakSignificance(polarity*sigma)
926 for footprint
in newFootprints.getFootprints():
927 for peak
in footprint.peaks:
928 peak[
"significance"] = 0
933 """Make an afw.detection.Threshold object corresponding to the task's
934 configuration and the statistics of the given image.
938 image : `afw.image.MaskedImage`
939 Image to measure noise statistics from if needed.
940 thresholdParity: `str`
941 One of "positive" or "negative", to set the kind of fluctuations
942 the Threshold will detect.
944 Factor by which to multiply the configured detection threshold.
945 This is useful for tweaking the detection threshold slightly.
949 threshold : `lsst.afw.detection.Threshold`
952 parity =
False if thresholdParity ==
"negative" else True
953 thresholdValue = self.config.thresholdValue
954 thresholdType = self.config.thresholdType
955 if self.config.thresholdType ==
'stdev':
956 bad = image.getMask().getPlaneBitMask(self.config.statsMask)
958 sctrl.setAndMask(bad)
960 thresholdValue *= stats.getValue(afwMath.STDEVCLIP)
961 thresholdType =
'value'
964 threshold.setIncludeMultiplier(self.config.includeThresholdMultiplier)
965 self.log.debug(
"Detection threshold: %s", threshold)
969 """Update the Peaks in a FootprintSet by detecting new Footprints and
970 Peaks in an image and using the new Peaks instead of the old ones.
974 fpSet : `afw.detection.FootprintSet`
975 Set of Footprints whose Peaks should be updated.
976 image : `afw.image.MaskedImage`
977 Image to detect new Footprints and Peak in.
978 threshold : `afw.detection.Threshold`
979 Threshold object for detection.
981 Input Footprints with fewer Peaks than self.config.nPeaksMaxSimple
982 are not modified, and if no new Peaks are detected in an input
983 Footprint, the brightest original Peak in that Footprint is kept.
985 for footprint
in fpSet.getFootprints():
986 oldPeaks = footprint.getPeaks()
987 if len(oldPeaks) <= self.config.nPeaksMaxSimple:
992 sub = image.Factory(image, footprint.getBBox())
997 self.config.minPixels
1000 for fpForPeaks
in fpSetForPeaks.getFootprints():
1001 for peak
in fpForPeaks.getPeaks():
1002 if footprint.contains(peak.getI()):
1003 newPeaks.append(peak)
1004 if len(newPeaks) > 0:
1006 oldPeaks.extend(newPeaks)
1012 """Set the edgeBitmask bits for all of maskedImage outside goodBBox
1016 maskedImage : `lsst.afw.image.MaskedImage`
1017 Image on which to set edge bits in the mask.
1018 goodBBox : `lsst.geom.Box2I`
1019 Bounding box of good pixels, in ``LOCAL`` coordinates.
1020 edgeBitmask : `lsst.afw.image.MaskPixel`
1021 Bit mask to OR with the existing mask bits in the region
1022 outside ``goodBBox``.
1024 msk = maskedImage.getMask()
1026 mx0, my0 = maskedImage.getXY0()
1027 for x0, y0, w, h
in ([0, 0,
1028 msk.getWidth(), goodBBox.getBeginY() - my0],
1029 [0, goodBBox.getEndY() - my0, msk.getWidth(),
1030 maskedImage.getHeight() - (goodBBox.getEndY() - my0)],
1032 goodBBox.getBeginX() - mx0, msk.getHeight()],
1033 [goodBBox.getEndX() - mx0, 0,
1034 maskedImage.getWidth() - (goodBBox.getEndX() - mx0), msk.getHeight()],
1038 edgeMask |= edgeBitmask
1042 """Context manager for removing wide (large-scale) background
1044 Removing a wide (large-scale) background helps to suppress the
1045 detection of large footprints that may overwhelm the deblender.
1046 It does, however, set a limit on the maximum scale of objects.
1048 The background that we remove will be restored upon exit from
1049 the context manager.
1053 exposure : `lsst.afw.image.Exposure`
1054 Exposure on which to remove large-scale background.
1058 context : context manager
1059 Context manager that will ensure the temporary wide background
1062 doTempWideBackground = self.config.doTempWideBackground
1063 if doTempWideBackground:
1064 self.log.info(
"Applying temporary wide background subtraction")
1065 original = exposure.maskedImage.image.array[:].copy()
1066 self.tempWideBackground.run(exposure).background
1069 image = exposure.maskedImage.image
1070 mask = exposure.maskedImage.mask
1071 noData = mask.array & mask.getPlaneBitMask(
"NO_DATA") > 0
1072 isGood = mask.array & mask.getPlaneBitMask(self.config.statsMask) == 0
1073 image.array[noData] = np.median(image.array[~noData & isGood])
1077 if doTempWideBackground:
1078 exposure.maskedImage.image.array[:] = original
1081def addExposures(exposureList):
1082 """Add a set of exposures together.
1086 exposureList : `list` of `lsst.afw.image.Exposure`
1087 Sequence of exposures to add.
1091 addedExposure : `lsst.afw.image.Exposure`
1092 An exposure of the same size as each exposure in ``exposureList``,
1093 with the metadata from ``exposureList[0]`` and a masked image equal
1094 to the sum of all the exposure's masked images.
1096 exposure0 = exposureList[0]
1097 image0 = exposure0.getMaskedImage()
1099 addedImage = image0.Factory(image0,
True)
1100 addedImage.setXY0(image0.getXY0())
1102 for exposure
in exposureList[1:]:
1103 image = exposure.getMaskedImage()
1106 addedExposure = exposure0.Factory(addedImage, exposure0.getWcs())
1107 return addedExposure
A circularly symmetric Gaussian Psf class with no spatial variation, intended mostly for testing purp...
Parameters to control convolution.
A kernel described by a pair of functions: func(x, y) = colFunc(x) * rowFunc(y)
Pass parameters to a Statistics object.
A mapping between the keys of two Schemas, used to copy data between them.
An integer coordinate rectangle.
__init__(self, msg, **kwargs)
makeThreshold(self, image, thresholdParity, factor=1.0)
applyTempLocalBackground(self, exposure, middle, results)
calculateKernelSize(self, sigma)
detectFootprints(self, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None, background=None, backgroundToPhotometricRatio=None)
setEdgeBits(maskedImage, goodBBox, edgeBitmask)
tempWideBackgroundContext(self, exposure)
setPeakSignificance(self, exposure, footprints, threshold, negative=False)
clearUnwantedResults(self, mask, results)
updatePeaks(self, fpSet, image, threshold)
getPsf(self, exposure, sigma=None)
applyThreshold(self, middle, bbox, factor=1.0, factorNeg=None)
convolveImage(self, maskedImage, psf, doSmooth=True)
display(self, exposure, results, convolvedImage=None)
removeBadPixels(self, middle)
__init__(self, schema=None, **kwds)
finalizeFootprints(self, mask, results, sigma, factor=1.0, factorNeg=None, growOverride=None)
run(self, table, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None, background=None, backgroundToPhotometricRatio=None)
reEstimateBackground(self, maskedImage, backgrounds, backgroundToPhotometricRatio=None)
Threshold createThreshold(const double value, const std::string type="value", const bool polarity=true)
Factory method for creating Threshold objects.
Statistics makeStatistics(lsst::afw::image::Image< Pixel > const &img, lsst::afw::image::Mask< image::MaskPixel > const &msk, int const flags, StatisticsControl const &sctrl=StatisticsControl())
Handle a watered-down front-end to the constructor (no variance)
void convolve(OutImageT &convolvedImage, InImageT const &inImage, KernelT const &kernel, ConvolutionControl const &convolutionControl=ConvolutionControl())
Convolve an Image or MaskedImage with a Kernel, setting pixels of an existing output image.
backgroundFlatContext(maskedImage, doApply, backgroundToPhotometricRatio=None)