我有一个函数"func",它接收一个列表,其中包含名为"matrix_image"的图像行数:
list_rows = range(N_rows)
然后,在 func 内部完成计算,我得到一行表示图像的结果矩阵的新行。
def func(list_rows):
new_row = numpy.empty(N_columns)
....
....# some computation
....
return new_row
matrix_image = pool.map(func, list_n_rows )
"new_row"在func
内部正确计算,因为我在调试器中看到值,但生成的matrix_image具有形状:(list_n_rows,(。填充了"无">处的所有值。
如何从func
返回要附加到结果矩阵(二维数字数组(中的(一维数字数组(行?
您可以使用多处理的 RawArray 功能,在将启动进程之前需要从进程访问的变量定义为 RawArray,然后在进程完成后将其作为重塑的 numpy 数组进行访问。
下面是一个示例:
import numpy as np
import multiprocessing as mp
n_elements = 1000 # how many elements your numpy should have
def myProc( shared_var ):
'''
here you convert your shared variable from mp.RawArray to numpy
then treat it as it is numpy array e.g. fill it in with some
random numbers for demonstration purpose
'''
var = np.reshape( np.frombuffer( shared_var, dtype=np.uint32 ), -1 )
for i in range( n_elements ):
var[i] = np.random.randint( 0, 2**16, 1 )
print( 'myProc var.mean() = ', var.mean() )
#buffer that contains the memory
mp_var = mp.RawArray( 'i', n_elements )
p = mp.Process( target=myProc, args=(mp_var,) )
p.start()
p.join()
#after the process has ended, you convert the buffer that was passed to it
var = np.reshape( np.frombuffer( mp_var, dtype=np.uint32 ), -1)
#and again, you can treat it like a numpy array
print( ' out var.mean() = ',var.mean() )
输出为:
myProc var.mean() = 32612.403
var.mean() = 32612.403
希望对您有所帮助!
请注意,如果您从并发进程访问此缓冲区,则需要组织适当的锁定机制,以便不会有两个进程同时修改同一块内存。