作者:翟天保Steven
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处
功能函数
// 绘制虚线
void DrawDottedLine(cv::Mat &input, cv::Point p1, cv::Point p2, cv::Scalar color, int thickness, int len)
{// 分段double line_length = std::sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y));double num_dashes = line_length / len;double x_increment = (p2.x - p1.x) / num_dashes;double y_increment = (p2.y - p1.y) / num_dashes;// 间隔绘制for (int i = 0; i < num_dashes; ++i) {if (i % 2 == 0) {cv::Point start(p1.x + i * x_increment, p1.y + i * y_increment);cv::Point end(p1.x + (i + 1) * x_increment, p1.y + (i + 1) * y_increment);cv::line(input, start, end, color, thickness);}}
}
测试代码
#include <iostream>
#include <opencv2/opencv.hpp>using namespace std;
using namespace cv;// 绘制虚线
void DrawDottedLine(cv::Mat &input, cv::Point p1, cv::Point p2, cv::Scalar color, int thickness, int len)
{// 分段double line_length = std::sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y));double num_dashes = line_length / len;double x_increment = (p2.x - p1.x) / num_dashes;double y_increment = (p2.y - p1.y) / num_dashes;// 间隔绘制for (int i = 0; i < num_dashes; ++i) {if (i % 2 == 0) {cv::Point start(p1.x + i * x_increment, p1.y + i * y_increment);cv::Point end(p1.x + (i + 1) * x_increment, p1.y + (i + 1) * y_increment);cv::line(input, start, end, color, thickness);}}
}int main()
{// 绘制虚线cv::Mat test = cv::Mat::zeros(100, 100, CV_8UC1);cv::Point p1(20, 20);cv::Point p2(80, 80);DrawDottedLine(test, p1, p2, cv::Scalar(255), 1, 3);return 0;
}
测试效果
这是斜向线和水平的效果图。可以通过调节len来改变虚线中实线的长度。
如果文章帮助到你了,可以点个赞让我知道,我会很快乐~加油!