简体   繁体   English

如何将 3d 数组展平为 1d 数组

[英]How to flatten a 3d array to 1d array

I need a 3d nested array.我需要一个 3d 嵌套数组。 How can I flatten that to a 1d array?如何将其展平为一维数组? (Because of performance) I assume, that I need to multiply some stuff etc. but I'm not the greatest mathematician. (因为性能)我假设,我需要乘一些东西等等,但我不是最伟大的数学家。 Thanks!谢谢!

def imgRGB(im):
    width, height = im.size

    #create matrix
    matrix = []
    for i in range(height):
        matrix.append([[0,0,0] for _ in range(width)])

    #get the rgb values
    for x in range(width):
        for y in range(height):
            r,g,b = im.getpixel((x,y))
            matrix[y][x][0] = r
            matrix[y][x][1] = g
            matrix[y][x][2] = b
    return matrix

The pixel values will be compared to other RGB values to find the closest match.像素值将与其他 RGB 值进行比较以找到最接近的匹配。

def getNearestColor(rgb):
    a = []
    for i in range(len(rgbValues)):
        d = ((rgbValues[i][0]-rgb[0])*0.3)**2 + ((rgbValues[i][1]-rgb[1])*0.59)**2 + ((rgbValues[i][2]-rgb[2])*0.11)**2
        a.append(d)
    list.sort(a)
    return a[0]

You can use the ndarray.flatten, in your example it would be matrix.flatten() .您可以使用 ndarray.flatten,在您的示例中它将是matrix.flatten() This returns the flattened version of your matrix.这将返回矩阵的扁平版本。 Documentation here also has an example. 这里的文档也有一个例子。

If I understand it correctly, you want to do the following:如果我理解正确,您希望执行以下操作:

rgbValues = np.array(im).reshape(-1,3)
a = np.sort(np.sum(((rgbValues - rgb)* [0.3, 0.59, 0.11])**2, axis=1))

where rgb is a list [r, g, b] for some values r, g, b.其中rgb是一些值 r, g, b 的列表[r, g, b]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM