- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
cv::plot::Plot2d 是 OpenCV 的 plot 模块中的一个类,用于在图像上绘制二维图形。它提供了便捷的方法来可视化数据,例如将数值数据绘制成折线图等,非常适合快速查看实验结果、调试算法或生成报告图表。
主要成员函数
-
static Ptr create(InputArray dataX, InputArray dataY)
功能:静态工厂方法,创建 Plot2d 实例。
参数:
dataX: X 轴数据点集合(可选,如果为空,则使用默认的索引作为 X 轴)。
dataY: Y 轴数据点集合(必需)。
返回:Ptrcv::plot::Plot2d 智能指针。
示例:
cv::Mat yData = (cv::Mat_<float>({1, 2, 3, 4, 5}));
auto plot = cv::plot::Plot2d::create(cv::Mat(), yData);
-
virtual void render(OutputArray _plotImage) const
功能:渲染图形到指定的 cv::Mat 图像。
参数:
_plotImage: 输出图像,图形将会被绘制在此图像上。通常是一个空白图像(cv::Mat(height, width, CV_8UC3))。
示例:
cv::Mat plotImage(400, 600, CV_8UC3, cv::Scalar(255, 255, 255));
plot->render(plotImage);
cv::imshow("Plot", plotImage);
cv::waitKey();
-
void setMinX(double minX)
功能:设置 X 轴最小值。
参数:minX - 新的 X 轴最小值。 -
void setMaxX(double maxX)
功能:设置 X 轴最大值。
参数:maxX - 新的 X 轴最大值。 -
void setMinY(double minY)
功能:设置 Y 轴最小值。
参数:minY - 新的 Y 轴最小值。 -
void setMaxY(double maxY)
功能:设置 Y 轴最大值。
参数:maxY - 新的 Y 轴最大值。 -
void setPlotLineColor(Scalar plotLineColor)
功能:设置绘制线条的颜色。
参数:plotLineColor - 颜色(例如 cv::Scalar(255, 0, 0) 表示红色)。 -
void setPlotBackgroundColor(Scalar plotBackgroundColor)
功能:设置背景颜色。
参数:plotBackgroundColor - 背景颜色。 -
void setPlotTextColor(Scalar plotTextColor)
功能:设置文本颜色(如轴标签)。
参数:plotTextColor - 文本颜色。 -
void setPlotGridColor(Scalar plotGridColor)
功能:设置网格线颜色。
参数:plotGridColor - 网格线颜色。 -
void setShowGrid(bool showGrid)
功能:是否显示网格线。
参数:showGrid - 布尔值,true 显示网格线,false 不显示。 -
void setPlotSize(int plotWidth, int plotHeight)
功能:设置绘图区域大小。
参数:
plotWidth - 宽度。
plotHeight - 高度。
使用示例
#include <opencv2/opencv.hpp>
#include <opencv2/plot.hpp>
int main()
{
// 准备数据
cv::Mat xData = ( cv::Mat_< double >( { 0, 1, 2, 3, 4, 5 } ) ); // X 轴数据
cv::Mat yData = ( cv::Mat_< double >( { 0, 1, 4, 9, 16, 25 } ) ); // Y 轴数据
// 创建 Plot2d 对象
auto plot = cv::plot::Plot2d::create( xData, yData );
// 设置属性(可选)
plot->setPlotLineColor( cv::Scalar( 255, 0, 0 ) ); // 红色线条
plot->setShowGrid( true ); // 显示网格线
// 创建空白画布
cv::Mat plotImage( 400, 600, CV_8UC3, cv::Scalar( 255, 255, 255 ) );
// 渲染图形
plot->render( plotImage );
// 显示结果
cv::imshow( "Plot", plotImage );
cv::waitKey();
return 0;
}