- 操作系统:ubuntu22.04
- OpenCV版本:OpenCV4.9
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
该类用于从检测到的线段中提取一种称为 LBD (Line Band Descriptor) 的二值描述符。它在 OpenCV 的 line_descriptor 模块中实现,是当前最流行的直线特征描述方法之一。
功能概述
- 用于为检测到的线段(KeyLine)生成二进制描述符;
- 基于线段周围的梯度信息构建描述区域;
- 支持快速匹配(使用汉明距离);
- 是 LSD 直线检测器的配套描述子。
主要函数和方法
- 创建 BinaryDescriptor 对象
static BinaryDescriptor* cv::line_descriptor::BinaryDescriptor::createBinaryDescriptor();
或:
Ptr<BinaryDescriptor> bd = BinaryDescriptor::createBinaryDescriptor();
说明:
- 静态方法,用于创建一个 BinaryDescriptor 实例;
- 返回智能指针 Ptr,便于内存管理。
- compute() 方法:计算 LBD 描述符
void compute(InputArray image, std::vector<KeyLine>& keylines, OutputArray descriptors);
参数说明:
参数 | 类型 | 含义 |
---|---|---|
image | InputArray | 输入图像(通常是单通道灰度图) |
keylines | std::vector& | 由 LSD 等检测器提取出的线段列表 |
descriptors | OutputArray | 输出的描述符矩阵,每行对应一条线段的 LBD 特征向量 |
说明: |
- 根据输入图像和线段集合,计算每条线段的 LBD 描述符;
- 输出是一个 CV_8U 类型的矩阵,每一行是一个二值描述符(如 512 bit);
- 可以用 descriptors.type() == CV_8UC1 判断其类型。
- getDescriptorSize() 方法:获取描述符大小
int getDescriptorSize() const;
返回值:
- 描述符长度(以字节为单位),默认为 64 字节(即 512 bits)。
- getDescriptorType() 方法:获取描述符类型
int getDescriptorType() const;
返回值:
- 返回 CV_8UC1,表示描述符为 8 位无符号整型单通道数据。
代码示例
#include <opencv2/line_descriptor/descriptor.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;
using namespace cv::line_descriptor;
int main()
{
// 加载图像(灰度图)
Mat image = imread( "/media/dingxin/data/study/OpenCV/sources/images/Lenna.png", IMREAD_GRAYSCALE );
if ( image.empty() )
{
std::cerr << "无法加载图像!" << std::endl;
return -1;
}
// 2. 初始化 LSDDetector 和 BinaryDescriptor
Ptr< LSDDetector > lsd = LSDDetector::createLSDDetector();
Ptr< BinaryDescriptor > bd = BinaryDescriptor::createBinaryDescriptor();
// 3. 存储检测到的线段
std::vector< KeyLine > keylines;
// 4. 设置参数并检测线段
double scale = 2.0; // 尺度因子
int numOctaves = 1; // 金字塔层数
lsd->detect( image, keylines, scale, numOctaves );
if ( keylines.empty() )
{
std::cerr << "未检测到任何线段!请检查输入图像或调整检测参数。" << std::endl;
return -1;
}
else
{
std::cout << "检测到线段数量: " << keylines.size() << std::endl;
}
// 5. 使用 BinaryDescriptor 计算描述符
Mat descriptors;
bd->compute( image, keylines, descriptors );
// 打印描述符信息
std::cout << "Descriptors matrix size: " << descriptors.rows << " x " << descriptors.cols << std::endl;
// 可视化检测到的线段
Mat colorImage;
cvtColor( image, colorImage, COLOR_GRAY2BGR );
for ( const auto& line : keylines )
{
Point pt1( line.startPointX, line.startPointY );
Point pt2( line.endPointX, line.endPointY );
// 使用 cv::line 函数来绘制线段,而不是 KeyLine 对象的方法
cv::line( colorImage, pt1, pt2, Scalar( 0, 0, 255 ), 2 ); // 红色线条
}
imshow( "Detected Lines with Descriptors", colorImage );
waitKey( 0 );
return 0;
}
运行结果
检测到线段数量: 346
Descriptors matrix size: 346 x 32