算法小抄-CV3D-优化问题求解

0. 优化问题

线性

区分齐次和非齐次,齐次的用svd分解,非齐次的用伪逆求解

U, S, Vt = np.linalg.svd(A, full_matrices=True)
x = Vt[-1].T
print(x / -x[1])

非线性

一阶迭代

随机梯度下降/SGD variants: AdaGrad, RMSProp, Adam,

二阶迭代

牛顿法

1. 一个例子直线拟合问题

2. CV3D中的优化问题

线性

仿射变换矩阵求解

def getAffineTransform(src, dst):
    if len(src) == len(dst):
    # Solve 'Ax = b'
    A, b = [], []
    for p, q in zip(src, dst):
    A.append([p[0], p[1], 0, 0, 1, 0])
    A.append([0, 0, p[0], p[1], 0, 1])
    b.append(q[0])
    b.append(q[1])
    x = np.linalg.pinv(A) @ b
    # Reorganize `x` as a matrix
    H = np.array([[x[0], x[1], x[4]], [x[2], x[3], x[5]]])
    return H


if __name__ == '__main__':
    src = np.array([[115, 401], [776, 180], [330, 793]], dtype=np.float32)
    dst = np.array([[0, 0], [900, 0], [0, 500]], dtype=np.float32)
    my_H = getAffineTransform(src, dst)
    cv_H = cv.getAffineTransform(src, dst) # Note) It accepts only 3 pairs of points.

平面单应性求解

def getPerspectiveTransform(src, dst):
    if len(src) == len(dst):
        # Make homogeneous coordiates if necessary
        if src.shape[1] == 2:
         src = np.hstack((src, np.ones((len(src), 1), dtype=src.dtype)))
        if dst.shape[1] == 2:
         dst = np.hstack((dst, np.ones((len(dst), 1), dtype=dst.dtype)))
        # Solve 'Ax = 0'
        A = []
        for p, q in zip(src, dst):
            A.append([0, 0, 0, q[2]*p[0], q[2]*p[1], q[2]*p[2], -q[1]*p[0], -q[1]*p[1], -q[1]*p[2]])
            A.append([q[2]*p[0], q[2]*p[1], q[2]*p[2], 0, 0, 0, -q[0]*p[0], -q[0]*p[1], -q[0]*p[2]])
        _, _, Vt = np.linalg.svd(A, full_matrices=True)
        x = Vt[-1]
        # Reorganize `x` as a matrix
        H = x.reshape(3, -1) / x[-1] # Normalize the last element as 1
        return H

基础矩阵求解

