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

时间:2018-11-21 05:24:45

标签: python string function

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

main.py

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_train输出),并获得图像标签(Y_train和groundtruth_train)。图片转换是由带有参数(例如“ adjust_gamma”等)的字符串定义的。

现在,根据这个答案about how to pass functions with arguments to another function

构建了load_data.py

data_utils.py

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数组中的图像和参数)。执行的功能如下:

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函数,因此可以将传递的字符串视为函数名称(This answer inspired me to do that)。但是,当我运行代码时,出现以下错误:

  

文件   “ main.py”,   do_experiment中的第32行

     

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

     

文件   “ data_utils.py”,   第29行,在loaddata中

     

img = perform(eval(功能名称)(img,参数))文件“ data_utils.py”,

     

第171行,进行中       fun(** args)TypeError:“ numpy.ndarray”对象不可调用

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

1 个答案:

答案 0 :(得分:1)

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

globals()[function_name](img,parameter)

请注意,您所需的函数应该在我的答案的同一模块中,如果不是,请在python中阅读有关globalslocals的{​​{3}}或this link找到最适合您的问题的东西。

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

getattr(module, func)(*args, **kwargs)
相关问题