如何将带参数的函数作为参数传递给python中的另一个函数,函数名作为字符串?

How to pass functions with arguments as parameter to another function in python with function name as a string?

我在main.py中有以下源代码

主.py

1
2
3
4
5
6
7
8
9
10
import data_utils as du

X_train1, Y_train1, groundtruth_train1= du.loaddata(train_file,"adjust_gamma", 0.8)
X_train2, Y_train2, groundtruth_train2= du.loaddata(train_file,"adjust_gamma", 1.2)
X_train3, Y_train3, groundtruth_train3= du.loaddata(train_file,"scale_image", 0.5)
X_train4, Y_train4, groundtruth_train4= du.loaddata(train_file,"scale_image", 0.8)
X_train5, Y_train5, groundtruth_train5= du.loaddata(train_file,"scale_image", 1.5)
X_train6, Y_train6, groundtruth_train6= du.loaddata(train_file,"scale_image", 2.0)
X_train7, Y_train7, groundtruth_train7= du.loaddata(train_file,"compress_jpeg", 70)
X_train8, Y_train8, groundtruth_train8= du.loaddata(train_file,"compress_jpeg", 90)

main.py将读取几个图像,应用图像转换,将它们划分为块(这些是我的x_训练输出),并获取图像标签(y_训练和groundtruth_训练)。图像转换由带参数的字符串定义(例如"Adjust_Gamma"等)。

现在,load_data.py是基于这个关于如何将带有参数的函数传递给另一个函数的答案而构建的。

数据实用程序.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def loaddata(file_images, function_name, parameter):

x = []
y = []

with open(file_images) as f:
    images_names = f.readlines()
    images_names = [a.strip() for a in images_names]

    j=0

    for line in images_names:

        j=j+1

        line='image_folder/' + line
        img = cv2.imread(img_path)
        img=perform(eval(function_name)(img,parameter))
        ...

执行的函数将接收函数名(如在main.py中看到的字符串)及其参数(numpy数组中的图像和参数)。执行的功能详细如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def perform(fun, *args):
fun(*args)

def adjust_gamma(image, gamma):
   invGamma = 1.0 / gamma
   table = np.array([((i / 255.0) ** invGamma) * 255
      for i in np.arange(0, 256)]).astype("uint8")
   return cv2.LUT(image, table)

def compress_jpeg(image, compression_factor):
   encode_param=[int(cv2.IMWRITE_JPEG_QUALITY), compression_factor]
   result, encimg=cv2.imencode('.jpg', image, encode_param)
   decimg=cv2.imdecode(encimg, 1)
   return decimg

def scale_image(image, scaling_factor):
   resized_image=cv2.resize(image, (scaling_factor, scaling_factor))
   return resized_image

我尝试使用eval函数,这样传递的字符串就可以被视为函数名(这个答案激励我这样做)。但是,当我运行代码时,会得到以下错误:

File
"main.py",
line 32, in do_experiment

X_train1, Y_train1, groundtruth_train1= du.loaddata(train_file,"adjust_gamma", 0.8)

File
"data_utils.py",
line 29, in loaddata

img=perform(eval(function_name)(img,parameter)) File"data_utils.py",

line 171, in perform
fun(**args) TypeError: 'numpy.ndarray' object is not callable

那么,我该如何解决我的问题呢?如何使用函数名作为字符串将函数作为参数传递给另一个函数?


eval(function_name)(img,parameter)替换为:

1
globals()[function_name](img,parameter)

请注意,在我的答案中,您想要的函数应该在同一个模块中,如果不是,请阅读这个链接或关于Python中的globalslocals的链接,以找到解决问题的最佳方法。

此外,您还可以使用getattr访问另一个模块的功能,如下所示:

1
getattr(module, func)(*args, **kwargs)