2017-09-03 136 views
0

我写了一个小程序来完成以下功能:传递变量进出的

  • 检查图像
  • 随机从图像
  • 情节像素值一起挑一排该行
  • 使局部极小的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() 

,如果我不使用函数的定义(它工作正常,也就是说,如果indexrowlocal_minima和嵌套循环for的声明是在的main部分该程序)。如图所示的函数定义,它返回一个NameError: name 'local_minima' is not defined错误。
因为我将这些变量传递给函数,所以我不能在程序的其余部分使用它们吗?
我错过了一些关于本地和全局变量的东西吗?

+0

你从哪里得到'NameError'?我看不到如何发布代码会为'local_minima'返回一个'NameError',除非它在你没有显示的代码的其他部分 – SethMMorton

回答

0

当您致电plot_envelope(w1data, height)时,您正在告诉函数将w1data和height分别指定给image和image_heigth。在函数内部,您应该使用image虚拟变量操作w1data(在函数内部更改图像的w1data),该范围仅在函数内部。接下来的事情是你应该得到函数的结果(返回)在一个变量中:envelope = plot_envelope(w1data, height)然后local_minima = envelope[0], row = envelope[1], index = envelope[2]

+1

另一种调用将是'local_minima,row,index = plot_envelope( w1data,height)'。 – SethMMorton

+0

呀!更好的@SethMMorton;) – Tico