OpenCV_在图像上添加十字线

参考:OpenCV 绘制十字Mark标https://blog.csdn.net/kakiebu/article/details/111933184

调用: 

头文件里加入声明:

void DrawCross(cv::Mat& mat, cv::Point2i ptCenter, cv::Scalar color, double dFactor);

 函数定义:

void DrawCross(cv::Mat& mat, cv::Point2i ptCenter, cv::Scalar color, double dFactor)
{
	double dAxisOffset = 12;
	double dAxisLen = 24 * 10 + 12 - dAxisOffset;

	// 坐标轴属性 0=Y+ 1=X+ 2=Y- 3=X-
	double dDirX[] = { 0, 1, 0, -1 };
	double dDirY[] = { -1, 0, 1, 0 };

	// 刻度属性
	int nLabelSize = 9 + 5;
	double dLabelStep[] = { 12, 12, 12, 12, 12, 12, 12, 12, 12, 24, 24, 24, 24, 24 };
	double dLabelHeight[] = { 12, 6, 12, 6, 12, 6, 12, 6, 12, 12, 12, 12, 12, 12 };

	// 字符属性
	int nIdx5 = 8;
	int nIdx10 = 13;
	double nCharOffset = 6;
	double dCharH = 0;
	double dCharW = 0;

	for (int i = 0; i < 4; i++)
	{
		cv::Point AxisPtS, AxisPtE;

		// 绘制轴
		//AxisPtS.x = ptCenter.x + dAxisOffset / dFactor * dDirX[i];
		AxisPtS.x = rect1.Width()/2;
		//AxisPtS.y = ptCenter.y + dAxisOffset / dFactor * dDirY[i];
		AxisPtS.y = rect1.Height()/2;
		AxisPtE.x = AxisPtS.x + dAxisLen / dFactor * dDirX[i];
		AxisPtE.y = AxisPtS.y + dAxisLen / dFactor * dDirY[i];
		cv::line(mat, AxisPtS, AxisPtE, color, 1.5);

		// 绘制刻度
		double nSumStep = 0;
		for (int j = 0; j < nLabelSize; j++)
		{
			int i_ = (i + 1) % 4;
			cv::Point LabelPtS, LabelPtE;

			nSumStep += dLabelStep[j];
			LabelPtS.x = AxisPtS.x + nSumStep / dFactor * dDirX[i];
			LabelPtS.y = AxisPtS.y + nSumStep / dFactor * dDirY[i];
			LabelPtE.x = LabelPtS.x + dLabelHeight[j] / dFactor * dDirX[i_];
			LabelPtE.y = LabelPtS.y + dLabelHeight[j] / dFactor * dDirY[i_];

			cv::line(mat, LabelPtS, LabelPtE, color, 1);


			// 绘制数字
			if (j == nIdx5 || j == nIdx10)
			{
				//cv::string str = "";
				String str = "";
				if (j == nIdx5)
					str = "5";
				else
					str = "10";

				int baseline = 0;
				double dFactor = 1;
				int nSizeFace = cv::FONT_HERSHEY_PLAIN;

				cv::Size textSize = cv::getTextSize(str, nSizeFace, dFactor, 1, &baseline);
				dCharH = textSize.height;
				dCharW = textSize.width;

				if (i == 0) {
					LabelPtS.x = LabelPtE.x + nCharOffset;
					LabelPtS.y = LabelPtE.y + dCharH / 2;
				}
				if (i == 1) {
					LabelPtS.x = LabelPtE.x - dCharW / 2;
					LabelPtS.y = LabelPtE.y + nCharOffset + dCharH;
				}
				if (i == 2) {
					LabelPtS.x = LabelPtE.x - nCharOffset - dCharW;
					LabelPtS.y = LabelPtE.y + dCharH / 2;
				}
				if (i == 3) {
					LabelPtS.x = LabelPtE.x - dCharW / 2;
					LabelPtS.y = LabelPtE.y - nCharOffset;
				}

				cv::putText(mat, str, LabelPtS, nSizeFace, dFactor, color);
			}

		}

	}
}

 在获取图像后调用

 运行效果:

猜你喜欢

转载自blog.csdn.net/qq_36917144/article/details/124191434