求一个可以用OpenCV求线段距离的代码!可以有偿,用C++, 最好也可以用javaCV
我本来打算用霍夫变化求线段长度,奈何时间不够了下午就要出结果
这种白底黑线的简单的图片可以识别就可以,可以识别出线段长度,以及线段的端点坐标
简单写一个,里面内凹的角起始点差一个像素,我懒得处理,你自己要是觉得不行自己处理下
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
struct Line {
Point A, B;
double distance;
};
double getDistance(Point A,Point B) {
return sqrt((A.x - B.x)* (A.x - B.x) + (A.y - B.y)*(A.y - B.y));
}
int main()
{
string path = "./3/1.jpg";
Mat img = imread(path);
Mat gray,binary;
cvtColor(img, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 180,255, THRESH_BINARY_INV);
vector<vector<Point>> contours;
findContours(binary, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
vector<Line> Lines; //存放找到结果Lines
for (int i = 0; i < contours.size(); ++i) {
for (int j = 0; j < contours[i].size(); ++j) {
int k = (j +1)%contours[i].size();
Point A = contours[i][j];
Point B = contours[i][k];
double distance = getDistance(A, B);
if (distance > 2) {
Line temp_line;
temp_line.A = A;
temp_line.B = B;
temp_line.distance = distance;
Lines.push_back(temp_line);
}
}
}
//绘制每条线:
Mat drawImg = img.clone();
for (int i = 0; i < Lines.size(); ++i) {
Scalar color(rand() % 255, rand() % 255, rand() % 255 );
line(drawImg, Lines[i].A, Lines[i].B, color, 1, 8);
}
imshow("src", img);
imshow("res", drawImg);
waitKey();
return 0;
}
如果是这种的闭合图像,不复杂,3步: 1.用threshold将图形二值化,flag用THRESH_BINARY_INV同时反色,只留下白色边框。2.findContours()查找出图像的边框,只找外框就行。3.arcLength()计算出边框的周长。