Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从一堆图像中裁剪具有不同位置的相同大小的图像面片?_Python_Image Processing_Numpy_Multidimensional Array - Fatal编程技术网

Python 如何从一堆图像中裁剪具有不同位置的相同大小的图像面片?

Python 如何从一堆图像中裁剪具有不同位置的相同大小的图像面片?,python,image-processing,numpy,multidimensional-array,Python,Image Processing,Numpy,Multidimensional Array,假设我有一个形状(num\u images,3,width,height)的ndarrayimgs,它存储了一堆大小相同的num\u imagesRGB images。 我想从每个图像中切片/裁剪一块形状为(3,pw,ph)的补丁,但是每个图像的补丁中心位置不同,并且在中心形状数组(num_images,2)中给出 是否有一种很好的/类似于蟒蛇的方式来切割imgs以获得补丁(形状(num_图像,3,pw,ph))每个补丁都围绕其相应的中心进行集中 为简单起见,可以安全地假设所有面片都位于图像边界

假设我有一个形状
(num\u images,3,width,height)
的ndarray
imgs
,它存储了一堆大小相同的
num\u images
RGB images。
我想从每个图像中切片/裁剪一块形状为
(3,pw,ph)
的补丁,但是每个图像的补丁中心位置不同,并且在
中心
形状数组
(num_images,2)
中给出

是否有一种很好的/类似于蟒蛇的方式来切割
imgs
以获得
补丁
(形状
(num_图像,3,pw,ph)
)每个补丁都围绕其相应的
中心进行集中


为简单起见,可以安全地假设所有面片都位于图像边界内。

不可能进行适当的切片,因为您需要以不规则的间隔访问底层数据。您可以通过一个“奇特的索引”操作获得作物,但您需要一个(非常)大的索引数组。因此,我认为使用循环更容易、更快

比较以下两个功能:

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

哦,索引有一个错误,但是参数仍然支持
for
-循环版本运行良好。非常感谢。