1.recursive_bezier用以实现De Casteljau算法
cv::Point2f recursive_bezier(const std::vector<cv::Point2f> &control_points, float t)
{// TODO: Implement de Casteljau's algorithm//return cv::Point2f();if (control_points.size() < 2){return control_points[0];}std::vector<cv::Point2f> temp_control_points = {};for (int i = 0; i < control_points.size() - 1; i++){cv::Point2f temp_point = (1 - t) * control_points[i] + t * control_points[i + 1];temp_control_points.push_back(temp_point);}return recursive_bezier(temp_control_points, t); }
2.bezier调用recursive_bezier函数,指定每次计算目标点坐标时使用的t值。
bezier每次传入的t都会返回一个在对应t下贝塞尔曲线上的点。
void bezier(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 (double t = 0.0; t <= 1.0; t += 0.001){cv::Point2f point = recursive_bezier(control_points, t);window.at<cv::Vec3b>(point.y, point.x)[1] = 255;}
3.修改点的数量
修改点的数量只需要修改mouse_handler里的点的数量的限制和main函数点的数量
void mouse_handler(int event, int x, int y, int flags, void *userdata)
{if (event == cv::EVENT_LBUTTONDOWN && control_points.size() < 5) {std::cout << "Left button of the mouse is clicked - position (" << x << ", "<< y << ")" << '\n';control_points.emplace_back(x, y);} }if (control_points.size() == 5) {naive_bezier(control_points, window);bezier(control_points, window);cv::imshow("Bezier Curve", window);cv::imwrite("my_bezier_curve.png", window);key = cv::waitKey(0);return 0;}
结果