【问题标题】:How to crop same size image patches with different locations from a stack of images?如何从一堆图像中裁剪具有不同位置的相同大小的图像补丁?
【发布时间】:2014-09-05 09:03:54
【问题描述】:

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

有没有一种很好的/pythonic 方式来切片imgs 以获得patches(形状为(num_images,3,pw,ph))每个补丁都围绕其对应的centers 为中心?

为简单起见,假设所有补丁都在图像边界内是安全的。

【问题讨论】:

    标签: python image-processing numpy multidimensional-array


    【解决方案1】:

    正确的切片是不可能的,因为您需要不定期地访问基础数据。您可以通过一个“花式索引”操作获得作物,但您需要一个(非常)大的索引数组。因此,我认为使用循环更容易更快。

    比较以下两个函数:

    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-loop
    • 循环版本运行良好。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2014-02-16
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多