我写了一个小程序来完成以下功能:传递变量进出的
- 检查图像
- 随机从图像
- 情节像素值一起挑一排该行
- 使局部极小的
list
该行
中,我试图使之成为一个功能,让我做同样的东西,比如说10行,这样我就可以绘制所有这些行的像素值而无需运行程序10次。
的代码看起来是这样的:
from astropy.io import fits
import matplotlib.pyplot as plt
import numpy as np
hdulist = fits.open('xbulge-w1.fits') # Open FITS file as image
w1data = hdulist[0].data
height = w1data.shape[0] # Inspect height of image
width = w1data.shape[1]
def plot_envelope(image, image_height):
index = np.random.randint(0, height/2) # Select random number in upper half
row = w1data[index] # Look at row number
local_minima = []
# Find local minimum, and add to list of minimum-valued pixels
for i in range(1, width-1):
if w1data[index][i-1] > w1data[index][i]:
if w1data[index][i+1] > w1data[index][i]:
local_minima.append(w1data[index][i])
else:
continue
return (local_minima, row, index)
plot_envelope(w1data, height)
x1 = range(width)
plt.plot(x1, row, color = 'r', linewidth = 0.5)
plt.title('Local envelope for row ' + str(index))
plt.xlabel('Position')
plt.ylabel('Pixel value')
plt.show()
,如果我不使用函数的定义(它工作正常,也就是说,如果index
,row
和local_minima
和嵌套循环for
的声明是在的main
部分该程序)。如图所示的函数定义,它返回一个NameError: name 'local_minima' is not defined
错误。
因为我将这些变量传递给函数,所以我不能在程序的其余部分使用它们吗?
我错过了一些关于本地和全局变量的东西吗?
你从哪里得到'NameError'?我看不到如何发布代码会为'local_minima'返回一个'NameError',除非它在你没有显示的代码的其他部分 – SethMMorton