亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

退出后如何訪問“while True: try/break”循環內生成的局部變量?

退出后如何訪問“while True: try/break”循環內生成的局部變量?

慕無忌1623718 2023-07-05 16:31:06
我編寫了一個模塊,它獲取目錄中的所有 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這里有什么問題嗎?我的第一個想法是,它outputPath是循環本地的while True: try,并且在 后被破壞break,所以我outputPath = ''在循環之前實例化了一個空字符串,但這沒有幫助。
查看完整描述

1 回答

?
一只名叫tom的貓

TA貢獻1906條經驗 獲得超3個贊

您并不是試圖在循環之外訪問變量,而是試圖完全在方法之外訪問它。該方法返回您要查找的值,因此將該值設置為變量:


outputPath = average_tiff_frames(inputPath)


print(outputPath)

或者直接打印:


print(average_tiff_frames(inputPath))


查看完整回答
反對 回復 2023-07-05
  • 1 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號