2017-09-03 78 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