C++的opencv写一个可以用滑动条调参的直线检测
时间: 2024-05-19 18:10:46 浏览: 17
好的,下面是一份可以用滑动条调参的直线检测的C++代码:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
Mat src, dst;
int threshold_value = 100;
int threshold_max = 255;
int line_value = 100;
int line_max = 200;
const char* window_name = "Line Detection";
void onThresholdChange(int, void*);
void onLineChange(int, void*);
int main(int argc, char** argv)
{
src = imread(argv[1], IMREAD_GRAYSCALE);
if (src.empty())
{
cout << "Could not open or find the image!\n" << endl;
return -1;
}
namedWindow(window_name, WINDOW_AUTOSIZE);
createTrackbar("Threshold", window_name, &threshold_value, threshold_max, onThresholdChange);
createTrackbar("Line Length", window_name, &line_value, line_max, onLineChange);
onThresholdChange(0, 0);
onLineChange(0, 0);
waitKey(0);
return 0;
}
void onThresholdChange(int, void*)
{
Canny(src, dst, threshold_value, threshold_value * 2);
imshow(window_name, dst);
}
void onLineChange(int, void*)
{
vector<Vec2f> lines;
HoughLines(dst, lines, 1, CV_PI / 180, line_value);
Mat lineImage = Mat::zeros(dst.size(), CV_8UC3);
for (size_t i = 0; i < lines.size(); i++)
{
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(lineImage, pt1, pt2, Scalar(0, 0, 255), 1, LINE_AA);
}
imshow(window_name, lineImage);
}
```
代码中使用了OpenCV的Canny边缘检测和Hough直线变换来实现直线检测。通过调整滑动条的值,可以实时更新图像并检测出不同长度的直线。