line()
是 OpenCV 中用于在图像上绘制直线的基本函数。下面是它的函数原型。
void cv::line(
InputOutputArray img, // 输入输出图像
Point pt1, // 直线起点
Point pt2, // 直线终点
const Scalar& color, // 线条颜色
int thickness = 1, // 线宽
int lineType = LINE_8, // 线型
int shift = 0 // 坐标点小数位数
);
下面将这个函数放到实际的应用场景中,如下所示
#include<opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat girl = imread("images/girl.jpg", IMREAD_COLOR);//3通道(CV_8UC3)
if (girl.empty()) {
return 0;
}
imshow("girl", girl);//显示图像
Scalar color(0, 0, 255);// 线条颜色
int thickness = 1;// 线宽
int lineType = LINE_8;// 线型
//画水平线
for (int i = 0; i < girl.rows; i += 100)
{
Point start(0, i);
Point end(girl.cols, i);
line(girl, start, end, color, thickness, lineType);
}
//画垂直线
for (int i = 0; i < girl.cols; i += 100)
{
Point start(i, 0);
Point end(i, girl.rows);
line(girl, start, end, color, thickness, lineType);
}
imshow("girl2", girl);
imwrite("girl2.jpg", girl);
waitKey(0);//等待按键
return 0;
}
首先加载一张图片,然后显示原图。

接着定义了线条的颜色和线宽,然后定义了线条的形状,lineType表示线型,值LINE_8表示默认值(连通线),线型是一个名为LineTypes的枚举,它的定义和说明如下:
enum LineTypes {
FILLED = -1,
LINE_4 = 4, //!< 4-connected line
LINE_8 = 8, //!< 8-connected line
LINE_AA = 16 //!< antialiased line
};
FILLED = -1
,主要用于闭合图形(如矩形、圆形等)的填充,当设置thickness = FILLED
或thickness = -1
时,图形会被完全填充。特别注意:在line()
函数中不能使用,因为直线无法被填充,适用于rectangle()
,circle()
,ellipse()
等绘制闭合图形的函数。LINE_4 = 4
,使用 Bresenham 算法,只允许水平、垂直和对角线(45度)移动,每个像素只与上下左右4个相邻像素连接,斜线会有锯齿,但速度快。LINE_8 = 8
,使用改进的 Bresenham 算法,允许水平、垂直和所有对角线方向移动,每个像素与周围8个相邻像素连接,特点是比LINE_4平滑,开销适中。LINE_AA = 16
,使用高斯滤波等技术,通过部分透明像素平滑边缘,特点是视觉效果平滑,但开销大。
最后,使用for语句,分别绘制水平直线和垂直直线,如下所示。

——重庆教主 2025年5月15日
若文章对您有帮助,可以激励一下我哦,祝您平安幸福!
微信 | 支付宝 |
---|---|
![]() |
![]() |