从字典中的2d数组中的每个元素中减去一个值

时间:2021-11-13 21:21:52

I am trying to subtract a value (dark_val) from all values within a 2D array that is within a dictionary. Currently I am looping through each key and extracting the values to a list and then using list comprehension:

我试图从字典中的2D数组中的所有值中减去一个值(dark_val)。目前,我循环遍历每个键并将值提取到列表,然后使用列表解析:

def dark_subtract(dic, dark_val):

    band_values = []

    # loop through the keys and variables to lists
    for key, value in dic.items():
        band_values.append(value)

    band_values[:] = [x - dark_val for x in band_values]

    return band_values

Ideally, however, I would like to iterate within the dictionary so that I returning a dictionary rather than a list (i.e. band_values).

然而,理想情况下,我想在字典中进行迭代,以便返回字典而不是列表(即band_values)。

I have tried the following and it doesn't bring up any errors but doesn't change the values either:

我尝试了以下内容并没有出现任何错误,但也没有更改值:

def dark_subtract(dic, dark_val):
    """
    Must be a dictionary input and a variable containing dark value
    """
    for entry in dic:
        if type(dic[entry]) is dict:
            dic[entry] = dark_subtract(dic[entry])
        else:
            dic[entry] - 100

    return dic
    print dic

The way I call the function is as follows:

我调用函数的方式如下:

dark_dic = dark_subtract(dic, d_value)
print "This is the original values:\n", dic
print "This is the dark current corrected values:\n", dark_dic

When printed the dictionary dic looks like:

打印时字典dic看起来像:

{'Band_1': array([[26176, 25920, 26816, ..., 53632, 53440, 52544],
       [25408, 24448, 23872, ..., 46592, 47040, 49216],
       [27264, 25024, 25792, ..., 50368, 51648, 51648],
       ..., 
       [32960, 32576, 32512, ..., 13568, 14528, 14720],
       [38784, 36416, 35648, ..., 18816, 15680, 16512],
       [33152, 32512, 32192, ..., 14464, 14720, 14784]], dtype=uint16)}

The dark_val is just an integer (currently set to 75)

dark_val只是一个整数(当前设置为75)

Any ideas?

1 个解决方案

#1


1  

You already have a NumPy array. Therefore, you can subtract the integer directly:

你已经有了一个NumPy数组。因此,您可以直接减去整数:

 for key, value in dic.items():
      dic[key] = value - dark_val

#1


1  

You already have a NumPy array. Therefore, you can subtract the integer directly:

你已经有了一个NumPy数组。因此,您可以直接减去整数:

 for key, value in dic.items():
      dic[key] = value - dark_val