从逐块处理函数中调用过滤器函数 [英] Calling filter functions from within a block-by-block processing function
问题描述
我有一些内存密集型图像过滤器,我想在大型图像/数组上逐块调用(因为它们为整个数组计算过滤器,在尝试计算整个数组时它们会耗尽内存)。 p>
I have some memory intensive image filters that I want to call block by block on large images/arrays (because they compute the filter for an entire array, they run out of memory when trying to compute the whole array).
def block_process(Ic, blocksize):
B = numpy.empty(Ic.shape)
colstart = 0
while colstart < Ic.shape[1]:
BlockWidth = blocksize
if (colstart + blocksize) > Ic.shape[1]:
BlockWidth = Ic.shape[1] - colstart
rowstart = 0
while rowstart < Ic.shape[0]:
BlockHeight = blocksize
if (rowstart + blocksize) > Ic.shape[0]:
BlockHeight = Ic.shape[0] - rowstart
B[colstart:colstart+BlockWidth, rowstart:rowstart+BlockHeight] = filter1(params) # One of many available filters
rowstart += BlockHeight
colstart += BlockWidth
return B # The complete filtered array
我的过滤器在其他函数中计算,即 def filter1(A,filtsize)
, def filter2(A,filtsize,otherparam)
,它有一个 A
参数(输入数组,由块函数给出),以及其他参数如作为过滤器大小。某些过滤器的参数比其他过滤器多。他们返回过滤后的数组。
My filters are computed in other functions i.e. def filter1(A, filtsize)
, def filter2(A, filtsize, otherparam)
, which have an A
parameter (the input array, given by the block function), and other parameters such as filter size. Some filters have more parameters than others. They return the filtered array.
两个问题
- 如何通过block_process函数调用我的一个过滤函数?我不想将块处理代码复制到每个函数中。换句话说,有没有办法指定调用哪个过滤器(以及使用什么参数)作为
block_process()
调用的参数? - 有更好的编码方法吗?
- How do I go about calling one of my filter functions through the block_process function? I don't want to copy the block processing code into each function. In other words, is there a way of specifying which filter to call (and with what parameters) as a parameter of the
block_process()
call? - Is there a better way of coding this?
推荐答案
你可以做到像这样:
def block_process(a, blocksize, filt, args):
b = numpy.empty(a.shape)
for row in xrange(0, a.shape[0], blocksize):
for col in xrange(0, a.shape[1], blocksize):
b[row:row + blocksize, col:col + blocksize] = (
filt(a[row:row + blocksize, col:col + blocksize], *args))
return b
无需更正图像右下边缘的不完整块 - 这将自动进行。您可以简单地传入过滤器函数和参数元组。要调用过滤器 filter1(a,filtsize)
,请使用
There is no need to correct for incomplete blocks at the right and lower edge of the image -- this will happen automatically. You can simply pass in the filter function and the tuple of arguments. To call the filter filter1(a, filtsize)
, use
block_process(a, blocksize, filter1, (filtsize,))
上面的代码假定第一个参数为过滤器是要过滤的数组,过滤器返回相同形状的过滤数组。
The code above assumes that the first parameter to a filter is the array to be filtered and that a filter returns a filtered array of the same shape.
也可以通过以下方式重写过滤器:它们不会使用尽可能多的内存,因此块处理将变得不必要。
It is also possible that your filters can be rewritten in a way that they don't use as much memory, so the blockprocessing would become unnecessary.
这篇关于从逐块处理函数中调用过滤器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!