退出后如何访问 "while True: try/break" 循环内生成的局部变量?
How to access a local variable generated inside a "while True: try/break" loop after exiting it?
我编写了一个模块,它获取目录中的所有 TIFF 图像,对每个图像文件中的所有帧进行平均,并将平均图像保存到由 outputPath
:
指定的自动生成的子目录中
def average_tiff_frames(inputPath):
'''
This function opens all TIFF image files in a directory, averages over all frames within each TIFF file,
and saves the averaged images to a subdirectory.
Parameters
----------
inputPath : string
Absolute path to the raw TIFF files
'''
import datetime
import os
import numpy as np
from PIL import Image
# Read image file names, create output folder
while True:
try:
inputPath = os.path.join(inputPath, '') # Add trailing slash or backslash to the input path if missing
filenames = [filename for filename in os.listdir(inputPath)
if filename.endswith(('.tif', '.TIF', '.tiff', '.TIFF'))
and not filename.endswith(('_avg.tif'))]
outputPath = os.path.join(inputPath, datetime.datetime.now().strftime('%Y%m%dT%H%M%S'), '')
os.mkdir(outputPath)
break
except FileNotFoundError:
print('TIFF file not found - or - frames in TIFF file already averaged (file name ends with "_avg.tif")')
# Open image files, average over all frames, save averaged image files
for filename in filenames:
img = Image.open(inputPath + filename)
width, height = img.size
NFrames = img.n_frames
imgArray = np.zeros((height, width)) # Ordering of axes: img.size returns (width, height), np.zeros takes (rows, columns)
for i in range(NFrames):
img.seek(i)
imgArray += np.array(img)
i += 1
imgArrayAverage = imgArray / NFrames
imgAverage = Image.fromarray(imgArrayAverage)
imgAverage.save(outputPath + filename.rsplit('.')[0] + '_avg' + '.tif')
img.close()
return outputPath
print('Averaged TIFF images have been saved to ' + outputPath + '. The output path is returned as a string to the variable "outputPath".')
执行模块后,我希望 outputPath
(即分配给它的字符串)可用于进一步的步骤。然而,当做
average_tiff_frames(inputPath)
print(outputPath)
我收到以下错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-99d0a947275c> in <module>()
1 inputPath = '/home/user/Desktop/data/'
2 average_tiff_frames(inputPath)
----> 3 print(outputPath)
NameError: name 'outputPath' is not defined
这里有什么问题?
我的第一个想法是 outputPath
是 while True: try
循环的局部变量,并在 break
之后被销毁,所以我在 outputPath = ''
之前实例化了一个空字符串 outputPath = ''
循环,但没有帮助。
您不是在尝试访问循环外的变量,而是在尝试完全在方法之外访问它。该方法 returns 您要查找的值,因此将该值设置为变量:
outputPath = average_tiff_frames(inputPath)
print(outputPath)
或者直接打印出来:
print(average_tiff_frames(inputPath))
我编写了一个模块,它获取目录中的所有 TIFF 图像,对每个图像文件中的所有帧进行平均,并将平均图像保存到由 outputPath
:
def average_tiff_frames(inputPath):
'''
This function opens all TIFF image files in a directory, averages over all frames within each TIFF file,
and saves the averaged images to a subdirectory.
Parameters
----------
inputPath : string
Absolute path to the raw TIFF files
'''
import datetime
import os
import numpy as np
from PIL import Image
# Read image file names, create output folder
while True:
try:
inputPath = os.path.join(inputPath, '') # Add trailing slash or backslash to the input path if missing
filenames = [filename for filename in os.listdir(inputPath)
if filename.endswith(('.tif', '.TIF', '.tiff', '.TIFF'))
and not filename.endswith(('_avg.tif'))]
outputPath = os.path.join(inputPath, datetime.datetime.now().strftime('%Y%m%dT%H%M%S'), '')
os.mkdir(outputPath)
break
except FileNotFoundError:
print('TIFF file not found - or - frames in TIFF file already averaged (file name ends with "_avg.tif")')
# Open image files, average over all frames, save averaged image files
for filename in filenames:
img = Image.open(inputPath + filename)
width, height = img.size
NFrames = img.n_frames
imgArray = np.zeros((height, width)) # Ordering of axes: img.size returns (width, height), np.zeros takes (rows, columns)
for i in range(NFrames):
img.seek(i)
imgArray += np.array(img)
i += 1
imgArrayAverage = imgArray / NFrames
imgAverage = Image.fromarray(imgArrayAverage)
imgAverage.save(outputPath + filename.rsplit('.')[0] + '_avg' + '.tif')
img.close()
return outputPath
print('Averaged TIFF images have been saved to ' + outputPath + '. The output path is returned as a string to the variable "outputPath".')
执行模块后,我希望 outputPath
(即分配给它的字符串)可用于进一步的步骤。然而,当做
average_tiff_frames(inputPath)
print(outputPath)
我收到以下错误:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-5-99d0a947275c> in <module>()
1 inputPath = '/home/user/Desktop/data/'
2 average_tiff_frames(inputPath)
----> 3 print(outputPath)
NameError: name 'outputPath' is not defined
这里有什么问题?
我的第一个想法是 outputPath
是 while True: try
循环的局部变量,并在 break
之后被销毁,所以我在 outputPath = ''
之前实例化了一个空字符串 outputPath = ''
循环,但没有帮助。
您不是在尝试访问循环外的变量,而是在尝试完全在方法之外访问它。该方法 returns 您要查找的值,因此将该值设置为变量:
outputPath = average_tiff_frames(inputPath)
print(outputPath)
或者直接打印出来:
print(average_tiff_frames(inputPath))