def findFundamentalMat(pts1, pts2):
    if len(pts1) == len(pts2):
        # Make homogeneous coordiates if necessary
        if pts1.shape[1] == 2:
         pts1 = np.hstack((pts1, np.ones((len(pts1), 1), dtype=pts1.dtype)))
        if pts2.shape[1] == 2:
         pts2 = np.hstack((pts2, np.ones((len(pts2), 1), dtype=pts2.dtype)))
        # Solve 'Ax = 0'
        A = []
        for p, q in zip(pts1, pts2):
            A.append([q[0]*p[0], q[0]*p[1], q[0]*p[2], q[1]*p[0], q[1]*p[1], q[1]*p[2], q[2]*p[0], q[2]*p[1], q[2]*p[
        _, _, Vt = np.linalg.svd(A, full_matrices=True)
        x = Vt[-1]
        # Reorganize `x` as `F` and enforce 'rank(F) = 2'
        F = x.reshape(3, -1)
        U, S, Vt = np.linalg.svd(F)
        S[-1] = 0
        F = U @ np.diag(S) @ Vt
        return F / F[-1,-1] # Normalize the last element as 1

三角化求解

def triangulatePoints(P0, P1, pts0, pts1):
    Xs = []
    for (p, q) in zip(pts0.T, pts1.T):
        # Solve 'AX = 0'
        A = np.vstack((p[0] * P0[2] - P0[0],
        p[1] * P0[2] - P0[1],
        q[0] * P1[2] - P1[0],
        q[1] * P1[2] - P1[1]))
    _, _, Vt = np.linalg.svd(A, full_matrices=True)
    Xs.append(Vt[-1])
    return np.vstack(Xs).T

非线性

绝对位姿估计

import numpy as np
from scipy.optimize import least_squares
from scipy.spatial.transform import Rotation
import cv2 as cv

def project_no_distort(X, rvec, t, K):
    R = Rotation.from_rotvec(rvec.flatten()).as_matrix()
    XT = X @ R.T + t # Transpose of 'X = R @ X + t'
    xT = XT @ K.T # Transpose of 'x = KX'
    xT = xT / xT[:,-1].reshape((-1, 1)) # Normalize
    return xT[:,0:2]

def reproject_error_pnp(unknown, X, x, K):
    rvec, tvec = unknown[:3], unknown[3:]
    xp = project_no_distort(X, rvec, tvec, K)
    err = x - xp
    return err.ravel()

def solvePnP(obj_pts, img_pts, K):
    unknown_init = np.array([0, 0, 0, 0, 0, 1.]) # Sequence: rvec(3), tvec(3)
    result = least_squares(reproject_error_pnp, unknown_init, args=(obj_pts, img_pts, K))
    return result['success'], result['x'][:3], result['x'][3:]

相机标定

def fcxcy_to_K(f, cx, cy):
 return np.array([[f, 0, cx], [0, f, cy], [0, 0, 1]])

def reproject_error_calib(unknown, Xs, xs):
    K = fcxcy_to_K(*unknown[0:3])
    err = []
    for j in range(len(xs)):
        offset = 3 + 6 * j
        rvec, tvec = unknown[offset:offset+3], unknown[offset+3:offset+6]
        xp = project_no_distort(Xs[j], rvec, tvec, K)
        err.append(xs[j] - xp)
    return np.vstack(err).ravel()

def calibrateCamera(obj_pts, img_pts, img_size):
    img_n = len(img_pts)
    unknown_init = np.array([img_size[0], img_size[0]/2, img_size[1]/2] \
    + img_n * [0, 0, 0, 0, 0, 1.]) # Sequence: f, cx, cy, img_n * (rvec, tvec)
    result = least_squares(reproject_error_calib, unknown_init, args=(obj_pts, img_pts))
    K = fcxcy_to_K(*result['x'][0:3])
    rvecs = [result['x'][(6*i+3):(6*i+6)] for i in range(img_n)]
    tvecs = [result['x'][(6*i+6):(6*i+9)] for i in range(img_n)]
    return result['cost'], K, np.zeros(5), rvecs, tvecs

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Leetcode算法小抄是一份权威的算法手册,包含了Leetcode上常见的算法题目的解法和详细讲解。这个小抄对于想要提升自己算法能力的程序员来说非常有用。该小抄包括以下内容: 1.基础数据结构:包括数组、链表、栈、队列、树、哈希表等。 2.算法基础:包括排序算法、搜索算法、贪心算法、动态规划等。 3.高级算法:包括图论、字符串匹配、线性代数、计算几何等。 每个算法题目都附有详细的解析和代码实现,方便程序员进行学习和练习。此外,该小抄还提供了优秀的算法实现其他程序员的思路和解答,这对于新手来说尤为重要。 总之,Leetcode算法小抄是一份非常实用的算法手册,如果你想成为一名出色的程序员,学习和掌握其中的内容必不可少。 ### 回答2: LeetCode算法小抄是一份非常实用的算法指南,它包含了大量的算法问题和解答,而且所有的算法问题都是以LeetCode网站上的题目为蓝本的。这个小抄主要面向准备参加Google、Facebook、 Apple等知名科技公司的笔试或者面试的程序员,也适用于想要提高自己算法能力的人。这份小抄的编制者是Steven Halim和Felix Halim,也就是ACM竞赛的著名选手和教练。他们将自己多年的ACM竞赛经验倾囊相授,帮助大家提高算法能力。小抄中包含了高频出现的数据结构和算法,如树、图、排序、数组、动态规划等,每个算法都有详细的解释和代码实现。此外,小抄还包含了一些实用技巧,如测试用例设计、代码调试、复杂度分析等。总之,LeetCode算法小抄是一份非常实用、全面的算法指南,如果你想要提高自己的算法能力,相信它一定能为你带来帮助。 ### 回答3: LeetCode算法小抄是一个常用的算法学习工具,它主要是为了帮助程序员更加高效地学习和掌握LeetCode算法。LeetCode算法小抄中收录了大量经典的算法题目,并提供了详细的题解和代码示例,涵盖了各种数据结构、算法和编程技术。 LeetCode算法小抄的优点在于它的简便性和针对性。其内容结构清晰,难度逐渐增加,让读者能够逐步学习并掌握更加复杂的数据结构和算法。同时,小抄中提供了大量的代码示例和优化方法,可以帮助读者更加深入地理解和掌握算法。 另外,LeetCode算法小抄还提供了各种算法题目的分类、标签和解法推荐,让读者能够更加容易地找到自己需要的题目和解法。同时,小抄中还提供了一些常见的面试题目和解题思路,可以帮助读者更好地应对工作中和面试中的挑战。 总之,LeetCode算法小抄是一本非常实用的算法学习工具,它可以帮助程序员更加高效地学习和掌握算法知识。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值