gpt4 book ai didi

python - 为什么用透视相机翻转轴?

转载 作者:太空宇宙 更新时间:2023-11-03 23:07:08 25 4
gpt4 key购买 nike

我正在尝试使用右手坐标系在 Python 中实现一个简单的透视相机,其中 +x 轴在右,+y 轴在上,+z 轴在屏幕外。

我有一些代码可以将点从 3D 世界坐标投影到 2D 图像坐标。为了测试它,我尝试沿 +X、+Y 和 +Z 轴投影三个单位矢量并渲染它们,但是当我这样做时,所有的点似乎都在“相机后面”,我希望看到这样的东西:

enter image description here

当我取消注释 l = -l 行时,所有出现的轴都翻转了,当我围绕原点旋转相机时,它们看不到在正确的平面上旋转。

enter image description here

这是显示问题的我的代码。我有什么误解吗?

import numpy as np
import cv2

def compute_focal(angle, dimension):
return dimension / 2.0 / np.tan( np.radians(angle) / .2)

# Positive camera at c looking at p with up=u http://ksimek.github.io/2012/08/22/extrinsic/
def lookat(c, p, u):
l = p - c
l = l / np.linalg.norm(l)
s = np.cross(l, u)
s = s / np.linalg.norm(s)
u = np.cross(s, l)

# uncomment this and the axis will appear by are all flipped
# l = -l

R = np.vstack( (s, u, -l))
Rc = R.T
return Rc

# project 3D point into camera define by projection matrix
def projectPoint(P, point):
xw, yw, zw = point
W = np.array([ [xw, yw, zw, 1] ]).T
xi, yi, zi = P.dot(W).flatten()

if zi < 0.0:
print("point {},{},{} is behind the camera!".format(xi, yi, zi))

xi = int(xi + 0.5)
yi = int(yi + 0.5)
return xi, yi

theta = 0

while True:
# used to rotate the camera around the y-axis looking at origin
theta += 1

w = h = 500
fx = fy = compute_focal(w, 45.)
cx = w / 2.
cy = h / 2.

K = np.array([ [fx, 0., cx], [0., fy, cy], [0., 0., 1.] ], dtype='float32')

# position of the camera in world coordintes 1-unit from the origin rotating around the y-axis looking at the origin
C = np.array([ np.sin(np.radians(theta)), 0, np.cos(np.radians(theta)) ])
# pointing towards the origin
P = np.array([ 0.0, 0.0, 0.0 ])
# up direction is along the positive y-axis
U = np.array([ 0, 1, 0 ])
Rc = lookat(C, P, U)

img = np.zeros((h, w, 3), dtype='uint8')

# create the projection matrix from camera position
R = Rc.T
t = R.dot( -np.reshape(C, (3, 1)) )
P = K.dot(np.hstack([R, t]))

# draw and project positive principle axes
x0, y0 = projectPoint(P, (0, 0, 0))
x1, y1 = projectPoint(P, (1, 0, 0))
x2, y2 = projectPoint(P, (0, 1, 0))
x3, y3 = projectPoint(P, (0, 0, 1))

# x-axis red
cv2.line(img, (x0, y0), (x1, y1), [0, 0, 255], 1)
# y-axis green
cv2.line(img, (x0, y0), (x2, y2), [0, 255, 0], 1)
# z-axis blue
cv2.line(img, (x0, y0), (x3, y3), [255, 0, 0], 1)

# flip image because opencv images have origin in top left
img = np.flipud(img)

cv2.imshow("camera", img)
cv2.waitKey(1)

最佳答案

如果我改为将内在矩阵更改为:

 K = np.array([
[fx, 0., -cx],
[0., fy, -cy],
[0., 0., -1.]
], dtype='float32')

这些条目被否定。我不确定为什么,但我在一些示例代码中看到并尝试了它并且它有效,尽管它非常不直观。

关于python - 为什么用透视相机翻转轴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com