24__all__ = (
"SourceDetectionConfig",
"SourceDetectionTask",
"addExposures")
26from contextlib
import contextmanager
39from lsst.utils.timer
import timeMethod
40from .subtractBackground
import SubtractBackgroundTask
44 """Configuration parameters for the SourceDetectionTask
46 minPixels = pexConfig.RangeField(
47 doc="detected sources with fewer than the specified number of pixels will be ignored",
48 dtype=int, optional=
False, default=1, min=0,
50 isotropicGrow = pexConfig.Field(
51 doc=
"Pixels should be grown as isotropically as possible (slower)",
52 dtype=bool, optional=
False, default=
False,
54 combinedGrow = pexConfig.Field(
55 doc=
"Grow all footprints at the same time? This allows disconnected footprints to merge.",
56 dtype=bool, default=
True,
58 nSigmaToGrow = pexConfig.Field(
59 doc=
"Grow detections by nSigmaToGrow * [PSF RMS width]; if 0 then do not grow",
60 dtype=float, default=2.4,
62 returnOriginalFootprints = pexConfig.Field(
63 doc=
"Grow detections to set the image mask bits, but return the original (not-grown) footprints",
64 dtype=bool, optional=
False, default=
False,
66 thresholdValue = pexConfig.RangeField(
67 doc=
"Threshold for footprints; exact meaning and units depend on thresholdType.",
68 dtype=float, optional=
False, default=5.0, min=0.0,
70 includeThresholdMultiplier = pexConfig.RangeField(
71 doc=
"Include threshold relative to thresholdValue",
72 dtype=float, default=1.0, min=0.0,
74 thresholdType = pexConfig.ChoiceField(
75 doc=
"specifies the desired flavor of Threshold",
76 dtype=str, optional=
False, default=
"stdev",
78 "variance":
"threshold applied to image variance",
79 "stdev":
"threshold applied to image std deviation",
80 "value":
"threshold applied to image value",
81 "pixel_stdev":
"threshold applied to per-pixel std deviation",
84 thresholdPolarity = pexConfig.ChoiceField(
85 doc=
"specifies whether to detect positive, or negative sources, or both",
86 dtype=str, optional=
False, default=
"positive",
88 "positive":
"detect only positive sources",
89 "negative":
"detect only negative sources",
90 "both":
"detect both positive and negative sources",
93 adjustBackground = pexConfig.Field(
95 doc=
"Fiddle factor to add to the background; debugging only",
98 reEstimateBackground = pexConfig.Field(
100 doc=
"Estimate the background again after final source detection?",
101 default=
True, optional=
False,
103 background = pexConfig.ConfigurableField(
104 doc=
"Background re-estimation; ignored if reEstimateBackground false",
105 target=SubtractBackgroundTask,
107 tempLocalBackground = pexConfig.ConfigurableField(
108 doc=(
"A local (small-scale), temporary background estimation step run between "
109 "detecting above-threshold regions and detecting the peaks within "
110 "them; used to avoid detecting spuerious peaks in the wings."),
111 target=SubtractBackgroundTask,
113 doTempLocalBackground = pexConfig.Field(
115 doc=
"Enable temporary local background subtraction? (see tempLocalBackground)",
118 tempWideBackground = pexConfig.ConfigurableField(
119 doc=(
"A wide (large-scale) background estimation and removal before footprint and peak detection. "
120 "It is added back into the image after detection. The purpose is to suppress very large "
121 "footprints (e.g., from large artifacts) that the deblender may choke on."),
122 target=SubtractBackgroundTask,
124 doTempWideBackground = pexConfig.Field(
126 doc=
"Do temporary wide (large-scale) background subtraction before footprint detection?",
129 nPeaksMaxSimple = pexConfig.Field(
131 doc=(
"The maximum number of peaks in a Footprint before trying to "
132 "replace its peaks using the temporary local background"),
135 nSigmaForKernel = pexConfig.Field(
137 doc=(
"Multiple of PSF RMS size to use for convolution kernel bounding box size; "
138 "note that this is not a half-size. The size will be rounded up to the nearest odd integer"),
141 statsMask = pexConfig.ListField(
143 doc=
"Mask planes to ignore when calculating statistics of image (for thresholdType=stdev)",
144 default=[
'BAD',
'SAT',
'EDGE',
'NO_DATA'],
157 for maskPlane
in (
"DETECTED",
"DETECTED_NEGATIVE"):
163 """Detect peaks and footprints of sources in an image.
165 This task convolves the image with a Gaussian approximation to the PSF,
166 matched to the sigma of the input exposure, because this
is separable
and
167 fast. The PSF would have to be very non-Gaussian
or non-circular
for this
168 approximation to have a significant impact on the signal-to-noise of the
176 Keyword arguments passed to `lsst.pipe.base.Task.__init__`
178 If schema
is not None and configured
for 'both' detections,
179 a
'flags.negative' field will be added to label detections made
with a
184 This task can add fields to the schema, so any code calling this task must
185 ensure that these columns are indeed present
in the input match list.
187 ConfigClass = SourceDetectionConfig
188 _DefaultName = "sourceDetection"
191 pipeBase.Task.__init__(self, **kwds)
192 if schema
is not None and self.config.thresholdPolarity ==
"both":
194 "flags_negative", type=
"Flag",
195 doc=
"set if source was detected as significantly negative"
198 if self.config.thresholdPolarity ==
"both":
199 self.log.warning(
"Detection polarity set to 'both', but no flag will be "
200 "set to distinguish between positive and negative detections")
202 if self.config.reEstimateBackground:
203 self.makeSubtask(
"background")
204 if self.config.doTempLocalBackground:
205 self.makeSubtask(
"tempLocalBackground")
206 if self.config.doTempWideBackground:
207 self.makeSubtask(
"tempWideBackground")
210 def run(self, table, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None):
211 r"""Detect sources and return catalog(s) of detections.
216 Table object that will be used to create the SourceCatalog.
218 Exposure to process; DETECTED mask plane will be set in-place.
220 If
True, smooth the image before detection using a Gaussian of width
221 ``sigma``,
or the measured PSF width. Set to
False when running on
222 e.g. a pre-convolved image,
or a mask plane.
224 Sigma of PSF (pixels); used
for smoothing
and to grow detections;
225 if None then measure the sigma of the PSF of the exposure
227 Clear DETECTED{,_NEGATIVE} planes before running detection.
229 Exposure identifier; unused by this implementation, but used
for
230 RNG seed by subclasses.
234 result : `lsst.pipe.base.Struct`
235 The `~lsst.pipe.base.Struct` contains:
238 Detected sources on the exposure.
241 Positive polarity footprints.
244 Negative polarity footprints.
247 Number of footprints
in positive
or 0
if detection polarity was
250 Number of footprints
in negative
or 0
if detection polarity was
253 Re-estimated background. `
None`
if
254 ``reEstimateBackground==
False``.
255 (`lsst.afw.math.BackgroundList`)
257 Multiplication factor applied to the configured detection
263 Raised
if flags.negative
is needed, but isn
't in table's schema.
264 lsst.pipe.base.TaskError
265 Raised
if sigma=
None, doSmooth=
True and the exposure has no PSF.
269 If you want to avoid dealing
with Sources
and Tables, you can use
274 raise ValueError(
"Table has incorrect Schema")
275 results = self.
detectFootprints(exposure=exposure, doSmooth=doSmooth, sigma=sigma,
276 clearMask=clearMask, expId=expId)
277 sources = afwTable.SourceCatalog(table)
278 sources.reserve(results.numPos + results.numNeg)
280 results.negative.makeSources(sources)
282 for record
in sources:
285 results.positive.makeSources(sources)
286 results.sources = sources
289 def display(self, exposure, results, convolvedImage=None):
290 """Display detections if so configured
292 Displays the ``exposure`` in frame 0, overlays the detection peaks.
294 Requires that ``lsstDebug`` has been set up correctly, so that
295 ``
lsstDebug.Info(
"lsst.meas.algorithms.detection")`` evaluates `
True`.
297 If the ``convolvedImage``
is non-`
None`
and
299 ``convolvedImage`` will be displayed
in frame 1.
304 Exposure to display, on which will be plotted the detections.
305 results : `lsst.pipe.base.Struct`
306 Results of the
'detectFootprints' method, containing positive
and
307 negative footprints (which contain the peak positions that we will
308 plot). This
is a `Struct`
with ``positive``
and ``negative``
311 Convolved image used
for thresholding.
324 afwDisplay.setDefaultMaskTransparency(75)
326 disp0 = afwDisplay.Display(frame=0)
327 disp0.mtv(exposure, title=
"detection")
329 def plotPeaks(fps, ctype):
332 with disp0.Buffering():
333 for fp
in fps.getFootprints():
334 for pp
in fp.getPeaks():
335 disp0.dot(
"+", pp.getFx(), pp.getFy(), ctype=ctype)
336 plotPeaks(results.positive,
"yellow")
337 plotPeaks(results.negative,
"red")
339 if convolvedImage
and display > 1:
340 disp1 = afwDisplay.Display(frame=1)
341 disp1.mtv(convolvedImage, title=
"PSF smoothed")
343 disp2 = afwDisplay.Display(frame=2)
344 disp2.mtv(afwImage.ImageF(np.sqrt(exposure.variance.array)), title=
"stddev")
347 """Apply a temporary local background subtraction
349 This temporary local background serves to suppress noise fluctuations
350 in the wings of bright objects.
352 Peaks
in the footprints will be updated.
357 Exposure
for which to fit local background.
359 Convolved image on which detection will be performed
360 (typically smaller than ``exposure`` because the
361 half-kernel has been removed around the edges).
362 results : `lsst.pipe.base.Struct`
363 Results of the
'detectFootprints' method, containing positive
and
364 negative footprints (which contain the peak positions that we will
365 plot). This
is a `Struct`
with ``positive``
and ``negative``
371 bg = self.tempLocalBackground.fitBackground(exposure.getMaskedImage())
372 bgImage = bg.getImageF(self.tempLocalBackground.config.algorithm,
373 self.tempLocalBackground.config.undersampleStyle)
374 middle -= bgImage.Factory(bgImage, middle.getBBox())
375 if self.config.thresholdPolarity !=
"negative":
376 results.positiveThreshold = self.
makeThreshold(middle,
"positive")
377 self.
updatePeaks(results.positive, middle, results.positiveThreshold)
378 if self.config.thresholdPolarity !=
"positive":
379 results.negativeThreshold = self.
makeThreshold(middle,
"negative")
380 self.
updatePeaks(results.negative, middle, results.negativeThreshold)
383 """Clear the DETECTED and DETECTED_NEGATIVE mask planes.
385 Removes any previous detection mask in preparation
for a new
393 mask &= ~(mask.getPlaneBitMask("DETECTED") | mask.getPlaneBitMask(
"DETECTED_NEGATIVE"))
396 """Calculate the size of the smoothing kernel.
398 Uses the ``nSigmaForKernel`` configuration parameter. Note
399 that that is the full width of the kernel bounding box
400 (so a value of 7 means 3.5 sigma on either side of center).
401 The value will be rounded up to the nearest odd integer.
406 Gaussian sigma of smoothing kernel.
411 Size of the smoothing kernel.
413 return (int(sigma * self.config.nSigmaForKernel + 0.5)//2)*2 + 1
416 """Create a single Gaussian PSF for an exposure.
419 with that, otherwise use the sigma
from the psf of the ``exposure`` to
425 Exposure
from which to retrieve the PSF.
426 sigma : `float`, optional
427 Gaussian sigma to use
if provided.
432 PSF to use
for detection.
437 Raised
if ``sigma``
is not provided
and ``exposure`` does
not
438 contain a ``Psf`` object.
441 psf = exposure.getPsf()
443 raise RuntimeError(
"Unable to determine PSF to use for detection: no sigma provided")
444 sigma = psf.computeShape(psf.getAveragePosition()).getDeterminantRadius()
446 psf = afwDet.GaussianPsf(size, size, sigma)
450 """Convolve the image with the PSF.
452 We convolve the image with a Gaussian approximation to the PSF,
453 because this
is separable
and therefore fast. It
's technically a
454 correlation rather than a convolution, but since we use a symmetric
455 Gaussian there's no difference.
457 The convolution can be disabled with ``doSmooth=
False``. If we do
458 convolve, we mask the edges
as ``EDGE``
and return the convolved image
459 with the edges removed. This
is because we can
't convolve the edges
460 because the kernel would extend off the image.
467 PSF to convolve with (actually
with a Gaussian approximation
470 Actually do the convolution? Set to
False when running on
471 e.g. a pre-convolved image,
or a mask plane.
475 results : `lsst.pipe.base.Struct`
476 The `~lsst.pipe.base.Struct` contains:
481 Gaussian sigma used
for the convolution. (`float`)
483 self.metadata["doSmooth"] = doSmooth
484 sigma = psf.computeShape(psf.getAveragePosition()).getDeterminantRadius()
485 self.metadata[
"sigma"] = sigma
488 middle = maskedImage.Factory(maskedImage, deep=
True)
489 return pipeBase.Struct(middle=middle, sigma=sigma)
494 self.metadata[
"smoothingKernelWidth"] = kWidth
495 gaussFunc = afwMath.GaussianFunction1D(sigma)
496 gaussKernel = afwMath.SeparableKernel(kWidth, kWidth, gaussFunc, gaussFunc)
498 convolvedImage = maskedImage.Factory(maskedImage.getBBox())
500 afwMath.convolve(convolvedImage, maskedImage, gaussKernel, afwMath.ConvolutionControl())
503 goodBBox = gaussKernel.shrinkBBox(convolvedImage.getBBox())
504 middle = convolvedImage.Factory(convolvedImage, goodBBox, afwImage.PARENT,
False)
507 self.
setEdgeBits(maskedImage, goodBBox, maskedImage.getMask().getPlaneBitMask(
"EDGE"))
509 return pipeBase.Struct(middle=middle, sigma=sigma)
512 r"""Apply thresholds to the convolved image
515 The threshold can be modified by the provided multiplication
521 Convolved image to threshold.
523 Bounding box of unconvolved image.
525 Multiplier
for the configured threshold.
529 results : `lsst.pipe.base.Struct`
530 The `~lsst.pipe.base.Struct` contains:
533 Positive detection footprints,
if configured.
536 Negative detection footprints,
if configured.
539 Multiplier
for the configured threshold.
542 results = pipeBase.Struct(positive=None, negative=
None, factor=factor,
543 positiveThreshold=
None, negativeThreshold=
None)
545 if self.config.reEstimateBackground
or self.config.thresholdPolarity !=
"negative":
546 results.positiveThreshold = self.
makeThreshold(middle,
"positive", factor=factor)
547 results.positive = afwDet.FootprintSet(
549 results.positiveThreshold,
551 self.config.minPixels
553 results.positive.setRegion(bbox)
554 if self.config.reEstimateBackground
or self.config.thresholdPolarity !=
"positive":
555 results.negativeThreshold = self.
makeThreshold(middle,
"negative", factor=factor)
556 results.negative = afwDet.FootprintSet(
558 results.negativeThreshold,
560 self.config.minPixels
562 results.negative.setRegion(bbox)
567 """Finalize the detected footprints.
569 Grow the footprints, set the ``DETECTED`` and ``DETECTED_NEGATIVE``
570 mask planes,
and log the results.
572 ``numPos`` (number of positive footprints), ``numPosPeaks`` (number
573 of positive peaks), ``numNeg`` (number of negative footprints),
574 ``numNegPeaks`` (number of negative peaks) entries are added to the
580 Mask image on which to flag detected pixels.
581 results : `lsst.pipe.base.Struct`
582 Struct of detection results, including ``positive``
and
583 ``negative`` entries; modified.
585 Gaussian sigma of PSF.
587 Multiplier
for the configured threshold.
589 for polarity, maskName
in ((
"positive",
"DETECTED"), (
"negative",
"DETECTED_NEGATIVE")):
590 fpSet = getattr(results, polarity)
593 if self.config.nSigmaToGrow > 0:
594 nGrow = int((self.config.nSigmaToGrow * sigma) + 0.5)
595 self.metadata[
"nGrow"] = nGrow
596 if self.config.combinedGrow:
597 fpSet = afwDet.FootprintSet(fpSet, nGrow, self.config.isotropicGrow)
599 stencil = (afwGeom.Stencil.CIRCLE
if self.config.isotropicGrow
else
600 afwGeom.Stencil.MANHATTAN)
602 fp.dilate(nGrow, stencil)
603 fpSet.setMask(mask, maskName)
604 if not self.config.returnOriginalFootprints:
605 setattr(results, polarity, fpSet)
608 results.numPosPeaks = 0
610 results.numNegPeaks = 0
614 if results.positive
is not None:
615 results.numPos = len(results.positive.getFootprints())
616 results.numPosPeaks = sum(len(fp.getPeaks())
for fp
in results.positive.getFootprints())
617 positive =
" %d positive peaks in %d footprints" % (results.numPosPeaks, results.numPos)
618 if results.negative
is not None:
619 results.numNeg = len(results.negative.getFootprints())
620 results.numNegPeaks = sum(len(fp.getPeaks())
for fp
in results.negative.getFootprints())
621 negative =
" %d negative peaks in %d footprints" % (results.numNegPeaks, results.numNeg)
623 self.log.info(
"Detected%s%s%s to %g %s",
624 positive,
" and" if positive
and negative
else "", negative,
625 self.config.thresholdValue*self.config.includeThresholdMultiplier*factor,
626 "DN" if self.config.thresholdType ==
"value" else "sigma")
629 """Estimate the background after detection
634 Image on which to estimate the background.
635 backgrounds : `lsst.afw.math.BackgroundList`
636 List of backgrounds; modified.
640 bg : `lsst.afw.math.backgroundMI`
641 Empirical background model.
643 bg = self.background.fitBackground(maskedImage)
644 if self.config.adjustBackground:
645 self.log.warning(
"Fiddling the background by %g", self.config.adjustBackground)
646 bg += self.config.adjustBackground
647 self.log.info(
"Resubtracting the background after object detection")
648 maskedImage -= bg.getImageF(self.background.config.algorithm,
649 self.background.config.undersampleStyle)
651 actrl = bg.getBackgroundControl().getApproximateControl()
652 backgrounds.append((bg, getattr(afwMath.Interpolate, self.background.config.algorithm),
653 bg.getAsUsedUndersampleStyle(), actrl.getStyle(), actrl.getOrderX(),
654 actrl.getOrderY(), actrl.getWeighting()))
658 """Clear unwanted results from the Struct of results
660 If we specifically want only positive or only negative detections,
661 drop the ones we don
't want, and its associated mask plane.
667 results : `lsst.pipe.base.Struct`
668 Detection results, with ``positive``
and ``negative`` elements;
671 if self.config.thresholdPolarity ==
"positive":
672 if self.config.reEstimateBackground:
673 mask &= ~mask.getPlaneBitMask(
"DETECTED_NEGATIVE")
674 results.negative =
None
675 elif self.config.thresholdPolarity ==
"negative":
676 if self.config.reEstimateBackground:
677 mask &= ~mask.getPlaneBitMask(
"DETECTED")
678 results.positive =
None
681 def detectFootprints(self, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None):
682 """Detect footprints on an exposure.
687 Exposure to process; DETECTED{,_NEGATIVE} mask plane will be
689 doSmooth : `bool`, optional
690 If
True, smooth the image before detection using a Gaussian
691 of width ``sigma``,
or the measured PSF width of ``exposure``.
692 Set to
False when running on e.g. a pre-convolved image,
or a mask
694 sigma : `float`, optional
695 Gaussian Sigma of PSF (pixels); used
for smoothing
and to grow
696 detections;
if `
None` then measure the sigma of the PSF of the
698 clearMask : `bool`, optional
699 Clear both DETECTED
and DETECTED_NEGATIVE planes before running
701 expId : `dict`, optional
702 Exposure identifier; unused by this implementation, but used
for
703 RNG seed by subclasses.
707 results : `lsst.pipe.base.Struct`
708 A `~lsst.pipe.base.Struct` containing:
711 Positive polarity footprints.
714 Negative polarity footprints.
717 Number of footprints
in positive
or 0
if detection polarity was
720 Number of footprints
in negative
or 0
if detection polarity was
723 Re-estimated background. `
None`
if
724 ``reEstimateBackground==
False``.
725 (`lsst.afw.math.BackgroundList`)
727 Multiplication factor applied to the configured detection
730 maskedImage = exposure.maskedImage
735 psf = self.
getPsf(exposure, sigma=sigma)
737 convolveResults = self.
convolveImage(maskedImage, psf, doSmooth=doSmooth)
738 middle = convolveResults.middle
739 sigma = convolveResults.sigma
742 results.background = afwMath.BackgroundList()
743 if self.config.doTempLocalBackground:
750 results.positive = self.
setPeakSignificance(middle, results.positive, results.positiveThreshold)
751 results.negative = self.
setPeakSignificance(middle, results.negative, results.negativeThreshold,
754 if self.config.reEstimateBackground:
759 self.
display(exposure, results, middle)
764 """Set the significance of each detected peak to the pixel value divided
765 by the appropriate standard-deviation for ``config.thresholdType``.
767 Only sets significance
for "stdev" and "pixel_stdev" thresholdTypes;
768 we leave it undefined
for "value" and "variance" as it does
not have a
769 well-defined meaning
in those cases.
774 Exposure that footprints were detected on, likely the convolved,
775 local background-subtracted image.
777 Footprints detected on the image.
779 Threshold used to find footprints.
780 negative : `bool`, optional
781 Are we calculating
for negative sources?
783 if footprints
is None or footprints.getFootprints() == []:
785 polarity = -1
if negative
else 1
788 mapper = afwTable.SchemaMapper(footprints.getFootprints()[0].peaks.schema)
789 mapper.addMinimalSchema(footprints.getFootprints()[0].peaks.schema)
790 mapper.addOutputField(
"significance", type=float,
791 doc=
"Ratio of peak value to configured standard deviation.")
796 newFootprints = afwDet.FootprintSet(footprints)
797 for old, new
in zip(footprints.getFootprints(), newFootprints.getFootprints()):
798 newPeaks = afwDet.PeakCatalog(mapper.getOutputSchema())
799 newPeaks.extend(old.peaks, mapper=mapper)
800 new.getPeaks().clear()
801 new.setPeakCatalog(newPeaks)
804 if self.config.thresholdType ==
"pixel_stdev":
805 for footprint
in newFootprints.getFootprints():
806 footprint.updatePeakSignificance(exposure.variance, polarity)
807 elif self.config.thresholdType ==
"stdev":
808 sigma = threshold.getValue() / self.config.thresholdValue
809 for footprint
in newFootprints.getFootprints():
810 footprint.updatePeakSignificance(polarity*sigma)
812 for footprint
in newFootprints.getFootprints():
813 for peak
in footprint.peaks:
814 peak[
"significance"] = 0
819 """Make an afw.detection.Threshold object corresponding to the task's
820 configuration and the statistics of the given image.
825 Image to measure noise statistics
from if needed.
826 thresholdParity: `str`
827 One of
"positive" or "negative", to set the kind of fluctuations
828 the Threshold will detect.
830 Factor by which to multiply the configured detection threshold.
831 This
is useful
for tweaking the detection threshold slightly.
838 parity = False if thresholdParity ==
"negative" else True
839 thresholdValue = self.config.thresholdValue
840 thresholdType = self.config.thresholdType
841 if self.config.thresholdType ==
'stdev':
842 bad = image.getMask().getPlaneBitMask(self.config.statsMask)
843 sctrl = afwMath.StatisticsControl()
844 sctrl.setAndMask(bad)
845 stats = afwMath.makeStatistics(image, afwMath.STDEVCLIP, sctrl)
846 thresholdValue *= stats.getValue(afwMath.STDEVCLIP)
847 thresholdType =
'value'
849 threshold = afwDet.createThreshold(thresholdValue*factor, thresholdType, parity)
850 threshold.setIncludeMultiplier(self.config.includeThresholdMultiplier)
851 self.log.debug(
"Detection threshold: %s", threshold)
855 """Update the Peaks in a FootprintSet by detecting new Footprints and
856 Peaks in an image
and using the new Peaks instead of the old ones.
861 Set of Footprints whose Peaks should be updated.
863 Image to detect new Footprints
and Peak
in.
865 Threshold object
for detection.
867 Input Footprints
with fewer Peaks than self.config.nPeaksMaxSimple
868 are
not modified,
and if no new Peaks are detected
in an input
869 Footprint, the brightest original Peak
in that Footprint
is kept.
871 for footprint
in fpSet.getFootprints():
872 oldPeaks = footprint.getPeaks()
873 if len(oldPeaks) <= self.config.nPeaksMaxSimple:
878 sub = image.Factory(image, footprint.getBBox())
879 fpSetForPeaks = afwDet.FootprintSet(
883 self.config.minPixels
885 newPeaks = afwDet.PeakCatalog(oldPeaks.getTable())
886 for fpForPeaks
in fpSetForPeaks.getFootprints():
887 for peak
in fpForPeaks.getPeaks():
888 if footprint.contains(peak.getI()):
889 newPeaks.append(peak)
890 if len(newPeaks) > 0:
892 oldPeaks.extend(newPeaks)
898 """Set the edgeBitmask bits for all of maskedImage outside goodBBox
903 Image on which to set edge bits in the mask.
905 Bounding box of good pixels,
in ``LOCAL`` coordinates.
907 Bit mask to OR
with the existing mask bits
in the region
908 outside ``goodBBox``.
910 msk = maskedImage.getMask()
912 mx0, my0 = maskedImage.getXY0()
913 for x0, y0, w, h
in ([0, 0,
914 msk.getWidth(), goodBBox.getBeginY() - my0],
915 [0, goodBBox.getEndY() - my0, msk.getWidth(),
916 maskedImage.getHeight() - (goodBBox.getEndY() - my0)],
918 goodBBox.getBeginX() - mx0, msk.getHeight()],
919 [goodBBox.getEndX() - mx0, 0,
920 maskedImage.getWidth() - (goodBBox.getEndX() - mx0), msk.getHeight()],
924 edgeMask |= edgeBitmask
928 """Context manager for removing wide (large-scale) background
930 Removing a wide (large-scale) background helps to suppress the
931 detection of large footprints that may overwhelm the deblender.
932 It does, however, set a limit on the maximum scale of objects.
934 The background that we remove will be restored upon exit from
940 Exposure on which to remove large-scale background.
944 context : context manager
945 Context manager that will ensure the temporary wide background
948 doTempWideBackground = self.config.doTempWideBackground
949 if doTempWideBackground:
950 self.log.info(
"Applying temporary wide background subtraction")
951 original = exposure.maskedImage.image.array[:].copy()
952 self.tempWideBackground.
run(exposure).background
955 image = exposure.maskedImage.image
956 mask = exposure.maskedImage.mask
957 noData = mask.array & mask.getPlaneBitMask(
"NO_DATA") > 0
958 isGood = mask.array & mask.getPlaneBitMask(self.config.statsMask) == 0
959 image.array[noData] = np.median(image.array[~noData & isGood])
963 if doTempWideBackground:
964 exposure.maskedImage.image.array[:] = original
968 """Add a set of exposures together.
973 Sequence of exposures to add.
978 An exposure of the same size as each exposure
in ``exposureList``,
979 with the metadata
from ``exposureList[0]``
and a masked image equal
980 to the sum of all the exposure
's masked images.
982 exposure0 = exposureList[0]
983 image0 = exposure0.getMaskedImage()
985 addedImage = image0.Factory(image0, True)
986 addedImage.setXY0(image0.getXY0())
988 for exposure
in exposureList[1:]:
989 image = exposure.getMaskedImage()
992 addedExposure = exposure0.Factory(addedImage, exposure0.getWcs())
def tempWideBackgroundContext(self, exposure)
def getPsf(self, exposure, sigma=None)
def __init__(self, schema=None, **kwds)
def makeThreshold(self, image, thresholdParity, factor=1.0)
def setPeakSignificance(self, exposure, footprints, threshold, negative=False)
def run(self, table, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None)
def convolveImage(self, maskedImage, psf, doSmooth=True)
def applyTempLocalBackground(self, exposure, middle, results)
def detectFootprints(self, exposure, doSmooth=True, sigma=None, clearMask=True, expId=None)
def reEstimateBackground(self, maskedImage, backgrounds)
def updatePeaks(self, fpSet, image, threshold)
def finalizeFootprints(self, mask, results, sigma, factor=1.0)
def setEdgeBits(maskedImage, goodBBox, edgeBitmask)
def clearUnwantedResults(self, mask, results)
def clearMask(self, mask)
def display(self, exposure, results, convolvedImage=None)
def applyThreshold(self, middle, bbox, factor=1.0)
def calculateKernelSize(self, sigma)
def addExposures(exposureList)