2017-04-23 48 views
1

我希望有一位Python专家能够提供一些帮助,解决目前我正在使用内部函数,闭包和工厂函数时遇到的困惑。在寻找一个通用霍夫实现的例子变换,我发现这一点:Python - 内部函数,闭包和工厂函数 - 如何分解?

https://github.com/vmonaco/general-hough/blob/master/src/GeneralHough.py

我想转换成C++这一点,似乎第一步是分解出在general_hough_closure的内部函数() :

def general_hough_closure(reference_image): 
    ''' 
    Generator function to create a closure with the reference image and origin 
    at the center of the reference image 

    Returns a function f, which takes a query image and returns the accumulator 
    ''' 
    referencePoint = (reference_image.shape[0]/2, reference_image.shape[1]/2) 
    r_table = build_r_table(reference_image, referencePoint) 

    def f(query_image): 
     return accumulate_gradients(r_table, query_image) 

    return f 

我似乎被困在这个函数如何工作。 “f”似乎没有被调用到任何地方,我不确定函数如何知道“query_image”是什么?我尝试了各种谷歌搜索,以找到有关内部函数,闭包和工厂功能的提示,例如this和一些类似的页面,但我能找到的所有示例都更简单,因此帮助不大。任何人都可以提供一些方向吗?

+0

此代码__ *收益* A function__:

class GeneralHoughClosure { public: GeneralHoughClosure(reference_image) { referencePoint = (reference_image.shape[0]/2, reference_image.shape[1]/2) r_table = build_r_table(reference_image, referencePoint) } void Run(queryImage) { return accumulate_gradients(r_table, query_image) } void operator()(queryImage) { return accumulate_gradients(r_table, query_image) } } 

然后,您可以按以下方式使用它。你确定这就是你想要的吗?我怀疑你想在C++中做什么。 –

+0

@Rawing,我知道函数返回一个函数,这是我想分解的部分,所以我可以翻译成C++ – cdahms

+0

删除行'def f(query_image):',remove'return f ',给函数一个名为'query_image'的第二个参数。这应该很容易翻译。 –

回答

0

该代码只是返回函数f作为一个整体的事情。没有必要“知道什么是论据” - f在它被调用时会知道它。最典型的例子是这样的:

>>> def f(x): 
...  def g(y): 
...   return x + y 
...  return g 
... 
>>> f 
<function f at 0x7f8500603ae8> 
>>> f(1) 
<function f.<locals>.g at 0x7f8500603a60> 
>>> s = f(1) 
>>> s(2) 
3 

在这里,你的功能,g关闭了另一个值(xr_table,分别),但仍期待它的实际参数。

由于存在封闭值,因此不能直接分解出f。一种传统的方法是返回一个包含该值的对象,该对象具有某种代表该函数的调用方法;在C++中更简单的方法现在是使用lambda函数:

int f(int x) { 
    auto g = [x](int y) { 
    return x + y 
    }; 
    return g; 
} 

在C++中你有“优势”,它会骂你,如果没有指定哪些值你结束了(这是这里的[x] )。但是在内部,它几乎完成了同样的事情(构造一个带有x成员的匿名类)。

+0

如果我的C++格式不正确,请只编辑它,我实际上并不经常使用C++。 – phg

0

C++ 11之前的C++没有函数作为类型。

您可以使用下面的类来模拟语义(伪代码):

gg = new GeneralHoughClosure(reference_image) 
gg.Run(queryImage1) 
gg(queryImage2) 
+0

感谢您的建议,有没有一种方法可以在不添加类的情况下分解嵌套函数? – cdahms

+0

C++ 11具有类型的功能。你可以返回一个[std :: function](http://en.cppreference.com/w/cpp/utility/functional/function),用(lambda)(http://en.cppreference)初始化(例如)。com/w/cpp/language/lambda),就像你在python中一样。 – mdavezac

+0

你是对的,我更新了答案。 我们中的一些人没有奢侈品与C++ 11一起工作:-) – napuzba