【发布时间】: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