Numpy diagram (3)--high-dimensional array

content

high-dimensional array

create array

High-dimensional array operations

Connecting functions hstack, vstack and dstack

stack function concatenate

Summation function einsum

high-dimensional array

create array

When creating a 3D array by rearranging a 1D vector or transforming a nested Python list, the index means (z, y, x) .

The first index is the number of the plane, then the movement on that plane:

This indexing order is convenient, e.g. for keeping a bunch of grayscale images: this a[i] is a shortcut for referencing the ith image.

But this index order is not universal. When working with RGB images, the (y, x, z) order is usually used: the first two are pixel coordinates, and the last are color coordinates (RGB in Matplotlib, BGR in OpenCV) :

This way, it is convenient to refer to a specific pixel: a[i,j] gives the RGB tuple (i,j) of the pixel.

Therefore, the actual command to create a specific geometry depends on the conventions of the domain being processed:

High-dimensional array operations

Connecting functions hstack, vstack and dstack

Apparently, NumPy functions like hstack, vstack or dstack don't know these conventions. where the hardcoded index order is (y,x,z) and the RGB image order is:

RGB image array (for simplicity, only 2 colors in the above image)

stack function concatenate

If the data is laid out differently, it is more convenient to stack the images using the concatenate command, and provide an explicit number of indices in the axis parameter:

If it is not convenient to use axis, you can hardcode the array conversion to the form of hstack:

No actual copying takes place for this conversion. It just mixes the order of the indexes.

Another operation that mixes index order is array transpose. Examining it might make us more familiar with three-dimensional arrays.

Depending on the axis order we decide, the actual command to transpose all the planes of the array will be different: for generic arrays it swaps indices 1 and 2, for RGB images it swaps 0 and 1:

Interestingly, (and the only mode of operation) the default axes parameter reverses the index order, which is inconsistent with both of the above index order conventions.

Summation function einsum

Finally, there is a function that saves a lot of Python loops and makes the code more concise when dealing with multidimensional arrays, which is the Einstein summation function einsum :

It will sum along repeated indexed arrays.

Guess you like

Origin blog.csdn.net/weixin_43145427/article/details/124317892