给出zhang-suen细化结合灰度重心法提取激光条纹的vs c++代码
时间: 2023-12-06 10:03:12 浏览: 185
zhang-suen-thinning:Zhang-Suen 细化算法的 OpenCVC++ 实现以及相关的预处理和后处理步骤
以下是基于 Zhang-Suen 细化算法和灰度重心法提取激光条纹的 C++ 代码:
```c++
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
// Zhang-Suen 细化算法
Mat ZhangSuenThinning(Mat img) {
Mat thin(img.size(), CV_8UC1);
img.copyTo(thin);
thin /= 255;
Mat prev = Mat::zeros(thin.size(), CV_8UC1);
Mat diff;
do {
thin.copyTo(prev);
for (int i = 1; i < thin.rows - 1; ++i) {
for (int j = 1; j < thin.cols - 1; ++j) {
if (thin.at<uchar>(i,j) == 1) {
int p2 = thin.at<uchar>(i-1, j);
int p3 = thin.at<uchar>(i-1, j+1);
int p4 = thin.at<uchar>(i, j+1);
int p5 = thin.at<uchar>(i+1, j+1);
int p6 = thin.at<uchar>(i+1, j);
int p7 = thin.at<uchar>(i+1, j-1);
int p8 = thin.at<uchar>(i, j-1);
int p9 = thin.at<uchar>(i-1, j-1);
int A = 0;
if (p2 == 0 && p3 == 1) ++A;
if (p3 == 0 && p4 == 1) ++A;
if (p4 == 0 && p5 == 1) ++A;
if (p5 == 0 && p6 == 1) ++A;
if (p6 == 0 && p7 == 1) ++A;
if (p7 == 0 && p8 == 1) ++A;
if (p8 == 0 && p9 == 1) ++A;
if (p9 == 0 && p2 == 1) ++A;
int B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
int m1 = (p2 * p4 * p6);
int m2 = (p4 * p6 * p8);
if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) {
thin.at<uchar>(i,j) = 0;
}
}
}
}
for (int i = 1; i < thin.rows - 1; ++i) {
for (int j = 1; j < thin.cols - 1; ++j) {
if (thin.at<uchar>(i,j) == 1) {
int p2 = thin.at<uchar>(i-1, j);
int p3 = thin.at<uchar>(i-1, j+1);
int p4 = thin.at<uchar>(i, j+1);
int p5 = thin.at<uchar>(i+1, j+1);
int p6 = thin.at<uchar>(i+1, j);
int p7 = thin.at<uchar>(i+1, j-1);
int p8 = thin.at<uchar>(i, j-1);
int p9 = thin.at<uchar>(i-1, j-1);
int A = 0;
if (p2 == 0 && p3 == 1) ++A;
if (p3 == 0 && p4 == 1) ++A;
if (p4 == 0 && p5 == 1) ++A;
if (p5 == 0 && p6 == 1) ++A;
if (p6 == 0 && p7 == 1) ++A;
if (p7 == 0 && p8 == 1) ++A;
if (p8 == 0 && p9 == 1) ++A;
if (p9 == 0 && p2 == 1) ++A;
int B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
int m1 = (p2 * p4 * p8);
int m2 = (p2 * p6 * p8);
if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) {
thin.at<uchar>(i,j) = 0;
}
}
}
}
absdiff(thin, prev, diff);
} while (countNonZero(diff) > 0);
thin *= 255;
return thin;
}
// 灰度重心法提取激光条纹
Point2f extractLaserStripe(Mat img) {
// 将图像转换为灰度图像
Mat gray;
cvtColor(img, gray, COLOR_BGR2GRAY);
// 对灰度图像进行二值化处理
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
// 对二值化图像进行细化处理
Mat thin = ZhangSuenThinning(binary);
// 计算灰度重心
Moments m = moments(thin, true);
Point2f centroid(m.m10/m.m00, m.m01/m.m00);
return centroid;
}
int main() {
// 读取图像
Mat img = imread("laser_stripe.png");
// 提取激光条纹
Point2f centroid = extractLaserStripe(img);
// 在图像上标记出灰度重心
circle(img, centroid, 5, Scalar(0,0,255), -1);
// 显示图像
imshow("Laser Stripe Extraction", img);
waitKey(0);
return 0;
}
```
这段代码实现了对输入图像进行 Zhang-Suen 细化算法和灰度重心法提取激光条纹的功能,并在图像上标记出灰度重心。
阅读全文