【发布时间】:2015-10-27 09:58:00
【问题描述】:
我正在尝试找到将任意形状的 2d numpy 数组下采样为更小(或可能更大)的方形数组的最有效方法 - 我想取每个子数组的最大值并将其放入新数组中。这是我的代码:
import numpy as np
def downSampleMax(inputArray, numFrames):
newArray = np.zeros([numFrames, numFrames], dtype = np.uint8)
filterSize = (int(np.ceil(float(inputArray.shape[0]) / numFrames)),
int(np.ceil(float(inputArray.shape[1]) / numFrames)))
rowArr = np.linspace(0, inputArray.shape[0] - filterSize[0], numFrames, dtype = np.int)
colArr = np.linspace(0, inputArray.shape[1] - filterSize[1], numFrames, dtype = np.int)
for iRow in range(numFrames):
for iCol in range(numFrames):
newArray[iRow, iCol] = np.max(inputArray[rowArr[iRow]: rowArr[iRow] + filterSize[0],
colArr[iCol]: colArr[iCol] + filterSize[1]])
return newArray
关于如何显着加快速度的任何想法?我认为从我读到的内容来看,矢量化或切片可能是前进的方向,但不知道该怎么做。
【问题讨论】:
-
而不是
float(a) / b,最好在脚本顶部添加from __future__ import division,然后简单地执行a/b。 -
很酷,谢谢 Bas - 你知道我是否还需要在 Python 3 中这样做吗?我在这个项目中使用 Python 2,因为我必须与 Theano *** 编辑接口 - 刚刚尝试过,似乎没有! ***
-
from __future__在 Python2 中是必需的,在 Python3 中这是默认值,参见 PEP 238。如果您出于某种原因仍在使用 Python2,添加该行将使您以后更容易移植代码。
标签: arrays performance numpy vectorization downsampling