参考官方TF版,在numpy版基础上实现的:
一、多函数如何统一调用:
1. 用字典建立函数名和函数的对应关系。相似函数如Translate_X和Translate_Y可以借助lambda函数,送入不同的布尔值来xu
'TranslateX_BBox': lambda image, bboxes, pixels, replace:
translate_bbox(image, bboxes, pixels, replace, shift_horizontal=True),
'TranslateY_BBox': lambda image, bboxes, pixels, replace:
translate_bbox(image, bboxes, pixels, replace, shift_horizontal=False),
2. 借助inspect.getfullargspec(func)[0]获得函数的参数列表,通过参数列表,给函数送入不同的args:
def _parse_policy_info(name, prob, level, replace_value, augmentation_hparams):
"""Return the function that corresponds to `name` and update `level` param."""
func = NAME_TO_FUNC[name]
args = level_to_arg(augmentation_hparams)[name](level)
if 'prob' in inspect.getfullargspec(func)[0]:
# if 'prob' in inspect.signature(func)[0]:
args = tuple([prob] + list(args))
if 'replace' in inspect.getfullargspec(func)[0]:
# Make sure replace is the final argument
assert 'replace' == inspect.getfullargspec(func)[0][-1]
args = tuple(list(args) + [replace_value])
if 'bboxes' not in inspect.getfullargspec(func)[0]:
func = bbox_wrapper(func)
"""
args经过对应函数进行了修改,如:prob, replace
func对参数存在没有bboxes进行了修改
prob无修改
"""
return (func, prob, args)
有些函数不需要bboxes参数,除了送入函数后不使用外,还有一种包装方法:
def bbox_wrapper(func):
"""Adds a bboxes function argument to func and returns unchanged bboxes."""
def wrapper(images, bboxes, *args, **kwargs):
return (func(images, *args, **kwargs), bboxes)
return wrapper
3. 定义函数列表:定义函数内函数,将执行函数再次包装。
def make_final_policy(tf_policy_):
def final_policy(image_, bboxes_):
for func, prob, args in tf_policy_:
image_, bboxes_ = _apply_func_with_prob(func, image_, args, prob, bboxes_)
return image_, bboxes_
return final_policy