C ++计算机视觉透视渲染

时间:2016-09-29 19:16:48

标签: c++ computer-vision

我有一个顶点坐标文件。我在显示通过将每个坐标与线段连接而产生的图像时出现问题。我遇到了无数的错误。有任何帮助或想法来解决问题吗?

bool computePixelCoordinates(
const Vec3f &pWorld,
const Matrix44f &cameraToWorld,
const float &canvasWidth,
const float &canvasHeight,
const int &imageWidth,
const int &imageHeight,
Vec2i &pRaster)
{
// First transform the 3D point from world space to camera space. 
// It is of course inefficient to compute the inverse of the cameraToWorld
// matrix in this function. It should be done outside the function, only once
// and the worldToCamera should be passed to the function instead. 
// We are only compute the inverse of this matrix in this function ...
Vec3f pCamera;
Matrix44f worldToCamera = cameraToWorld.inverse();
worldToCamera.multVecMatrix(pWorld, pCamera);
// Coordinates of the point on the canvas. Use perspective projection.
Vec2f pScreen;
pScreen.x = pCamera.x / -pCamera.z;
pScreen.y = pCamera.y / -pCamera.z;
// If the x- or y-coordinate absolute value is greater than the canvas width 
// or height respectively, the point is not visible
if (std::abs(pScreen.x) > canvasWidth || std::abs(pScreen.y) > canvasHeight)
return false;
// Normalize. Coordinates will be in the range [0,1]
Vec2f pNDC;
pNDC.x = (pScreen.x + canvasWidth / 2) / canvasWidth;
pNDC.y = (pScreen.y + canvasHeight / 2) / canvasHeight;
// Finally convert to pixel coordinates. Don't forget to invert the y coordinate
pRaster.x = std::floor(pNDC.x * imageWidth);
pRaster.y = std::floor((1 - pNDC.y) * imageHeight);

return true;
}

int main(...)
{
...
Matrix44f cameraToWorld(...);
Vec3f pWorld(...);
float canvasWidth = 2, canvasHeight = 2;
uint32_t imageWidth = 512, imageHeight = 512;
// The 2D pixel coordinates of pWorld in the image if the point is visible
Vec2i pRaster;
if (computePixelCoordinates(pWorld, cameraToWorld, canvasWidth, canvasHeight, imageWidth, imageHeight, pRaster)) {
std::cerr << "Pixel coordinates " << pRaster << std::endl;
}
else {
std::cert << Pworld << " is not visible" << std::endl;
}
...

return 0;
} 

1 个答案:

答案 0 :(得分:0)

此代码使用库进行矩阵运算,该库定义类似Matrix44fVec3f的类型。您需要获取此库,包含相应的标题,并链接它。