将数学函数从 Python 转换为 C++

Posted

技术标签:

【中文标题】将数学函数从 Python 转换为 C++【英文标题】:Converting Math functions from Python to c++ 【发布时间】:2018-08-22 15:14:06 【问题描述】:

我正在尝试将一些 opencv 代码从 python 转换为 c++,但我有点迷茫。蟒蛇是:

if 0 < R[1,1] < 1:
    # If it gets here, the pose is flipped.

    # Flip the axes. E.g., Y axis becomes [-y0, -y1, y2].
    R *= np.array([
        [ 1, -1,  1],
        [ 1, -1,  1],
        [-1,  1, -1],
    ])

    # Fixup: rotate along the plane spanned by camera's forward (Z) axis and vector to marker's position
    forward = np.array([0, 0, 1])
    tnorm = T / np.linalg.norm(T)
    axis = np.cross(tnorm, forward)
    angle = -2*math.acos(tnorm @ forward)
    R = cv2.Rodrigues(angle * axis)[0] @ R

到目前为止我有:

cv::Mat R;
if (0 < R.at<double>(1, 1) < 1) 

            // Flip the axes.E.g., Y axis becomes[-y0, -y1, y2].
            float mult[9] =  1, -1, 1, 1, -1, 1,-1, 1, -1 ;

            cv::Mat FlipAxes = cv::Mat(3, 3, CV_32F, mult);

            R *= FlipAxes;

                //# Fixup: rotate along the plane spanned by camera's forward (Z) axis and vector to marker's position
            cv::Vec3d forward(0, 0, 1);
            double tnorm = tvecBest / np.linalg.norm(T)
            axis = np.cross(tnorm, forward)
            angle = -2 * math.acos(tnorm @ forward)
            R = cv2.Rodrigues(angle * axis)[0] * R


        

我迷路了:

double tnorm = tvecBest / np.linalg.norm(T)
axis = np.cross(tnorm, forward)
angle = -2 * math.acos(tnorm @ forward)

c++ opencv 中np.linalg.norm 的等价物是什么?

【问题讨论】:

没有一个可以直接使用 cv::sqrt() 和 cv::pow() 你能给我一个代码示例吗? norm怎么样,还是直接用normalize 谢谢,我可以这样做吗?:cv::Vec3d tvecNorm(tvecBest); cv::normalize(tvecNorm, tvecNorm); @anti 是的,应该可以。 【参考方案1】:

np.linalg.norm(T) 只是 L2 范数:

sqrt(T[0]*T[0]+T[1]*T[1]+T[2]*T[2]) 

np.cross(tnorm, forward) 是叉积:

axis[0] = tnorm[1]*forward[2]-tnorm[2]*forward[1]
axis[1] = -tnorm[0]*forward[2]+tnorm[2]*forward[0]
axis[2] = tnorm[0]*forward[1]-tnorm[1]*forward[0]

【讨论】:

谢谢!所以这给了我:cv::Vec3d forward(0, 0, 1); cv::Vec3d T(tvecBest); cv::Vec3d tnorm = sqrt(T[0] * T[0] + T[1] * T[1] + T[2] * T[2]); cv::Vec3d axis; axis[0] = tnorm[1] * forward[2] - tnorm[2] * forward[1]; axis[1] = -tnorm[0] * forward[2] + tnorm[2] * forward[0]; axis[2] = tnorm[0] * forward[1] - tnorm[1] * forward[0]; c++ 是干什么用的:cv::Vec3d angle = -2 * math.acos(tnorm @ forward) @ 不是 python 中的数学运算符。是 / 运算符吗? 从我读到的意思是@是一个点积:tnorm @ forward -> tnorm[0]*forward [0]+ tnorm[1]*forward [1]+ tnorm[2] *转发[2] 并且角度必须是双精度:双精度角 = -2 * acos( tnorm[0]*forward [0]+ tnorm[1]*forward [1]+ tnorm[2]*forward [ 2])

以上是关于将数学函数从 Python 转换为 C++的主要内容,如果未能解决你的问题,请参考以下文章

Python函数:内置函数(数学运算函数类型转换函数)

将数学公式转换为 Oracle 函数

将数学表达式转换为python表达式?

Python数学模块毕业

数学转换 sRGB 和 Adob​​eRGB

将包含数学的字符串转换为整数的递归函数