-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCentroid.py
More file actions
667 lines (579 loc) · 25.9 KB
/
Centroid.py
File metadata and controls
667 lines (579 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
from __future__ import division, absolute_import, print_function, unicode_literals
"""Measure centroids.
Note: as with all PyGuide routines, the coordinate system origin
is specified by PosMinusIndex.
Warnings:
- Will be thrown off by hot pixels. This could perhaps
be improved by centroiding median-filtered data. The question
is whether the median filtering would adversely affect
centroids, especially for faint objects. This is especially
a concern because at present I have no code to do a proper
median filter of masked data.
- The measure of asymmetry is supposed to be normalized,
but it gets large for bright objects with lots of masked pixels.
This may be simply because the value is only computed at the nearest
integer pixel or because the noise is assumed gaussian, or some error.
How it works:
1) Verify that there is usable signal (optional):
- Measure median and standard deviation of background
- Look for connected regions with value > med + (std dev * thresh);
if no such regions at least 2x2 in size are found
within a circle of radius rad centered at xyGuess
then reject the field with "No stars found".
2) Centroid the object (done in basicCentroid):
- The centroid is the point of mimimum radial asymmetry:
sum over rad of var(rad)^2 / weight(rad)
where weight is the expected sigma of var(rad) due to pixel noise:
weight(rad) = pixNoise(rad) * sqrt(2(numPix(rad) - 1))/numPix(rad)
pixNoise(rad) = sqrt((readNoise/ccdGain)^2 + (meanVal(rad)-bias)/ccdGain)
- The minimum is found in two stages:
a) Find the pixel with the minimum radAsymm.
The direction to walk is determined by measuring radAsymm at 9 points.
Each step is one pixel along x and/or y.
b) Find the true centroid (to better than one pixel) by applying
a quadratic fit to the 3x3 radAsymm matrix centered on the
pixel of minimum radAsymm. Only the points along +/-x and +/-y
are used for this fit; the diagonals are ignored.
3) Conform that there is usable signal (optional):
- This is just like step 1 but is performed at the final centroid position.
This makes sure the centroider has not wandered off into a region of bad signal.
It also allows us to return background statistics for the region about the star.
To do:
- Improve the estimate of centroid error.
Acknowledgements:
- The centroiding algorithm was invented by Jim Gunn
- The code uses a new asymmetry weighting function developed with help from Connie Rockosi
- This code is adapted from the SDSS centroiding code, which was written by Jim Gunn
and cleaned up by Connie Rockosi.
History:
2004-03-22 ROwen First release.
2004-04-07 ROwen Packaged as part of PyGuide and moved test code elsewhere.
Also changed array data types to match changes in radProf.
2004-04-12 ROwen Modified centroid to return totCounts.
2004-04-16 ROwen Modified centroid to not return minAsymm.
2004-04-30 ROwen Modified to truncate initGuess (i.e. anywhere within a pixel
selects that pixel) and round radius to the nearest integer.
Bug fix: was converting to Int16 instead of UInt16.
2004-06-03 ROwen Modified to use the initial guess without modification.
2004-08-03 ROwen Finally added a measure of centroiding error.
2004-08-06 ROwen Weight asymmetry calculation by radial noise.
2004-08-25 ROwen Added _MinRad, to more reliably centroid small stars.
Added __all__.
2004-10-14 ROwen Stopped computing several unused variables. Improved import of radProf.
2005-02-07 ROwen Changed centroid initGuess (i,j) argument to xyGuess.
Changed returned Centroid data object fields ctr (i,j) to xyCtr, err (i,j) to xyErr.
2005-03-31 ROwen Improved debug output and the efficiency of the "walked too far" test.
Noted that rad in CentroidData is integer.
2005-04-01 ROwen Modified to use round to round the radius instead of adding 0.5 and truncating.
2005-04-11 CLoomis Added ds9 flag (as per FindStars).
2005-05-18 ROwen Major overhaul to make sure centroid has usable signal:
- Modified centroid to measure usable signal.
- Renamed old centroid to basicCentroid
and modified it to count saturated pixels.
- Replaced bias, etc. with ccdInfo, a PyGuide.CCDInfo object.
- Renamed ds9 argument to doDS9.
- Default thresh is now set by Constants.DefThresh.
- Added verbosity argument, which replaces _CTRDEBUG and _CTRITERDBUG.
- Added isOK, msgStr and imStats fields to CentroidData.
- Both basicCentroid and centroid now always return normally
unless some serious internal error occurs;
if centroiding fails then centroidData.isOK is False.
2005-05-20 ROwen Added checkSignal method.
Rewrite centroid to check for usable signal first, then centroid,
then check signal again. Both signal checks are optional
The second check avoids trouble when centroid walks into a region of pure noise.
Bug fix: conditionMask was mis-handling mask=None.
Modified centroid to use conditionData and conditionMask.
Stopped auto-tiling frames for doDS9.
2005-10-14 ROwen Added satMask argument to centroid and basicCentroid;
they now ignore ccdInfo.satLevel.
Modified to use Float32 omage data instead of UInt16.
2006-04-06 ROwen CentroidData: stores null ImUtil.ImStats instance if imStats=None.
checkSignal:
- bug fix: sometimes returned the wrong thing
- improved compatibility when the subregion has no pixels
2006-04-17 ROwen Ditch unused "import warnings" (thanks to pychecker).
2008-01-12 ROwen Added doSmooth flag to the centroid function, as suggested by Adam Ginsburg.
2009-11-20 ROwen Modified to use numpy.
"""
__all__ = ['CentroidData', 'centroid',]
import math
import sys
import traceback
import numpy
import numpy.ma
import scipy.ndimage
from .Constants import DefThresh
from . import ImUtil
from . import radProf
def _fmtList(alist):
"""Return "alist[0], alist[1], ..."
"""
return str(alist)[1:-1]
# parameters
_MinRad = 3.0 # minimum radius
_OuterRadAdd = 10 # amount to add to rad to get outerRad
_MaxIter = 40 # max # of iterations
_MinPixForStats = 20 # minimum # of pixels needed to measure med and std dev
class CentroidData(object):
"""Centroid data, including the following fields:
flags; check before paying attention to the remaining data:
- isOK if False then centroiding failed; see msgStr for more info
- msgStr warning or error message, if any
- nSat number of saturated pixels; None if unknown
basic info:
- rad radius for centroid search (pix)
- imStats image statistics such as median and std. dev. (if known); an ImUtil.ImStats object.
star data:
- xyCtr the x,y centroid (pixels); None if unspecified
- xyErr the predicted 1-sigma uncertainty in xyCtr (pixels); [nan, nan] if unspecified
note: the following three values are computed for that radial profile
centered on the pixel nearest the centroid (NOT the true centroid):
- asymm measure of asymmetry:
sum over rad of var(rad)^2 / weight(rad)
where weight is the expected sigma of var(rad) due to pixel noise:
weight(rad) = pixNoise(rad) * sqrt(2(numPix(rad) - 1))/numPix(rad)
pixNoise(rad) = sqrt((readNoise/ccdGain)^2 + (meanVal(rad)-bias)/ccdGain)
- pix the total number of unmasked pixels (ADU)
- counts the total number of counts (ADU)
Warning: asymm is supposed to be normalized, but it gets large
for bright objects with lots of masked pixels. This may be
simply because the value is only computed at the nearest integer pixel
or because the noise is assumed gaussian, or some error.
Suggested use:
- check isOK; if False do not use the data
- check nSat(); if not None and more than a few then be cautious in using the data
(I don't know how sensitive centroid accuracy is to # of saturated pixels)
"""
def __init__(self,
isOK = True,
msgStr = "",
nSat = None,
rad = None,
imStats = None,
xyCtr = None,
xyErr = None,
asymm = None,
pix = None,
counts = None,
):
self.isOK = isOK
self.msgStr = msgStr
self.nSat = nSat
self.rad = rad
if imStats is None:
imStats = ImUtil.ImStats()
self.imStats = imStats
self.xyCtr = xyCtr
if xyErr is None:
xyErr = numpy.array([numpy.nan, numpy.nan])
self.xyErr = xyErr
self.asymm = asymm
self.pix = pix
self.counts = counts
def __repr__(self):
dataList = []
for arg in ("isOK", "msgStr", "nSat", "xyCtr", "xyErr", "asymm", "pix", "counts", "rad", "imStats"):
val = getattr(self, arg)
if val not in (None, ""):
dataList.append("%s=%s" % (arg, val))
return "%s(%s)" % (self.__class__.__name__, ", ".join(dataList))
def basicCentroid(
data,
mask,
satMask,
xyGuess,
rad,
ccdInfo,
verbosity = 0,
doDS9 = False,
):
"""Compute a centroid.
Inputs:
- data image data [i,j]
- mask a mask of invalid data (1 if invalid, 0 if valid); None if no mask.
- satMask a maks of of saturated pixels (1 if saturated, 0 if not); None if no mask.
- xyGuess initial x,y guess for centroid
- rad radius of search (pixels);
values less than _MinRad are treated as _MinRad
- ccdInfo ccd bias, gain, etc.; a PyGuide.CCDInfo object
- verbosity 0: no output, 1: print warnings, 2: print information,
3: print basic iteration info, 4: print detailed iteration info.
Note: there are no warnings at this time because the relevant info is returned.
- doDS9 if True, diagnostic images are displayed in ds9
Masks are optional. If specified, they must be the same shape as "data"
and should be of type Bool. None means no mask (all data is OK).
Returns a CentroidData object (which see for more info),
but with no imStats info.
"""
if verbosity > 1:
print("basicCentroid(xyGuess=%s, rad=%s, ccdInfo=%s)" % (xyGuess, rad, ccdInfo))
# condition and check inputs
data = conditionData(data)
mask = conditionMask(mask)
satMask = conditionMask(satMask)
if len(xyGuess) != 2:
raise ValueError("initial guess=%r must have 2 elements" % (xyGuess,))
rad = int(round(max(rad, _MinRad)))
if verbosity > 2:
print("basicCentroid: rounded rad=%s" % (rad,))
# compute index of pixel closest to initial guess
ijIndGuess = ImUtil.ijIndFromXYPos(xyGuess)
if doDS9:
ds9Win = ImUtil.openDS9Win()
else:
ds9Win = None
if ds9Win:
# show masked data in frame 1 and unmasked data in frame 2
ds9Win.xpaset("frame 1")
if mask is not None:
ds9Win.showArray(data * (mask==0))
else:
ds9Win.showArray(data)
ds9Win.xpaset("frame 2")
ds9Win.showArray(data)
ds9Win.xpaset("frame 1")
# display circle showing the centroider input in frame 1
args = list(xyGuess) + [rad]
ds9Win.xpaset("regions", "image; circle %s # group=ctrcirc" % _fmtList(args))
try:
# OK, use this as first guess at maximum. Extract radial profiles in
# a 3x3 gridlet about this, and walk to find minimum fitting error
maxi, maxj = ijIndGuess
asymmArr = numpy.zeros([3,3], float)
totPtsArr = numpy.zeros([3,3], int)
totCountsArr = numpy.zeros([3,3], float)
niter = 0
while True:
niter += 1
if niter > _MaxIter:
raise RuntimeError("could not find a star in %s iterations" % (niter,))
for i in range(3):
ii = maxi + i - 1
for j in range(3):
jj = maxj + j - 1
if totPtsArr[i, j] != 0:
continue
asymmArr[i, j], totCountsArr[i, j], totPtsArr[i, j] = radProf.radAsymmWeighted(
data, mask, (ii, jj), rad, ccdInfo.bias, ccdInfo.readNoise, ccdInfo.ccdGain)
# this version omits noise-based weighting
# (warning: the error estimate will be invalid and chiSq will not be normalized)
# asymmArr[i, j], totCountsArr[i, j], totPtsArr[i, j] = radProf.radAsymm(
# data, mask, (ii, jj), rad)
if verbosity > 3:
print("basicCentroid: ind=[%s, %s] ctr=(%s, %s) asymm=%10.1f, totPts=%s, totCounts=%s" % \
(i, j, ii, jj, asymmArr[i, j], totPtsArr[i, j], totCountsArr[i, j]))
# have error matrix. Find minimum
ii, jj = scipy.ndimage.minimum_position(asymmArr)
ii -= 1
jj -= 1
if verbosity > 2:
print("basicCentroid: error matrix min ii=%d, jj=%d, errmin=%5.1f" % (ii, jj, asymmArr[ii,jj]))
if verbosity > 3:
print("basicCentroid: asymm matrix =\n", asymmArr)
if (ii != 0 or jj != 0):
# minimum error not in center; walk and try again
maxi += ii
maxj += jj
if verbosity > 2:
print("shift by", -ii, -jj, "to", maxi, maxj)
if ((maxi - ijIndGuess[0])**2 + (maxj - ijIndGuess[1])**2) >= rad**2:
raise RuntimeError("could not find star within %r pixels" % (rad,))
# shift asymmArr and totPtsArr to minimum is in center again
asymmArr = scipy.ndimage.shift(asymmArr, (-ii, -jj))
totCountsArr = scipy.ndimage.shift(totCountsArr, (-ii, -jj))
totPtsArr = scipy.ndimage.shift(totPtsArr, (-ii, -jj))
else:
# Have minimum. Get out and go home.
break
if verbosity > 2:
print("basicCentroid: found ijMax=%s after %r iterations" % ((maxi, maxj), niter,))
# perform a parabolic fit to find true centroid
# and compute the error estimate
# y(x) = ymin + a(x-xmin)^2
# a = (y0 - 2y1 + y2) / 2
# xmin = b/2a where b = (y2-y0)/2
# ymin = y1 - b^2/4a but this is tricky in 2 dimensions so we punt
# for a given delta-y, delta-x = sqrt(delta-y / a)
ai = 0.5 * (asymmArr[2, 1] - 2.0*asymmArr[1, 1] + asymmArr[0, 1])
bi = 0.5 * (asymmArr[2, 1] - asymmArr[0, 1])
aj = 0.5 * (asymmArr[1, 2] - 2.0*asymmArr[1, 1] + asymmArr[1, 0])
bj = 0.5 * (asymmArr[1, 2] - asymmArr[1, 0])
di = -0.5*bi/ai
dj = -0.5*bj/aj
ijCtr = (
maxi + di,
maxj + dj,
)
xyCtr = ImUtil.xyPosFromIJPos(ijCtr)
if verbosity > 2:
print("basicCentroid: asymmArr[0:3, 1]=%s, ai=%s, bi=%s, di=%s, iCtr=%s" % (asymmArr[0:3, 1], ai, bi, di, ijCtr[0]))
print("basicCentroid: asymmArr[1, 0:3]=%s, aj=%s, bj=%s, dj=%s, jCtr=%s" % (asymmArr[1, 0:3], aj, bj, dj, ijCtr[1]))
# crude error estimate, based on measured asymmetry
# note: I also tried using the minimum along i,j but that sometimes is negative
# and this is already so crude that it's not likely to help
radAsymmSigma = asymmArr[1,1]
iErr = math.sqrt(radAsymmSigma / ai)
jErr = math.sqrt(radAsymmSigma / aj)
xyErr = (jErr, iErr)
if ds9Win:
# display x at centroid
ds9Win.xpaset("regions", "image; x point %s # group=centroid" % \
_fmtList(xyCtr))
# count # saturated pixels, if satMask available
if satMask is None:
nSat = None
else:
ctrPixIJ = (maxi, maxj)
ctrPixXY = ImUtil.xyPosFromIJPos(ctrPixIJ)
subSize = (rad*2) + 1
subSatMaskObj = ImUtil.subFrameCtr(
satMask,
xyCtr = ctrPixXY,
xySize = (subSize, subSize),
)
subSatMask = subSatMaskObj.getSubFrame()
subCtrIJ = subSatMaskObj.subIJFromFullIJ(ctrPixIJ)
def makeDisk(i, j):
return ((i-subCtrIJ[0])**2 + (j-subCtrIJ[1])**2) <= rad**2
maybeSatPixel = numpy.fromfunction(makeDisk, subSatMask.shape)
if mask is not None:
subMaskObj = ImUtil.subFrameCtr(
mask,
xyCtr = ctrPixXY,
xySize = (subSize, subSize),
)
subMask = subMaskObj.getSubFrame()
numpy.logical_and(maybeSatPixel, numpy.logical_not(subMask), maybeSatPixel)
numpy.logical_and(subSatMask, maybeSatPixel, maybeSatPixel)
nSat = scipy.ndimage.sum(maybeSatPixel)
ctrData = CentroidData(
isOK = True,
rad = rad,
nSat = nSat,
xyCtr = xyCtr,
xyErr = xyErr,
counts = totCountsArr[1,1],
pix = totPtsArr[1,1],
asymm = asymmArr[1,1],
)
if verbosity > 2:
print("basicCentroid: %s" % (ctrData,))
return ctrData
except Exception as e:
if verbosity > 1:
traceback.print_exc(file=sys.stderr)
elif verbosity > 0:
print("basicCentroid failed: %s" % (e,))
return CentroidData(
isOK = False,
msgStr = str(e),
rad = rad,
)
def centroid(
data,
mask,
satMask,
xyGuess,
rad,
ccdInfo,
thresh = DefThresh,
doSmooth = True,
verbosity = 0,
doDS9 = False,
checkSig = (True, True),
):
"""Centroid and then confirm that there is usable signal at the location.
Inputs:
- data image data [i,j]
- mask a mask of invalid data (1 if invalid, 0 if valid); None if no mask.
- satMask a maks of of saturated pixels (1 if saturated, 0 if not); None if no mask.
- xyGuess initial x,y guess for centroid
- rad radius of search (pixels);
values less than _MinRad are treated as _MinRad
- ccdInfo ccd bias, gain, etc.; a PyGuide.CCDInfo object
- thresh determines the point above which pixels are considered data;
valid data >= thresh * standard deviation + median
values less than PyGuide.Constants.MinThresh are silently increased
- doSmooth if True apply a 3x3 median filter to smooth the data
- verbosity 0: no output, 1: print warnings, 2: print information, 3: print iteration info.
Note: there are no warnings at this time
- doDS9 if True, display diagnostic images in ds9
- checkSig Verify usable signal for circle at (xyGuess, xy centroid)?
If both are false then imStats is not computed.
Returns a CentroidData object (which see for more info).
"""
if verbosity > 2:
print("data =", data)
print("mask =", mask)
print("centroid(xyGuess=%s, rad=%s, ccdInfo=%s, thresh=%s)" % (xyGuess, rad, ccdInfo, thresh))
if checkSig[0]:
signalOK, imStats = checkSignal(
data = data,
mask = mask,
xyCtr = xyGuess,
rad = rad,
thresh = thresh,
doSmooth = doSmooth,
verbosity = verbosity,
)
if not signalOK:
return CentroidData(
isOK = False,
msgStr = "No star found",
)
ctrData = basicCentroid(
data = data,
mask = mask,
satMask = satMask,
xyGuess = xyGuess,
rad = rad,
ccdInfo = ccdInfo,
verbosity = verbosity,
doDS9 = doDS9,
)
if ctrData.isOK and checkSig[1]:
signalOK, imStats = checkSignal(
data = data,
mask = mask,
xyCtr = ctrData.xyCtr,
rad = rad,
thresh = thresh,
doSmooth = doSmooth,
verbosity = verbosity,
)
ctrData.imStats = imStats
if not signalOK:
ctrData.isOK = False
ctrData.msgStr = "No star found"
return ctrData
def checkSignal(
data,
mask,
xyCtr,
rad,
thresh = DefThresh,
doSmooth = True,
verbosity = 0,
):
"""Check that there is usable signal in a given circle.
Inputs:
- data image data [i,j]
- mask a mask [i,j] of 0's (valid data) or 1's (invalid); None if no mask.
If mask is specified, it must have the same shape as data.
- xyCtr center of circule (pixels)
- rad radius of circle (pixels);
values less than _MinRad are treated as _MinRad
- thresh determines the point above which pixels are considered data;
valid data >= thresh * standard deviation + median
values less than PyGuide.Constants.MinThresh are silently increased
- doSmooth if True apply a 3x3 median filter to smooth the data
- verbosity 0: no output, 1: print warnings, 2: print information, 3: print iteration info.
Return:
- signalOK True if usable signal is present
- imStats background statistics: a PyGuide.ImStats object
Details of usable signal:
- Computes median and stdDev in a region extending from a circle of radius "rad"
to a box of size (rad+_OuterRadAdd)*2 on a side.
- if doSmooth is True then median-smooths the umasked data
- makes sure that the (possibly smoothed) data contains usable signal:
max(data) >= thresh*stdDev + median
"""
if verbosity > 2:
print("checkSignal(xyCtr=%s, rad=%s, thresh=%s)" % (xyCtr, rad, thresh))
# check check inputs
if len(xyCtr) != 2:
raise ValueError("initial guess=%r must have 2 elements" % (xyCtr,))
rad = int(round(max(rad, _MinRad)))
outerRad = rad + _OuterRadAdd
subDataObj = ImUtil.subFrameCtr(
data,
xyCtr = xyCtr,
xySize = (outerRad, outerRad),
)
subData = subDataObj.getSubFrame().astype(numpy.float32) # force type and copy
if subData.size < _MinPixForStats:
if verbosity > 1:
print("checkSignal: signalOK=False because subData.size = %d < %d = _MinPixForStats" %
(subData.size, _MinPixForStats))
return False, ImUtil.ImStats(
nPts = subData.size,
)
subCtrIJ = subDataObj.subIJFromFullIJ(ImUtil.ijPosFromXYPos(xyCtr))
if mask is not None:
subMaskObj = ImUtil.subFrameCtr(
mask,
xyCtr = xyCtr,
xySize = (outerRad, outerRad),
)
subMask = subMaskObj.getSubFrame().astype(numpy.bool) # force type and copy
else:
subMask = numpy.zeros(subData.shape, dtype=numpy.bool)
# create circleMask; a centered circle of radius rad
# with 0s in the middle and 1s outside
def makeCircle(i, j):
return ((i-subCtrIJ[0])**2 + (j-subCtrIJ[1])**2) > rad**2
circleMask = numpy.fromfunction(makeCircle, subData.shape)
# make a copy of the data outside a circle of radius "rad";
# use this to compute background stats
bkgndPixels = numpy.extract(numpy.logical_and(circleMask, numpy.logical_not(subMask)), subData)
if bkgndPixels.size < _OuterRadAdd**2:
# too few unmasked pixels in outer region; try not masking off the star
if verbosity > 2:
print("checkSignal: too few good pixels in outer region; testing entire region")
bkgndPixels = numpy.extract(subData, numpy.logical_not(subMask))
if bkgndPixels.size < _MinPixForStats:
if verbosity > 1:
print("checkSignal: signalOK=False because bkgndPixels.size = %d < %d = _MinPixForStats" %
(bkgndPixels.size, _MinPixForStats))
return False, ImUtil.ImStats(
nPts = bkgndPixels.size,
)
imStats = ImUtil.skyStats(bkgndPixels, thresh)
del(bkgndPixels)
# median filter the inner data and look for signal > dataCut
dataPixels = numpy.ma.masked_array(
subData,
mask = numpy.logical_or(subMask, circleMask),
copy = True,
)
smoothedData = dataPixels.filled(imStats.med)
if doSmooth:
scipy.ndimage.median_filter(smoothedData, 3, output=smoothedData)
del(dataPixels)
# look for a blob of at least 2x2 adjacent pixels with smoothed value >= dataCut
# note: it'd be much simpler but less safe to simply test:
# if max(smoothedData) < dataCut: # have signal
shapeArry = numpy.ones((3,3))
labels, numElts = scipy.ndimage.label(smoothedData > imStats.dataCut, shapeArry)
del(smoothedData)
if verbosity > 2:
print("number of candidate blobs = %s" % (numElts,))
slices = scipy.ndimage.find_objects(labels)
for ijSlice in slices:
minSize = min([slc.stop - slc.start for slc in ijSlice])
if minSize >= 2:
return True, imStats
if verbosity > 1:
print("checkSignal: signalOK=False because no stars found")
return False, imStats
def conditionData(data):
"""Convert dataArr to the correct type
such that basicCentroid can operate most efficiently on it.
Warning: does not copy the data unless necessary.
"""
return conditionArr(data, desType=numpy.float32)
def conditionMask(mask):
"""Convert mask to the correct type
such that basicCentroid can operate most efficiently on it.
Mask is optional, so a value of None returns None.
Warning: does not copy the data unless necessary.
"""
if mask is None:
return None
return conditionArr(mask, numpy.bool)
def conditionArr(arr, desType):
"""Convert a sequence to a numpy array of the desired type.
Warning: does not copy the data unless necessary.
"""
return numpy.array(arr, dtype=desType, order="C")