2017-02-17 68 views
0

Python初學者在這裏。我試圖讓我們把一些數據存儲在字典中。 我在一個文件夾中有一些.npy文件。我打算建立一個封裝以下內容的字典:讀取地圖,使用np.load,當前地圖的年份,月份和日期(以整數形式),以年爲單位的分數時間(假定一個月有30天 - 它不會影響我以後的計算),像素數量和像素數量超過某個值。最後我希望得到像一本字典:Python圖像文件操作

{'map0':'array(from np.load)', 'year', 'month', 'day', 'fractional_time', 'pixels' 
'map1':'....} 

我管理什麼到現在爲止是這樣的:

import glob 
file_list = glob.glob('*.npy') 

def only_numbers(seq): #for getting rid of any '.npy' or any other string 
    seq_type= type(seq) 
    return seq_type().join(filter(seq_type.isdigit, seq)) 

maps = {} 
for i in range(0, len(file_list)-1): 
    maps[i] = np.load(file_list[i]) 
    numbers[i]=list(only_numbers(file_list[i])) 

我不知道如何得到一本字典有多個值是在for循環下。我只能設法爲每個任務生成一個新字典或一個列表(例如數字)。對於數字字典,我不知道如何操作YYYYMMDD格式的日期來獲得我正在尋找的整數。

對於像素,我設法得到它在一張地圖,使用:

data = np.load('20100620.npy') 
print('Total pixel count: ', data.size) 
c = (data > 50).astype(int) 
print('Pixel >50%: ',np.count_nonzero(c)) 

任何提示?到目前爲止,圖像處理似乎是一個相當大的挑戰。

編輯:託管分裂日期和使用

date=list(only_numbers.values()) 
year=int(date[i][0:4]) 
month=int(date[i][4:6]) 
day=int(date[i][6:8]) 
print (year, month, day) 
+0

如果你可以使用標題來總結什麼是你的問題 – yuval

+0

也許你最好,也許你不需要字典,但類:https://www.tutorialspoint.com/python/python_classes_objects.htm –

+0

@StanislavIvanov感謝您的提示。 OOP目前有點難以掌握。我發佈了一些我做過的工作,儘管這不是最好的:) – nyw

回答

0

如果有人有興趣讓他們整數,我設法別的做一些事情。我放棄了包含所有內容的字典的想法,因爲我需要更輕鬆地進行操作。我做了以下:

file_list = glob.glob('data/...') # files named YYYYMMDD.npy 
file_list.sort() 

def only_numbers(seq): # i make sure that i remove all characters and symbols from the name of the file 
    seq_type = type(seq) 
    return seq_type().join(filter(seq_type.isdigit, seq)) 

numbers = {} 
time = [] 
np_above_value = [] 

for i in range(0, len(file_list) - 1): 
    maps = np.load(file_list[i]) 
    maps[np.isnan(maps)] = 0 # had some NANs and getting some errors 
    numbers[i] = only_numbers(file_list[i]) # getting a dictionary with the name of the files that contain only the dates - calling the function I defined earlier 
    date = list(numbers.values()) # registering the name of the files (only the numbers) as a list 
    year = int(date[i][0:4]) # selecting first 4 values (YYYY) and transform them as integers, as required 
    month = int(date[i][4:6]) # selecting next 2 values (MM) 
    day = int(date[i][6:8]) # selecting next 2 values (DD) 
    time.append(year + ((month - 1) * 30 + day)/360) # fractional time 

    print('Total pixel count for map '+ str(i) +':', maps.size) # total number of pixels for the current map in iteration 
    c = (maps > value).astype(int) 
    np_above_value.append (np.count_nonzero(c)) # list of the pixels with a value bigger than value 
    print('Pixels with concentration >value% for map '+ str(i) +':', np.count_nonzero(c)) # total number of pixels with a value bigger than value for the current map in iteration 

plt.plot(time, np_above_value) # pixels with concentration above value as a function of time 

我知道這可能是非常笨拙。 python的第二週,所以請忽略它。它的竅門:)