2017-02-17 62 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的第二周,所以请忽略它。它的窍门:)