使用OpenCV在图像上绘制带刻度线的十字线,可以通过以下步骤实现。我们将首先找到图像的中心点,然后绘制水平和垂直线,并在这些线的适当位置绘制刻度线。以下是详细的C++代码示例:
#include<opencv2\opencv.hpp>
//画十字标注线带刻度线,以图像中心点为0点
void DrawCross_new(cv::Mat& mat, double dFactor)
{cv::Scalar color = cv::Scalar(0, 0, 255);if (mat.empty()){return;}int nSizeFace = cv::FONT_HERSHEY_PLAIN;int ShortLineSize = 6;int LenghtLineSize = 12;double testsie = 0.35;int Linesize = 1;cv::Point CenterPoint = cv::Point(mat.cols / 2.0, mat.rows / 2.0);cv::Point Point{};//画十字对角cv::line(mat, cv::Point(CenterPoint.x, 0), cv::Point(CenterPoint.x, mat.rows), color, 1);//竖线cv::line(mat, cv::Point(0, CenterPoint.y), cv::Point(mat.cols, CenterPoint.y), color, 1);//横线//画X左刻度线for (int i_left = 1; i_left < int(CenterPoint.x / dFactor) + 1; i_left++){Point = cv::Point(CenterPoint.x - dFactor * i_left, CenterPoint.y);if (i_left % 5 == 0) {//画长线cv::line(mat, Point, cv::Point(Point.x, Point.y - LenghtLineSize), color, Linesize);//横线cv::putText(mat, std::to_string(i_left), cv::Point(Point.x - dFactor, Point.y - LenghtLineSize - 5), cv::FONT_HERSHEY_SIMPLEX, testsie, color, 1);}else{//画短线cv::line(mat, Point, cv::Point(Point.x, Point.y - ShortLineSize), color, Linesize);//横线}}//画X右刻度线for (int i_right = 1; i_right < int(CenterPoint.x / dFactor) + 1; i_right++){Point = cv::Point(CenterPoint.x + dFactor * i_right, CenterPoint.y);if (i_right % 5 == 0) {//画长线cv::line(mat, Point, cv::Point(Point.x, Point.y - LenghtLineSize), color, Linesize);//横线cv::putText(mat, std::to_string(i_right), cv::Point(Point.x - dFactor, Point.y - LenghtLineSize - 5), cv::FONT_HERSHEY_SIMPLEX, testsie, color, 1);}else{//画短线cv::line(mat, Point, cv::Point(Point.x, Point.y - ShortLineSize), color, Linesize);//横线}}//画Y上刻度线for (int i_up = 1; i_up < int(CenterPoint.y / dFactor) + 1; i_up++){Point = cv::Point(CenterPoint.x, CenterPoint.y - dFactor * i_up);if (i_up % 5 == 0) {//画长线cv::line(mat, Point, cv::Point(Point.x - LenghtLineSize, Point.y), color, Linesize);//横线cv::putText(mat, std::to_string(i_up), cv::Point(Point.x - LenghtLineSize * 3, Point.y + dFactor / 2.0), cv::FONT_HERSHEY_SIMPLEX, testsie, color, 1);}else{//画短线cv::line(mat, Point, cv::Point(Point.x - ShortLineSize, Point.y), color, Linesize);//横线}}//画Y下刻度线for (int i_down = 1; i_down < int(CenterPoint.y / dFactor) + 1; i_down++){Point = cv::Point(CenterPoint.x, CenterPoint.y + dFactor * i_down);if (i_down % 5 == 0) {//画长线cv::line(mat, Point, cv::Point(Point.x - LenghtLineSize, Point.y), color, Linesize);//横线cv::putText(mat, std::to_string(i_down), cv::Point(Point.x - LenghtLineSize * 3, Point.y + dFactor / 2.0), cv::FONT_HERSHEY_SIMPLEX, testsie, color, 1);}else{//画短线cv::line(mat, Point, cv::Point(Point.x - ShortLineSize, Point.y), color, Linesize);//横线}}
}
//测试程序
int main() {// 创建一个空白图像int width = 800;int height = 600;cv::Mat image = cv::Mat::zeros(height, width, CV_8UC3);int tickLength = 5; // 绘制带刻度线的十字线DrawCross_new(image, tickLength);// 显示图像cv::imshow("Crosshair with Ticks", image);cv::waitKey(0);return 0;
}
绘画的结果如下图所示: