我有一個使用numpy的Python腳本,它應該在返回單個值之前拍攝圖像並執行一些計算。當我單獨執行每條線時,它按預期工作。當我將它放在一個.py腳本中並從命令行或Canopy內運行時,它將返回一個數組。Python腳本返回一個數組而不是單個值
我已經修改了代碼略微不要求通常的圖像輸入,結果是一樣的:
import numpy as np
# Instead of loading an image, generate a test case (w or wo structured noise)
roi = np.random.poisson(38,(256,256));
blob = np.random.poisson(5,(128,128));
roi[64:192,64:192] = roi[64:192,64:192]+blob;
# Load the other variables if necessary (i.e., no DICOM to load)
[xDim,yDim] = [512,512];
roiLength = xDim/2;
pix = 1.18958;
# Declare memory for the FFTs
sizeFFT = xDim;
NPS2D = np.zeros((sizeFFT,sizeFFT)); # declare memory for fft results
fftslice = np.zeros((sizeFFT,sizeFFT));
# Set the dimension of the ROI and pull the pixel size. This will be
# used for the scaling factor in the 2D NPS.
deltaX = pix;
deltaY = pix;
scaleFactor = (deltaX/roiLength)*(deltaY/roiLength);
# Calculate the NPS
roiMean = np.mean(roi);
fftslice = np.fft.fft2((roi-roiMean),s=[sizeFFT,sizeFFT]);
NPS2D = scaleFactor*np.fft.fftshift(np.multiply(fftslice,np.conj(fftslice)));
NPS2D = NPS2D.real;
# Subtract the white noise from the NPS to get the structured NPS
stNPS = NPS2D - roiMean*deltaX*deltaY;
# Calculate SNI
SNI=sum(stNPS)/sum(NPS2D);
# Display the result
print SNI;
如果我執行每一行是0.107213670449(或類似的,因爲它是再生結果隨機數組)。如果我使用python foo.py
從命令行運行腳本,或單擊Canopy中的播放按鈕,結果是一個512長度的數組[4.64940089e-03 ... -4.59789051e-02 -7.15113682e-02]
,我已經手動刪除了509個條目。
有什麼想法?我錯過了明顯的東西嗎?
感謝注意到,。我從MATLAB修改了這段代碼,由於使用逐行執行方法在python中工作,我沒有添加np。這兩種執行方法之間'sum'的工作方式有什麼不同? – 2015-04-06 14:02:27