Python 3.x 创建包装器以从现有函数返回特定值
嗨,我有一个函数叫做Python 3.x 创建包装器以从现有函数返回特定值,python-3.x,Python 3.x,嗨,我有一个函数叫做 tfnet.return_predict() 当在图像上运行时,会输出某些集合o值,例如对象置信度类别和边界框坐标。我想做的是做一个只返回置信值的包装器 所以我的代码如下。我正在使用暗流对图像上的类进行预测 #Initialise Libraries # Load the YOLO Neural Network tfnet = TFNet(options) #call the YOLO network image = cv2.imread('C:/darkflow/C
tfnet.return_predict()
当在图像上运行时,会输出某些集合o值,例如对象置信度类别和边界框坐标。我想做的是做一个只返回置信值的包装器
所以我的代码如下。我正在使用暗流对图像上的类进行预测
#Initialise Libraries
# Load the YOLO Neural Network
tfnet = TFNet(options) #call the YOLO network
image = cv2.imread('C:/darkflow/Car.jpg', cv2.IMREAD_COLOR) #Load image
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
print(tfnet.return_predict(image)) #function to run predictions
打印输出为
[{'label': 'Car', 'confidence': 0.32647023, 'topleft': {'x': 98, 'y': 249}, 'bottomright': {'x': 311, 'y': 455}}]
因此,我想创建一个只返回“信心”值的包装器
我知道如何创建包装器并为其定义函数,但知道如何为已定义的函数进行包装
任何建议对我都有很大帮助
编辑:我试过:
def log_calls(tfnet.return_predict):
def wrapper(*args, **kwargs):
#name = func.__name__
print('before {name} was called')
r = func(*args, **kwargs)
print('after {name} was called')
return r
return wrapper
但是“tfnet.return\u predict”正在返回错误
SyntaxError: invalid syntax
是否需要重新定义
tfnet.return\u predict
函数以仅返回置信度?或者有一个单独的功能可以吗?如果是后者,那么你似乎可以这样做:
def conf_仅限(*args,**kwargs):
out=tfnet.return\u predict(*args,**kwargs)
返回[0][“信心”]
并且只调用conf_
只返回dict的这一部分
如果您需要重新定义tfnet.return\u predict,并且希望它只返回置信度
,那么您可以制作一个装饰器:
def conf_deco(func):
def包装(*args,**kwargs):
return func(*args,**kwargs)[0][“信心”]
返回包装器
例如,假装dummy\u函数
已经预定义
def dummy_function(*args, **kwargs):
print(args, kwargs)
return [{"confidence": .32, "other": "asdf"}]
现在用以下内容重新定义它:
In [6]: dummy_function = conf_deco(dummy_function)
它只会返回置信度值
In [7]: dummy_function("something", kw='else')
('something',) {'kw': 'else'}
Out[7]: 0.32
嘿@Scott Staniewicz谢谢你的快速回复。第一个代码返回“列表索引必须是整数或片,而不是str”。所以我改为“return out[0]”,它返回了{'label':'Carrr','confidence':0.32647023,'topleft':{'x':98,'y':249},'bottomright':{'x':311,'y':455},但都在一个新行中。所以现在我只需要进入第二条线来获得信心。我没有试过做一个装饰师。遗憾的是,我只能在星期一做。但无论如何都会让你知道哦,我看到你发布的输出是一个包含在列表中的dict-我相应地编辑了答案
In [7]: dummy_function("something", kw='else')
('something',) {'kw': 'else'}
Out[7]: 0.32