def testAssembly(self): ccdNames = ('R:0,0 S:1,0', 'R:0,0 S:0,1') compMap = { True: afwImage.ImageU(os.path.join(testPath, 'test_comp_trimmed.fits.gz')), False: afwImage.ImageU(os.path.join(testPath, 'test_comp.fits.gz')) } for cw in self.cameraList: camera = cw.camera imList = self.assemblyList[camera.getName()] for ccdName in ccdNames: for trim, assemble in ((False, assembleAmplifierRawImage), (True, assembleAmplifierImage)): det = camera[ccdName] if not trim: outBbox = cameraGeomUtils.calcRawCcdBBox(det) else: outBbox = det.getBBox() outImage = afwImage.ImageU(outBbox) if len(imList) == 1: for amp in det: assemble(outImage, imList[0], amp) else: for amp, im in zip(det, imList): assemble(outImage, im, amp) self.assertListEqual( outImage.getArray().flatten().tolist(), compMap[trim].getArray().flatten().tolist())
def testTransform(self): dims = lsst.geom.Extent2I(512, 512) bbox = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), dims) radius = 5 offset = lsst.geom.Extent2D(123, 456) crval = lsst.geom.SpherePoint(0, 0, lsst.geom.degrees) crpix = lsst.geom.Point2D(0, 0) cdMatrix = np.array([1.0e-5, 0.0, 0.0, 1.0e-5]) cdMatrix.shape = (2, 2) source = afwGeom.makeSkyWcs(crval=crval, crpix=crpix, cdMatrix=cdMatrix) target = afwGeom.makeSkyWcs(crval=crval, crpix=crpix + offset, cdMatrix=cdMatrix) sourceSpanSet = afwGeom.SpanSet.fromShape(radius, afwGeom.Stencil.CIRCLE) sourceSpanSet = sourceSpanSet.shiftedBy(12, 34) fpSource = afwDetect.Footprint(sourceSpanSet, bbox) fpTarget = fpSource.transform(source, target, bbox) self.assertEqual(len(fpSource.getSpans()), len(fpTarget.getSpans())) self.assertEqual(fpSource.getArea(), fpTarget.getArea()) imSource = afwImage.ImageU(dims) fpSource.spans.setImage(imSource, 1) imTarget = afwImage.ImageU(dims) fpTarget.spans.setImage(imTarget, 1) subSource = imSource.Factory(imSource, fpSource.getBBox()) subTarget = imTarget.Factory(imTarget, fpTarget.getBBox()) self.assertTrue(np.all(subSource.getArray() == subTarget.getArray())) # make a bbox smaller than the target footprint bbox2 = lsst.geom.Box2I(fpTarget.getBBox()) bbox2.grow(-1) fpTarget2 = fpSource.transform(source, target, bbox2) # this one clips fpTarget3 = fpSource.transform(source, target, bbox2, False) # this one doesn't self.assertTrue(bbox2.contains(fpTarget2.getBBox())) self.assertFalse(bbox2.contains(fpTarget3.getBBox())) self.assertNotEqual(fpTarget.getArea(), fpTarget2.getArea()) self.assertEqual(fpTarget.getArea(), fpTarget3.getArea()) # Test that peakCatalogs get Transformed correctly truthList = [(x, y, 10) for x, y in zip(range(-2, 2), range(-1, 3))] for value in truthList: fpSource.addPeak(*value) scaleFactor = 2 linTrans = lsst.geom.LinearTransform( np.array([[scaleFactor, 0], [0, scaleFactor]], dtype=float)) linTransFootprint = fpSource.transform(linTrans, fpSource.getBBox(), False) for peak, truth in zip(linTransFootprint.peaks, truthList): # Multiplied by two because that is the linear transform scaling # factor self.assertEqual(peak.getIx(), truth[0] * scaleFactor) self.assertEqual(peak.getIy(), truth[1] * scaleFactor)
def setUp(self): self.lsstCamWrapper = testUtils.CameraWrapper(isLsstLike=True) self.scCamWrapper = testUtils.CameraWrapper(isLsstLike=False) self.cameraList = (self.lsstCamWrapper, self.scCamWrapper) self.assemblyList = {} self.assemblyList[self.lsstCamWrapper.camera.getName()] =\ [afwImage.ImageU('tests/test_amp.fits.gz') for i in range(8)] self.assemblyList[self.scCamWrapper.camera.getName()] =\ [afwImage.ImageU('tests/test.fits.gz')]
def setUp(self): self.lsstCamWrapper = testUtils.CameraWrapper(isLsstLike=True) self.scCamWrapper = testUtils.CameraWrapper(isLsstLike=False) self.cameraList = (self.lsstCamWrapper, self.scCamWrapper) self.assemblyList = {} self.assemblyList[self.lsstCamWrapper.camera.getName()] =\ [afwImage.ImageU(os.path.join(testPath, 'test_amp.fits.gz')) for i in range(8)] self.assemblyList[self.scCamWrapper.camera.getName()] =\ [afwImage.ImageU(os.path.join(testPath, 'test.fits.gz'), allowUnsafe=True)]
def testNormalize(self): """Test Footprint.normalize""" w, h = 12, 10 region = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(w, h)) im = afwImage.ImageU(afwGeom.Extent2I(w, h)) im.set(0) # # Create a footprint; note that these Spans overlap # for spans, box in (([ (3, 5, 6), (4, 7, 7), ], afwGeom.Box2I(afwGeom.Point2I(5, 3), afwGeom.Point2I(7, 4))), ([ (3, 3, 5), (3, 6, 9), (4, 2, 3), (4, 5, 7), (4, 8, 8), (5, 2, 3), (5, 5, 8), (5, 6, 7), (6, 3, 5), ], afwGeom.Box2I(afwGeom.Point2I(2, 3), afwGeom.Point2I(9, 6)))): foot = afwDetect.Footprint(0, region) for y, x0, x1 in spans: foot.addSpan(y, x0, x1) for x in range(x0, x1 + 1): # also insert into im im.set(x, y, 1) idImage = afwImage.ImageU(afwGeom.Extent2I(w, h)) idImage.set(0) foot.insertIntoImage(idImage, 1) if display: # overlaping pixels will be > 1 ds9.mtv(idImage) # # Normalise the Footprint, removing overlapping spans # foot.normalize() idImage.set(0) foot.insertIntoImage(idImage, 1) if display: ds9.mtv(idImage, frame=1) idImage -= im self.assertTrue(box == foot.getBBox()) self.assertEqual( afwMath.makeStatistics(idImage, afwMath.MAX).getValue(), 0)
def testFootprintFromEllipse(self): """Create an elliptical Footprint""" cen = afwGeom.Point2D(23, 25) a, b, theta = 25, 15, 30 ellipse = afwGeomEllipses.Ellipse(afwGeomEllipses.Axes(a, b, math.radians(theta)), cen) foot = afwDetect.Footprint(ellipse, afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(50, 60))) idImage = afwImage.ImageU(afwGeom.Extent2I(foot.getRegion().getWidth(), foot.getRegion().getHeight())) idImage.set(0) foot.insertIntoImage(idImage, foot.getId()) if display: ds9.mtv(idImage, frame=2) displayUtils.drawFootprint(foot, frame=2) shape = foot.getShape() shape.scale(2) # <r^2> = 1/2 for a disk ds9.dot(shape, *cen, frame=2, ctype=ds9.RED) shape = foot.getShape() shape.scale(2) # <r^2> = 1/2 for a disk ds9.dot(shape, *cen, frame=2, ctype=ds9.MAGENTA) axes = afwGeom.ellipses.Axes(foot.getShape()) axes.scale(2) # <r^2> = 1/2 for a disk self.assertEqual(foot.getCentroid(), cen) self.assertTrue(abs(a - axes.getA()) < 0.15, "a: %g v. %g" % (a, axes.getA())) self.assertTrue(abs(b - axes.getB()) < 0.02, "b: %g v. %g" % (b, axes.getB())) self.assertTrue(abs(theta - math.degrees(axes.getTheta())) < 0.2, "theta: %g v. %g" % (theta, math.degrees(axes.getTheta())))
def flag(self, flag, exposure, flat): assert exposure, "exposure not provided" assert flat, "flat not provided" mi = exposure.getMaskedImage() dims = mi.getDimensions() if flag is None: flag = afwImage.ImageU(dims) image = mi.getImage() image /= flat.getImage() stats = afwMath.makeStatistics(image, mi.getMask(), afwMath.MEDIAN | afwMath.STDEVCLIP, afwMath.StatisticsControl()) median = stats.getValue(afwMath.MEDIAN) stdev = stats.getValue(afwMath.STDEVCLIP) self.log.log(self.log.INFO, "Background: %f +/- %f" % (median, stdev)) flag += threshold(image, median + self._threshold * stdev, True, log=self.log) flag += threshold(image, median - self._threshold * stdev, False, log=self.log) return flag
def mtv(self, data, title="", wcs=None): """!Display an Image or Mask on a DISPLAY display Historical note: the name "mtv" comes from Jim Gunn's forth imageprocessing system, Mirella (named after Mirella Freni); The "m" stands for Mirella. """ if hasattr(data, "getXY0"): self._xy0 = data.getXY0() else: self._xy0 = None if re.search("::Exposure<", repr(data)): # it's an Exposure; display the MaskedImage with the WCS if wcs: raise RuntimeError, "You may not specify a wcs with an Exposure" data, wcs = data.getMaskedImage(), data.getWcs() elif re.search("::DecoratedImage<", repr(data)): # it's a DecoratedImage; display it data, wcs = data.getImage(), afwImage.makeWcs(data.getMetadata()) self._xy0 = data.getXY0() # DecoratedImage doesn't have getXY0() if re.search("::Image<", repr(data)): # it's an Image; display it self._impl._mtv(data, None, wcs, title) elif re.search("::Mask<", repr(data)): # it's a Mask; display it, bitplane by bitplane # # Some displays can't display a Mask without an image; so display an Image too, # with pixel values set to the mask # self._impl._mtv(afwImage.ImageU(data.getArray()), data, wcs, title) elif re.search("::MaskedImage<", repr(data)): # it's a MaskedImage; display Image and overlay Mask self._impl._mtv(data.getImage(), data.getMask(True), wcs, title) else: raise RuntimeError, "Unsupported type %s" % repr(data)
def testMakeRGBU(self): """Test the function that does it all works with unsigned short images""" rgbImages = [afwImage.ImageU(_.getArray().astype('uint16')) for _ in [ self.images[R], self.images[G], self.images[B]]] assert "imageLib.ImageU" in repr(rgbImages[0]) # check that ImageU is supported rgbImage = rgb.makeRGB(*rgbImages, minimum=self.min, range=self.range, Q=self.Q)
def threshold(image, threshold, positive, log=None): thresh = afwDet.createThreshold(threshold, "value", positive) feet = afwDet.makeFootprintSet(image, thresh) if log is not None: log.log(log.INFO, "Found %d footprints" % len(feet.getFootprints())) pixels = afwImage.ImageU(image.getDimensions()) pixels.set(0) for foot in feet.getFootprints(): foot.insertIntoImage(pixels, 1) return pixels
def testAssembly(self): ccdNames = ('R:0,0 S:1,0', 'R:0,0 S:0,1') detectorImageMap = {True: afwImage.ImageU(os.path.join(testPath, 'test_comp_trimmed.fits.gz'), allowUnsafe=True), False: afwImage.ImageU(os.path.join(testPath, 'test_comp.fits.gz'), allowUnsafe=True)} for cw in self.cameraList: camera = cw.camera imList = self.assemblyList[camera.getName()] for ccdName in ccdNames: det = camera[ccdName] if len(imList) == 1: # There's one test image because it's the same for all # amplifiers, not because there's only one amplifier. imList *= len(det) # Test going from possibly-separate amp images to detector # images. for trim, assemble in ((False, assembleAmplifierRawImage), (True, assembleAmplifierImage)): if not trim: outBbox = cameraGeomUtils.calcRawCcdBBox(det) else: outBbox = det.getBBox() outImage = afwImage.ImageU(outBbox) for amp, im in zip(det, imList): assemble(outImage, im, amp) self.assertImagesEqual(outImage, detectorImageMap[trim]) # Test going from detector images back to single-amplifier # images. detector_exposure = afwImage.ExposureU(afwImage.MaskedImageU(detectorImageMap[trim])) detector_exposure.setDetector(makeUpdatedDetector(det)) for amp, im in zip(det, imList): amp_exposure = AmplifierIsolator.apply(detector_exposure, amp) self.assertEqual(len(amp_exposure.getDetector()), 1) self.assertEqual(amp_exposure.getDetector().getBBox(), amp.getBBox()) self.assertAmplifiersEqual(amp, amp_exposure.getDetector()[0]) if not trim: self.assertEqual(cameraGeomUtils.calcRawCcdBBox(amp_exposure.getDetector()), amp_exposure.getBBox()) self.assertImagesEqual(im[amp.getRawBBox()], amp_exposure.image) else: self.assertEqual(amp_exposure.getDetector().getBBox(), amp_exposure.getBBox()) self.assertImagesEqual(im[amp.getRawDataBBox()], amp_exposure.image)
def testGrow(self): """Test growing a footprint""" x0, y0 = 20, 20 width, height = 20, 30 foot1 = afwDetect.Footprint(afwGeom.Box2I(afwGeom.Point2I(x0, y0), afwGeom.Extent2I(width, height)), afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(100, 100))) # Add some peaks and check that they get copied into the new grown footprint foot1.addPeak(20, 20, 1) foot1.addPeak(30, 35, 2) foot1.addPeak(25, 45, 3) self.assertEqual(len(foot1.getPeaks()), 3) bbox1 = foot1.getBBox() self.assertEqual(bbox1.getMinX(), x0) self.assertEqual(bbox1.getMaxX(), x0 + width - 1) self.assertEqual(bbox1.getWidth(), width) self.assertEqual(bbox1.getMinY(), y0) self.assertEqual(bbox1.getMaxY(), y0 + height - 1) self.assertEqual(bbox1.getHeight(), height) ngrow = 5 for isotropic in (True, False): foot2 = afwDetect.growFootprint(foot1, ngrow, isotropic) # Check that peaks got copied into grown footprint self.assertEqual(len(foot2.getPeaks()), 3) for peak in foot2.getPeaks(): self.assertTrue((peak.getIx(), peak.getIy()) in [(20, 20), (30, 35), (25, 45)]) bbox2 = foot2.getBBox() if False and display: idImage = afwImage.ImageU(width, height) idImage.set(0) i = 1 for foot in [foot1, foot2]: foot.insertIntoImage(idImage, i) i += 1 metricImage = afwImage.ImageF("foo.fits") ds9.mtv(metricImage, frame=1) ds9.mtv(idImage) # check bbox2 self.assertEqual(bbox2.getMinX(), x0 - ngrow) self.assertEqual(bbox2.getWidth(), width + 2*ngrow) self.assertEqual(bbox2.getMinY(), y0 - ngrow) self.assertEqual(bbox2.getHeight(), height + 2*ngrow) # Check that region was preserved self.assertEqual(foot1.getRegion(), foot2.getRegion())
def testFootprintFromCircle(self): """Create an elliptical Footprint""" ellipse = afwGeomEllipses.Ellipse(afwGeomEllipses.Axes(6, 6, 0), afwGeom.Point2D(9,15)) foot = afwDetect.Footprint(ellipse, afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(20, 30))) idImage = afwImage.ImageU(afwGeom.Extent2I(foot.getRegion().getWidth(), foot.getRegion().getHeight())) idImage.set(0) foot.insertIntoImage(idImage, foot.getId()) if False: ds9.mtv(idImage, frame=2)
def testMergeFootprints(self): f1 = self.foot f2 = afwDetect.Footprint() spanList1 = [(10, 10, 20), (10, 30, 40), (10, 50, 60), (11, 30, 50), (12, 30, 50), (13, 10, 20), (13, 30, 40), (13, 50, 60), (15, 10, 20), (15, 31, 40), (15, 51, 60)] spanSet1 = afwGeom.SpanSet([afwGeom.Span(*span) for span in spanList1]) f1.spans = spanSet1 spanList2 = [(8, 10, 20), (9, 20, 30), (10, 0, 9), (10, 35, 65), (10, 70, 80), (13, 49, 54), (14, 10, 30), (15, 21, 30), (15, 41, 50), (15, 61, 70)] spanSet2 = afwGeom.SpanSet([afwGeom.Span(*span) for span in spanList2]) f2.spans = spanSet2 fA = afwDetect.mergeFootprints(f1, f2) fB = afwDetect.mergeFootprints(f2, f1) ims = [] for i, f in enumerate([f1, f2, fA, fB]): im1 = afwImage.ImageU(100, 100) im1.set(0) imbb = im1.getBBox() f.setRegion(imbb) f.spans.setImage(im1, 1) ims.append(im1) for i, merged in enumerate([ims[2], ims[3]]): m = merged.getArray() a1 = ims[0].getArray() a2 = ims[1].getArray() # Slightly looser tests to start... # Every pixel in f1 is in f[AB] self.assertTrue(np.all(m.flat[np.flatnonzero(a1)] == 1)) # Every pixel in f2 is in f[AB] self.assertTrue(np.all(m.flat[np.flatnonzero(a2)] == 1)) # merged == a1 | a2. self.assertTrue(np.all(m == np.maximum(a1, a2))) if False: import matplotlib matplotlib.use('Agg') import pylab as plt plt.clf() for i, im1 in enumerate(ims): plt.subplot(4, 1, i + 1) plt.imshow(im1.getArray(), interpolation='nearest', origin='lower') plt.axis([0, 100, 0, 20]) plt.savefig('merge2.png')
def testStarsResizeToSize(self): """Test creating an RGB image of a specified size""" xSize = self.images[R].getWidth()//2 ySize = self.images[R].getHeight()//2 for rgbImages in ([self.images[R], self.images[G], self.images[B]], [afwImage.ImageU(_.getArray().astype('uint16')) for _ in [ self.images[R], self.images[G], self.images[B]]]): rgbImage = rgb.AsinhZScaleMapping(rgbImages[0]).makeRgbImage(*rgbImages, xSize=xSize, ySize=ySize) if display: rgb.displayRGB(rgbImage)
def testTransform(self): dims = afwGeom.Extent2I(512, 512) bbox = afwGeom.Box2I(afwGeom.Point2I(0, 0), dims) radius = 5 offset = afwGeom.Extent2D(123, 456) crval = afwCoord.Coord(0 * afwGeom.degrees, 0 * afwGeom.degrees) crpix = afwGeom.Point2D(0, 0) cdMatrix = [1.0e-5, 0.0, 0.0, 1.0e-5] source = afwImage.makeWcs(crval, crpix, *cdMatrix) target = afwImage.makeWcs(crval, crpix + offset, *cdMatrix) fpSource = afwDetect.Footprint(afwGeom.Point2I(12, 34), radius, bbox) fpTarget = fpSource.transform(source, target, bbox) self.assertEqual(len(fpSource.getSpans()), len(fpTarget.getSpans())) self.assertEqual(fpSource.getNpix(), fpTarget.getNpix()) self.assertEqual(fpSource.getArea(), fpTarget.getArea()) imSource = afwImage.ImageU(dims) fpSource.insertIntoImage(imSource, 1) imTarget = afwImage.ImageU(dims) fpTarget.insertIntoImage(imTarget, 1) subSource = imSource.Factory(imSource, fpSource.getBBox()) subTarget = imTarget.Factory(imTarget, fpTarget.getBBox()) self.assertTrue( numpy.all(subSource.getArray() == subTarget.getArray())) # make a bbox smaller than the target footprint bbox2 = afwGeom.Box2I(fpTarget.getBBox()) bbox2.grow(-1) fpTarget2 = fpSource.transform(source, target, bbox2) # this one clips fpTarget3 = fpSource.transform(source, target, bbox2, False) # this one doesn't self.assertTrue(bbox2.contains(fpTarget2.getBBox())) self.assertFalse(bbox2.contains(fpTarget3.getBBox())) self.assertNotEqual(fpTarget.getArea(), fpTarget2.getArea()) self.assertEqual(fpTarget.getArea(), fpTarget3.getArea())
def setUp(self): self.im = afwImage.ImageU(lsst.geom.Extent2I(12, 8)) # # Objects that we should detect # self.objects = [] self.objects += [Object(10, [(1, 4, 4), (2, 3, 5), (3, 4, 4)])] self.objects += [Object(20, [(5, 7, 8), (5, 10, 10), (6, 8, 9)])] self.objects += [Object(20, [(6, 3, 3)])] self.im.set(0) # clear image for obj in self.objects: obj.insert(self.im)
def testGrow(self): """Test growing a footprint""" x0, y0 = 20, 20 width, height = 20, 30 foot1 = afwDetect.Footprint( afwGeom.Box2I(afwGeom.Point2I(x0, y0), afwGeom.Extent2I(width, height)), afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(100, 100))) bbox1 = foot1.getBBox() self.assertEqual(bbox1.getMinX(), x0) self.assertEqual(bbox1.getMaxX(), x0 + width - 1) self.assertEqual(bbox1.getWidth(), width) self.assertEqual(bbox1.getMinY(), y0) self.assertEqual(bbox1.getMaxY(), y0 + height - 1) self.assertEqual(bbox1.getHeight(), height) ngrow = 5 for isotropic in (True, False): foot2 = afwDetect.growFootprint(foot1, ngrow, isotropic) # Check that the grown footprint is normalized self.assertTrue(foot2.isNormalized()) # Check that the grown footprint is bigger than the original self.assertGreater(foot2.getArea(), foot1.getArea()) bbox2 = foot2.getBBox() if False and display: idImage = afwImage.ImageU(width, height) idImage.set(0) i = 1 for foot in [foot1, foot2]: foot.insertIntoImage(idImage, i) i += 1 metricImage = afwImage.ImageF("foo.fits") ds9.mtv(metricImage, frame=1) ds9.mtv(idImage) # check bbox2 self.assertEqual(bbox2.getMinX(), x0 - ngrow) self.assertEqual(bbox2.getWidth(), width + 2 * ngrow) self.assertEqual(bbox2.getMinY(), y0 - ngrow) self.assertEqual(bbox2.getHeight(), height + 2 * ngrow) # Check that region was preserved self.assertEqual(foot1.getRegion(), foot2.getRegion())
def bypass_defects(self, datasetType, pythonType, butlerLocation, dataId): """Return a defect list based on butlerLocation returned by map_defects. Use all nonzero pixels in the Community Pipeline Bad Pixel Masks. @param[in] butlerLocation: Butler Location with path to defects FITS @param[in] dataId: data identifier @return meas.algorithms.DefectListT """ bpmFitsPath = butlerLocation.getLocationsWithRoot()[0] bpmImg = afwImage.ImageU(bpmFitsPath) idxBad = np.nonzero(bpmImg.getArray()) mim = afwImage.MaskedImageU(bpmImg.getDimensions()) mim.getMask().getArray()[idxBad] |= mim.getMask().getPlaneBitMask("BAD") return isr.getDefectListFromMask(mim, "BAD", growFootprints=0)
def setUp(self): self.im = afwImage.ImageU(afwGeom.Extent2I(12, 8)) # # Objects that we should detect # self.objects = [] self.objects += [Object(10, [(1, 4, 4), (2, 3, 5), (3, 4, 4)])] self.objects += [Object(20, [(5, 7, 8), (5, 10, 10), (6, 8, 9)])] self.objects += [Object(20, [(6, 3, 3)])] self.im.set(0) # clear image for obj in self.objects: obj.insert(self.im) if False and display: ds9.mtv(self.im, frame=0)
def testString(self): imageF = afwImage.ImageF(100, 100) imageDSmall = afwImage.ImageD(2, 2) imageISmall = afwImage.ImageI(2, 2) imageU = afwImage.ImageU(100, 100) # NumPy's string representation varies depending on the size of the # array; we test both large and small. self.assertIn(str(np.zeros((100, 100), dtype=imageF.dtype)), str(imageF)) self.assertIn("bbox=%s" % str(imageF.getBBox()), str(imageF)) self.assertIn(str(np.zeros((2, 2), dtype=imageDSmall.dtype)), str(imageDSmall)) self.assertIn(str(np.zeros((2, 2), dtype=imageISmall.dtype)), str(imageISmall)) self.assertIn("ImageF=", repr(imageF)) self.assertIn("ImageU=", repr(imageU))
def testGrow2(self): """Grow some more interesting shaped Footprints. Informative with display, but no numerical tests""" ds = afwDetect.FootprintSet(self.ms, afwDetect.Threshold(10), "OBJECT") idImage = afwImage.ImageU(self.ms.getDimensions()) idImage.set(0) i = 1 for foot in ds.getFootprints()[0:1]: gfoot = afwDetect.growFootprint(foot, 3, False) gfoot.insertIntoImage(idImage, i) i += 1 if display: ds9.mtv(self.ms, frame=0) ds9.mtv(idImage, frame=1)
def testFootprintsImageId(self): """Check that we can insert footprints into an Image""" ds = afwDetect.FootprintSet(self.ms, afwDetect.Threshold(10)) objects = ds.getFootprints() idImage = afwImage.ImageU(self.ms.getDimensions()) idImage.set(0) for i, foot in enumerate(objects): foot.spans.setImage(idImage, i + 1) for i in range(len(objects)): for sp in objects[i].getSpans(): for x in range(sp.getX0(), sp.getX1() + 1): self.assertEqual(idImage[x, sp.getY(), afwImage.LOCAL], i + 1)
def testGrow2(self): """Grow some more interesting shaped Footprints. Informative with display, but no numerical tests""" ds = afwDetect.FootprintSet(self.ms, afwDetect.Threshold(10), "OBJECT") idImage = afwImage.ImageU(self.ms.getDimensions()) idImage.set(0) i = 1 for foot in ds.getFootprints()[0:1]: foot.dilate(3, afwGeom.Stencil.MANHATTAN) foot.spans.setImage(idImage, i, doClip=True) i += 1 if display: ds9.mtv(self.ms, frame=0) ds9.mtv(idImage, frame=1)
def _fig8Test(self, x1, y1, x2, y2): # Construct a "figure of 8" consisting of two circles touching at the # centre of an image, then demonstrate that it shrinks correctly. # (Helper method for tests below.) radius = 3 imwidth, imheight = 100, 100 nshrink = 1 # These are the correct values for footprint sizes given the paramters # above. circle_npix = 29 initial_npix = circle_npix * 2 - 1 # touch at one pixel shrunk_npix = 26 box = lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Extent2I(imwidth, imheight)) e1 = afwGeom.Ellipse(afwGeomEllipses.Axes(radius, radius, 0), lsst.geom.Point2D(x1, y1)) spanSet1 = afwGeom.SpanSet.fromShape(e1) f1 = afwDetect.Footprint(spanSet1, box) self.assertEqual(f1.getArea(), circle_npix) e2 = afwGeom.Ellipse(afwGeomEllipses.Axes(radius, radius, 0), lsst.geom.Point2D(x2, y2)) spanSet2 = afwGeom.SpanSet.fromShape(e2) f2 = afwDetect.Footprint(spanSet2, box) self.assertEqual(f2.getArea(), circle_npix) initial = afwDetect.mergeFootprints(f1, f2) initial.setRegion( f2.getRegion()) # merge does not propagate the region self.assertEqual(initial_npix, initial.getArea()) shrunk = afwDetect.Footprint().assign(initial) shrunk.erode(nshrink) self.assertEqual(shrunk_npix, shrunk.getArea()) if display: idImage = afwImage.ImageU(imwidth, imheight) for i, foot in enumerate([initial, shrunk]): print(foot.getArea()) foot.spans.setImage(idImage, i + 1) afwDisplay.Display(frame=1).mtv(idImage, title=self._testMethodName + " image")
def testFootprintToBBoxList(self): """Test footprintToBBoxList""" region = afwGeom.Box2I(afwGeom.Point2I(0, 0), afwGeom.Extent2I(12, 10)) foot = afwDetect.Footprint(0, region) for y, x0, x1 in [ (3, 3, 5), (3, 7, 7), (4, 2, 3), (4, 5, 7), (5, 2, 3), (5, 5, 8), (6, 3, 5), ]: foot.addSpan(y, x0, x1) idImage = afwImage.ImageU(region.getDimensions()) idImage.set(0) foot.insertIntoImage(idImage, 1) if display: ds9.mtv(idImage) idImageFromBBox = idImage.Factory(idImage, True) idImageFromBBox.set(0) bboxes = afwDetect.footprintToBBoxList(foot) for bbox in bboxes: x0, y0, x1, y1 = bbox.getMinX(), bbox.getMinY(), bbox.getMaxX( ), bbox.getMaxY() for y in range(y0, y1 + 1): for x in range(x0, x1 + 1): idImageFromBBox.set(x, y, 1) if display: x0 -= 0.5 y0 -= 0.5 x1 += 0.5 y1 += 0.5 ds9.line([(x0, y0), (x1, y0), (x1, y1), (x0, y1), (x0, y0)], ctype=ds9.RED) idImageFromBBox -= idImage # should be blank stats = afwMath.makeStatistics(idImageFromBBox, afwMath.MAX) self.assertEqual(stats.getValue(), 0)
def testGrow2(self): """Grow some more interesting shaped Footprints. Informative with display, but no numerical tests""" # Can't set mask plane as the image is not a masked image. ds = afwDetect.FootprintSet(self.im, afwDetect.Threshold(10)) idImage = afwImage.ImageU(self.im.getDimensions()) idImage.set(0) i = 1 for foot in ds.getFootprints()[0:1]: foot.dilate(3, afwGeom.Stencil.MANHATTAN) foot.spans.setImage(idImage, i, doClip=True) i += 1 if display: afwDisplay.Display(frame=1).mtv(idImage, title=self._testMethodName + " image")
def setUp(self): self.im = afwImage.ImageU(lsst.geom.Extent2I(12, 8)) # # Objects that we should detect # self.objects = [] self.objects += [Object(10, [(1, 4, 4), (2, 3, 5), (3, 4, 4)])] self.objects += [Object(20, [(5, 7, 8), (5, 10, 10), (6, 8, 9)])] self.objects += [Object(20, [(6, 3, 3)])] self.im.set(0) # clear image for obj in self.objects: obj.insert(self.im) if False and display: afwDisplay.Display(frame=0).mtv(self.im, title=self._testMethodName + " image")
def testFootprintFromCircle(self): """Create an elliptical Footprint""" ellipse = afwGeom.Ellipse(afwGeomEllipses.Axes(6, 6, 0), lsst.geom.Point2D(9, 15)) spanSet = afwGeom.SpanSet.fromShape(ellipse) foot = afwDetect.Footprint(spanSet, lsst.geom.Box2I(lsst.geom.Point2I(0, 0), lsst.geom.Extent2I(20, 30))) idImage = afwImage.ImageU( lsst.geom.Extent2I(foot.getRegion().getWidth(), foot.getRegion().getHeight())) idImage.set(0) foot.spans.setImage(idImage, foot.getId()) if False: ds9.mtv(idImage, frame=2)
def testFootprintsImageId(self): """Check that we can insert footprints into an Image""" ds = afwDetect.FootprintSet(self.ms, afwDetect.Threshold(10)) objects = ds.getFootprints() idImage = afwImage.ImageU(self.ms.getDimensions()) idImage.set(0) for foot in objects: foot.insertIntoImage(idImage, foot.getId()) if False: ds9.mtv(idImage, frame=2) for i in range(len(objects)): for sp in objects[i].getSpans(): for x in range(sp.getX0(), sp.getX1() + 1): self.assertEqual(idImage.get(x, sp.getY()), objects[i].getId())