规范深层嵌套列表Python中的所有元素

时间:2018-11-26 13:45:53

标签: python python-3.x image

我有一个深层的int列表形式的图像数据:

len(train_data_imgs) = 3889       # number of images in set
len(train_data_imgs[0]) = 100     # height
len(train_data_imgs[0][0]) = 100  # width
len(train_data_imgs[0][0][0]) = 3 # these are ints - RGB pixel values

我如何遍历这些变量以使其在0和1之间归一化?只需将每个数字除以255。

1 个答案:

答案 0 :(得分:1)

使用NumPy包在一行中完成:

# Assuming an image stored in a nested list | here NumPy array
lst = np.arange(27).reshape(3,3,3)
lst

array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

lst = lst/255 # That's what you should look for
lst

array([[[0.        , 0.00392157, 0.00784314],
        [0.01176471, 0.01568627, 0.01960784],
        [0.02352941, 0.02745098, 0.03137255]],

       [[0.03529412, 0.03921569, 0.04313725],
        [0.04705882, 0.05098039, 0.05490196],
        [0.05882353, 0.0627451 , 0.06666667]],

       [[0.07058824, 0.0745098 , 0.07843137],
        [0.08235294, 0.08627451, 0.09019608],
        [0.09411765, 0.09803922, 0.10196078]]])