我正在绘制一张适合星空的图像。然后,我在足够明亮的恒星上显示图像中的圆形光圈。接下来,我尝试点击我感兴趣的那颗星,并从最近的圆圈中获取亮度测量值。最后,我想将亮度测量用于其他计算。
我的问题是,我声明用来存储单击的x,y坐标的变量似乎在我实际单击之前就被调用了,这导致了一个空数组和错误。
几个月前,一位同事把它发给了我,曾几何时,它工作得无懈可击。但它似乎已经停止工作了。这可能是一些库/模块更新的结果,但我不能确定。
我尝试了各种组合,包括在其他函数、其他位置等中声明"coords“。我尝试更改某些行的顺序,以便稍后调用"coords”。我也尝试过从头开始编写代码,并且遇到了许多相同的错误。因为这个特定的代码曾经有效,所以我附加了它而不是我的尝试。
老实说,我不完全理解代码,因为它不是我写的。因此,我不知道什么时候被调用,或者我所做的任何更改实际上做了什么。
def plot_image(file, vmin=5, vmax=99, threshold=5, radius=25):
hdu=fits.open(file)
image = hdu[0].data
exptime = hdu[0].header['EXPTIME']
band = hdu[0].header['FILTERS']
airmass = hdu[0].header['AIRMASS']
readnoise = hdu[0].header['RN_01']
gain = hdu[0].header['GAIN_01']
obj = hdu[0].header['OBJECT']
sub = image[1500:2000,1500:2000]
bkg_sigma = mad_std(sub)
mean, median, std = sigma_clipped_stats(sub, sigma=3.0, maxiters=5)
daofind = photutils.DAOStarFinder(fwhm=2., threshold=threshold*bkg_sigma)
sources = daofind(sub - median)
positions = (sources['xcentroid'], sources['ycentroid'])
apertures = photutils.CircularAperture(positions, r=radius)
phot_table = photutils.aperture_photometry(sub - median, apertures)
pix = select(image, apertures)
print(pix)
if len(pix) == 2 or len(coords) == 2:
distance = np.sqrt((np.array(phot_table['xcenter'])-pix[0])**2 + (np.array(phot_table['ycenter'])-pix[1])**2)
star = np.argmin(dist)
counts = phot_table[star]['aperture_sum']
fluxfile = open('testfile.txt')
signal = (counts * gain) / exptime
err = np.sqrt(counts*gain + (readnoise**2*np.pi*radius**2))
else:
print('Pix length = 0')
def select(image, apertures, vmin = 5, vmax = 99):
global coords
coords = []
fig = plt.figure(figsize = (9,9))
ax = fig.add_subplot(111)
ax.imshow(image, cmap = 'gist_gray_r', origin='lower', vmin = np.percentile(image, vmin), vmax = np.percentile(image, vmax), interpolation='none')
apertures.plot(color='blue', lw=1.5, alpha=0.5, ax = ax)
ax.set_title('Hello')#label='Object: '+obj+'\nFilter: '+band)
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
fig.canvas.mpl_disconnect(cid)
if None in coords:
return [np.nan,np.nan]
else:
return np.round(coords)
def onclick(event):
x = event.xdata
y = event.ydata
global coords
coords = [x, y]
plt.close()
return
def closeonclick(event):
print('Close On Click')
plt.close()
return预期结果:图像以叠加的蓝色光圈显示。然后,我点击所需的星号,我点击的坐标被存储到“坐标”中,并打印到控制台。显示图像的窗口也会在上一步旁边关闭。最后,使用这些坐标,它找到最近的光圈,并对产生的亮度进行一些科学研究。
实际结果:立即打印"coords“(一个空列表)。之后,图像立即显示出来。单击它不会执行任何操作。它不会更改"coords“的值,也不会打印任何其他内容,窗口也不会关闭。
发布于 2019-10-02 05:15:12
如果它不正确,我会回来删除它(如果我有这样的名声,我会评论),但看起来你必须首先在任何函数外定义一个全局变量,然后在函数内的变量名之前使用关键字来更改其作用域。试着在你的函数之外移动"coords = []“(在第一次调用"onclick”之后,列表将不再是空的,但是每次新的点击都应该替换坐标,所以这应该不是问题)。
参考:https://www.programiz.com/python-programming/global-keyword
https://stackoverflow.com/questions/57699434
复制相似问题