numpy python图像切片使用np.arange

3b6akqbq  于 5个月前  发布在  Python
关注(0)|答案(1)|浏览(75)
import numpy as np

img = np.zeros((321, 481, 3))
h, w = img.shape[:2]
new_h, new_w = 300, 400

top = np.random.randint(0, h-new_h)
left = np.random.randint(0, w - new_w)

print(top, left)

id_y = np.arange(top, top+new_h, 1)
id_x = np.arange(left, left+new_w, 1)

dst = img[id_y, id_x]

字符串
我想把(321,481,3)的图像分割成(300,400,3)。通常,我使用img[:300, :400, :],但我希望起点是随机的,所以我尝试用不同的方式编写代码。
但发生了索引错误。

id_y = np.arange(top, top_new_h, 1)[:, np.newaxis]


当我像这样添加轴时,切片是正确的,但我对这样添加轴的原理很好奇。

x7rlezfr

x7rlezfr1#

这是基于广播的,你需要每对索引都索引到你的图像数组中。当两个数组都是1D数组时,广播不会发生。你可以通过添加一个新的轴(相当于:[:,None])或使用np.xi_来解决这个问题。

dst = img[np.xi_(id_y, id_x)]

字符串

相关问题