【问题标题】:How to create multiple images from a single image using strides?如何使用步幅从单个图像创建多个图像?
【发布时间】:2021-09-29 02:38:49
【问题描述】:

我有一个图像,我想像滑动窗口一样使用垂直和水平跨步将其拆分为多个图像,并且生成的图像都将具有相同的分辨率。我怎样才能在 Python 中有效地做到这一点?我做了这么多:

from PIL import Image

def sliding_window(image, stride, imgSize):
    width, height = image.size
    img = []
    for y in range(0, height-imgSize, stride):
        for x in range(0, width-imgSize, stride):
            # Setting the points for cropped image
            left = x
            top = y
            right = x + imgSize
            bottom = y + imgSize
            im1 = image.crop((left, top, right, bottom))
            img.append(im1)
    return img
file = "/home/xxxxxx/yyyyyy.png"
im = Image.open(file)
img = sliding_window(im, 1, 838) # Strides of 1 takes too much time

但是此代码需要太多 RAM 并且太耗时。请帮忙。

例子:

示例代码:img = sliding_window(im, 200, 300)

以下图片为800*800尺寸。

输出:

【问题讨论】:

  • 请展示您想要的最小示例。你展示的代码真的有效吗?
  • 您使用 matplotlib 显示它,因此您可以将图像加载为 numpy.array 并简单地使用 img[y:y+200, x:x+200] 获取图像的一部分并显示它 - 它应该更快地工作。它不会复制图像,但它使用原始数组中的数据。最终你可以使用img[y:y+200, x:x+200].copy() 复制它
  • 如果您只进行了一些计算而不显示,那么也许您应该直接在sliding_window 内进行操作,而不将图像保留在列表中。这样它应该使用更少的内存
  • @furas 我想返回一个 numpy 数组,其中包含上述格式的所有可能图像,我有几个图像可以执行相同的操作。感谢您的帮助。

标签: python image-processing sliding-window


【解决方案1】:

正如您正确推测的那样,有一种方法可以在不复制原始数据的情况下查看原始数据的窗口。最简单的方法大概是使用比较新的sliding_window_view函数:

from numpy.lib.stride_tricks import sliding_window_view

window = sliding_window_view(image, (838, 838), axis=(0, 1))

对于 2D 图像,您不需要显式的 axis,但在 3D 情况下它不会造成伤害并为您省去一些麻烦。如果你想调整步幅,你可以只对结果进行子集化。例如,对于(3, 4) 的步幅:

window = window[::3, ::4]

由于窗口轴必须(应该)按 C 顺序排在最后,因此 3D 图像的通道将移动到中间轴。要访问正确的形状,您可以使用 np.moveaxistranspose 之类的东西:

np.moveaxis(window[80, 70], 0, -1)

window[80, 70].transpose(1, 2, 0).shape

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2022-01-26
    • 2013-09-23
    • 2018-05-30
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多