#include <opencv2/opencv.hpp>
#include <vector>
#include <cmath>
struct Point3D { float x, y, z; };
struct Triangle { Point3D v1, v2, v3; };
// 正交投影矩阵生成
cv::Mat getOrthoProjection(float l, float r, float b, float t, float n, float f) {
return (cv::Mat_<float>(4, 4) <<
2 / (r - l), 0, 0, -(r + l) / (r - l),
0, 2 / (t - b), 0, -(t + b) / (t - b),
0, 0, -2 / (f - n), -(f + n) / (f - n),
0, 0, 0, 1);
}
// 视图变换矩阵
cv::Mat getViewMatrix(char view) {
switch (view) {
case 'F': return cv::Mat::eye(4, 4, CV_32F); // Front
case 'B': return (cv::Mat_<float>(4, 4) << // Back
-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1);
case 'L': return (cv::Mat_<float>(4, 4) << // Left
0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1);
case 'R': return (cv::Mat_<float>(4, 4) << // Right
0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 0, 1);
case 'T': return (cv::Mat_<float>(4, 4) << // Top
1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1);
case 'U': return (cv::Mat_<float>(4, 4) << // Bottom
1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1);
default: return cv::Mat::eye(4, 4, CV_32F);
}
}
void renderView(const std::vector<Triangle>& mesh, char view, const std::string& filename) {
const int IMG_SIZE = 512;
cv::Mat image(IMG_SIZE, IMG_SIZE, CV_8UC3, cv::Scalar(255, 255, 255));
// 获取变换矩阵
cv::Mat viewMat = getViewMatrix(view);
cv::Mat projMat = getOrthoProjection(-1, 1, -1, 1, -1, 1);
// 处理每个三角形
for (const auto& tri : mesh) {
std::vector<cv::Point> points;
for (int i = 0; i < 3; i++) {
const Point3D& v = (i == 0) ? tri.v1 : (i == 1) ? tri.v2 : tri.v3;
// 应用视图变换和投影
cv::Mat point = (cv::Mat_<float>(4, 1) << v.x, v.y, v.z, 1);
point = projMat * viewMat * point;
// 转换为图像坐标
int x = (point.at<float>(0) + 1) * 0.5 * IMG_SIZE;
int y = IMG_SIZE - (point.at<float>(1) + 1) * 0.5 * IMG_SIZE;
points.emplace_back(x, y);
}
// 绘制三角形边框
cv::polylines(image, points, true, cv::Scalar(0, 0, 0), 1);
}
cv::imwrite(filename, image);
}
int main() {
// 示例三角形数据(实际应从STL文件读取)
std::vector<Triangle> mesh = {
{{0,0,0}, {1,0,0}, {0,1,0}},
{{0,0,1}, {1,0,1}, {0,1,1}}
};
// 生成6视图
renderView(mesh, 'F', "front.bmp");
renderView(mesh, 'B', "back.bmp");
renderView(mesh, 'L', "left.bmp");
renderView(mesh, 'R', "right.bmp");
renderView(mesh, 'T', "top.bmp");
renderView(mesh, 'U', "bottom.bmp");
return 0;
}
根据实际情景补全这段代码
最新发布