我正在尝试使用Python的右手坐标系实现一个简单的透视相机,其中+ x轴是正确的,+ y轴是向上的,而+ z轴是在屏幕之外的。
我有一些代码可以将点从3D世界坐标投影到2D图像坐标。为了测试它,我尝试沿+ X,+ Y和+ Z轴投影三个单位矢量并进行渲染,但是当我这样做时,所有的点似乎都在“相机后面”,正如我希望看到的那样:
当我取消注释l = -l
行时,所有出现的轴都被翻转,并且当我绕着原点指向旋转照相机时,它们看不到在正确的平面上旋转。
这是显示该问题的代码。有什么我误会的东西吗?
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)
答案 0 :(得分:0)
如果我改为将内在矩阵更改为:
K = np.array([
[fx, 0., -cx],
[0., fy, -cy],
[0., 0., -1.]
], dtype='float32')
否定这些条目。我不知道为什么,但是我看了一些示例代码并尝试了它,尽管它很不直观。