一张图像上有一把刻度尺尺子上有50个竖直的刻度线如何通过opencv用c++语言将这些直线检测出来并求出相邻两个直线之间像素距离的平均值
以下是通过OpenCV和C++语言实现检测刻度尺上的直线并计算相邻两个直线之间像素距离平均值的代码示例:
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取图像
Mat img = imread("ruler.jpg", IMREAD_GRAYSCALE);
// 二值化图像
Mat bw;
threshold(img, bw, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 查找轮廓
vector<vector<Point>> contours;
findContours(bw, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 画出轮廓
Mat drawing = Mat::zeros(bw.size(), CV_8UC3);
for (size_t i = 0; i < contours.size(); i++)
{
drawContours(drawing, contours, (int)i, Scalar(0, 0, 255), 2);
}
// 计算相邻两个直线之间像素距离的平均值
vector<float> distances;
for (size_t i = 0; i < contours.size(); i++)
{
for (size_t j = i + 1; j < contours.size(); j++)
{
float dist = norm(contours[i][0] - contours[j][0]);
distances.push_back(dist);
}
}
float avg_dist = accumulate(distances.begin(), distances.end(), 0.0) / distances.size();
// 显示结果
imshow("Original Image", img);
imshow("Binary Image", bw);
imshow("Contours", drawing);
cout << "Average Distance: " << avg_dist << endl;
waitKey(0);
return 0;
}
在这个代码中,我们首先读取图像并将其转换为灰度图像。然后,我们使用Otsu二值化算法将图像二值化。接下来,我们使用findContours函数查找轮廓,并使用drawContours函数将轮廓画出来。最后,我们计算相邻两个直线之间像素距离的平均值,并将结果显示在控制台中。
原文地址: https://www.cveoy.top/t/topic/bSpP 著作权归作者所有。请勿转载和采集!