python - numpy - how to slice of an array passed the limit of the array and back to the beginning
问题描述
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.
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?
解决方案
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.
推荐阅读
- javascript - 为什么我的 forEach 循环没有从 array.length 创建 DOM 元素?
- java - 将两个映射连接成一个 java 类
- ios - AVPlayerViewController 有时会显示黑屏
- javascript - Vue克隆问题
- java - Java ,For 循环命令
- python - 使用 astropy.io.ascii 格式化
- loops - 循环遍历值并添加到范围
- java - java.time.LocalDate 和 Jython datetime.date
- bash - 作曲家错误/bin/sh:错误的解释器:没有这样的文件或目录
- java - 雅虎财经 URL 不起作用(自 2018 年 5 月起再次)