voidmouse_handler(int event, int x, int y, int flags, void *userdata) { if (event == cv::EVENT_LBUTTONDOWN && control_points.size() < 4) { std::cout << "Left button of the mouse is clicked - position (" << x << ", " << y << ")" << '\n'; control_points.emplace_back(x, y); } }
voidnaive_bezier(const std::vector<cv::Point2f> &points, cv::Mat &window) { auto &p_0 = points[0]; auto &p_1 = points[1]; auto &p_2 = points[2]; auto &p_3 = points[3];
for (double t = 0.0; t <= 1.0; t += 0.001) { auto point = std::pow(1 - t, 3) * p_0 + 3 * t * std::pow(1 - t, 2) * p_1 + 3 * std::pow(t, 2) * (1 - t) * p_2 + std::pow(t, 3) * p_3;
voidbezier(const std::vector<cv::Point2f> &control_points, cv::Mat &window) { // TODO: Iterate through all t = 0 to t = 1 with small steps, and call de Casteljau's // recursive Bezier algorithm.
voidbezier(const std::vector<cv::Point2f> &control_points, cv::Mat &window) { // TODO: Iterate through all t = 0 to t = 1 with small steps, and call de Casteljau's // recursive Bezier algorithm. for (float t = 0; t <= 1; t += 0.001f) { auto point = recursive_bezier(control_points, t); window.at<cv::Vec3b>(point.y, point.x)[1] = 255; } }
朴素算法
由于给定的框架代码有四个控制点,所以我们可以向课程中那样依次推演:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
cv::Point2f recursive_bezier(const std::vector<cv::Point2f> &control_points, float t) { // TODO: Implement de Casteljau's algorithm auto p_0 = control_points[0]; auto p_1 = control_points[1]; auto p_2 = control_points[2]; auto p_3 = control_points[3];
auto p_01 = (1 - t) * p_0 + t * p_1; auto p_12 = (1 - t) * p_1 + t * p_2; auto p_23 = (1 - t) * p_2 + t * p_3;
auto p_012 = (1 - t) * p_01 + t * p_12; auto p_123 = (1 - t) * p_12 + t * p_23;