请用C代码或C++代码,实现两种骨架提取算法:顺序细化和北、南、东、西提取算法。
时间: 2023-12-03 11:46:44 浏览: 76
顺序细化算法的C++实现:
```c++
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
void seqThinning(Mat &img) {
Mat prev = Mat::zeros(img.size(), CV_8UC1);
Mat diff;
do {
thinning(img, 0);
thinning(img, 1);
absdiff(img, prev, diff);
img.copyTo(prev);
} while (countNonZero(diff) > 0);
}
void thinning(Mat &img, int type) {
Mat marker = Mat::zeros(img.size(), CV_8UC1);
for (int i = 1; i < img.rows - 1; i++) {
for (int j = 1; j < img.cols - 1; j++) {
uchar p2 = img.at<uchar>(i - 1, j);
uchar p3 = img.at<uchar>(i - 1, j + 1);
uchar p4 = img.at<uchar>(i, j + 1);
uchar p5 = img.at<uchar>(i + 1, j + 1);
uchar p6 = img.at<uchar>(i + 1, j);
uchar p7 = img.at<uchar>(i + 1, j - 1);
uchar p8 = img.at<uchar>(i, j - 1);
uchar p9 = img.at<uchar>(i - 1, j - 1);
int A = (!p2 && p3) + (!p3 && p4) + (!p4 && p5) + (!p5 && p6) +
(!p6 && p7) + (!p7 && p8) + (!p8 && p9) + (!p9 && p2);
int B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
int m1 = (type == 0) ? (p2 * p4 * p6) : (p2 * p4 * p8);
int m2 = (type == 0) ? (p4 * p6 * p8) : (p2 * p6 * p8);
if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) {
marker.at<uchar>(i, j) = 1;
}
}
}
img &= ~marker;
}
int main() {
Mat src = imread("test.png", 0);
threshold(src, src, 128, 255, THRESH_BINARY);
seqThinning(src);
imshow("result", src);
waitKey(0);
return 0;
}
```
北、南、东、西提取算法的C++实现:
```c++
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
void nsweThinning(Mat &img) {
Mat prev = Mat::zeros(img.size(), CV_8UC1);
Mat diff;
do {
thinning(img, 0);
thinning(img, 1);
absdiff(img, prev, diff);
img.copyTo(prev);
} while (countNonZero(diff) > 0);
}
void thinning(Mat &img, int type) {
Mat marker = Mat::zeros(img.size(), CV_8UC1);
for (int i = 1; i < img.rows - 1; i++) {
for (int j = 1; j < img.cols - 1; j++) {
uchar p2 = img.at<uchar>(i - 1, j);
uchar p3 = img.at<uchar>(i - 1, j + 1);
uchar p4 = img.at<uchar>(i, j + 1);
uchar p5 = img.at<uchar>(i + 1, j + 1);
uchar p6 = img.at<uchar>(i + 1, j);
uchar p7 = img.at<uchar>(i + 1, j - 1);
uchar p8 = img.at<uchar>(i, j - 1);
uchar p9 = img.at<uchar>(i - 1, j - 1);
int A = (!p2 && p3) + (!p3 && p4) + (!p4 && p5) + (!p5 && p6) +
(!p6 && p7) + (!p7 && p8) + (!p8 && p9) + (!p9 && p2);
int B = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9;
int m1 = (type == 0) ? (p2 * p4 * p8) : (p2 * p6 * p8);
int m2 = (type == 0) ? (p2 * p4 * p6) : (p4 * p6 * p8);
if (A == 1 && (B >= 2 && B <= 6) && m1 == 0 && m2 == 0) {
marker.at<uchar>(i, j) = 1;
}
}
}
img &= ~marker;
}
int main() {
Mat src = imread("test.png", 0);
threshold(src, src, 128, 255, THRESH_BINARY);
nsweThinning(src);
imshow("result", src);
waitKey(0);
return 0;
}
```
阅读全文