Sha*_*hai 5 python numpy image-processing multidimensional-array
假设我有一个imgs形状的ndarray ( num_images, 3, width, height ),它存储一堆num_images大小相同的 RGB 图像。
我想从每个图像中切片/裁剪一个形状的补丁( 3, pw, ph ),但是每个图像的补丁的中心位置都不同,并且以centersshape 数组的形式给出(num_images, 2)。
是否有一种很好的/Python式的切片方式imgs来获得patches(形状(num_images,3,pw,ph))每个补丁都以其相应的为中心centers?
为简单起见,可以安全地假设所有补丁都落在图像边界内。
小智 3
适当的切片是不可能的,因为您需要以不规则的间隔访问底层数据。您可以通过单个“花式索引”操作来获取农作物,但您需要一个(非常)大的索引数组。因此我认为使用循环更容易、更快。
比较以下两个函数:
def fancy_indexing(imgs, centers, pw, ph):
n = imgs.shape[0]
img_i, RGB, x, y = np.ogrid[:n, :3, :pw, :ph]
corners = centers - [pw//2, ph//2]
x_i = x + corners[:,0,None,None,None]
y_i = y + corners[:,1,None,None,None]
return imgs[img_i, RGB, x_i, y_i]
def just_a_loop(imgs, centers, pw, ph):
crops = np.empty(imgs.shape[:2]+(pw,ph), imgs.dtype)
for i, (x,y) in enumerate(centers):
crops[i] = imgs[i,:,x-pw//2:x+pw//2,y-ph//2:y+ph//2]
return crops
Run Code Online (Sandbox Code Playgroud)