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

我在main.py中有以下源代码主.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_训练输出),并获取图像标签(y_训练和groundtruth_训练)。图像转换由带参数的字符串定义(例如"Adjust_Gamma"等)。

现在,load_data.py是基于这个关于如何将带有参数的函数传递给另一个函数的答案而构建的。数据实用程序.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函数,这样传递的字符串就可以被视为函数名(这个答案激励我这样做)。但是,当我运行代码时,会得到以下错误:

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

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

为什么对函数使用字符串别名而不是导入它们?

你的压痕好像掉了。不要让我们猜测应该缩进什么,请编辑您的问题,以准确显示每个def的结尾。(在此网站的桌面版本上,复制粘贴代码,选择粘贴的文本,然后键入ctrl-k使其缩进。)

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

globals()[function_name](img,parameter)

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值