首页 > 解决方案 > numpy - how to slice of an array passed the limit of the array and back to the beginning

问题描述

enter image description here

I have an image in a numpy array and I want to take the slice in red.

I expect the output to look like this.

enter image description here

Imagine the shape is [600,800,3]

I've tried img[200:400,400:900,:] the 900 being higher than the limit hoping it would wrap around but no.

I know i could also take it as two slices and then hstack them, but i cant help think there is a better way?

Its also possible that the slice could overrun horizontally or vertically or both.

Any suggestions?

标签: pythonnumpy

解决方案


You could use np.roll(), which does a cyclic permutation / cyclic shift, along the specified axis (or axes)

If the shift happens along just axis1, use:

new_img = np.roll (img, split, axis=1)

where split is the col value at which your image is to be split. The effect of this cyclic shift is exactly as though the image had been split at the specified point on the axis, and the two resulting image-parts have been swapped.

Since you require to shift along axis1, and simultaneously slice along axis0, it would be:

new_img = np.roll (img[low:high,...], split, axis=[0,1])

where low and high are appropriate slice boundaries along axis0.

If a shift can happen along both axes simultaneously (and there is on slicing), it would be:

new_img = np.roll (img, [split_0, split_1], axis=[0,1])

where split_0 is the split point along axis0 and split_1 is the split point along axis1

Note: Somewhat surprisingly, instead of returning a view, roll() returns a copy, which means it may not give much of a speed-advantage, compared to stacking / concatenating.


推荐阅读