请用C代码或C++代码,实现zi.jpg的两种骨架提取算法:顺序细化和北、南、东、西提取算法。
时间: 2023-12-18 09:04:25 浏览: 67
由于图像处理需要用到许多库函数和数据结构,C++的STL库和OpenCV库是非常方便的选择。以下是使用OpenCV库实现zi.jpg的两种骨架提取算法的代码:
顺序细化算法:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读入图像
Mat src = imread("zi.jpg", IMREAD_GRAYSCALE);
// 二值化图像
Mat bin;
threshold(src, bin, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 初始化细化标志
Mat skel(bin.size(), CV_8UC1, Scalar(0));
Mat temp(bin.size(), CV_8UC1);
// 定义结构元素
Mat element = getStructuringElement(MORPH_CROSS, Size(3, 3));
// 迭代细化
do {
morphologyEx(bin, temp, MORPH_OPEN, element);
bitwise_not(temp, temp);
bitwise_and(bin, temp, temp);
bitwise_or(skel, temp, skel);
erode(bin, bin, element);
} while (countNonZero(bin) != 0);
// 显示结果
imshow("Skeleton", skel);
waitKey(0);
return 0;
}
```
北、南、东、西提取算法:
```c++
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读入图像
Mat src = imread("zi.jpg", IMREAD_GRAYSCALE);
// 二值化图像
Mat bin;
threshold(src, bin, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
// 初始化细化标志
Mat skel(bin.size(), CV_8UC1, Scalar(0));
Mat temp(bin.size(), CV_8UC1);
// 定义结构元素
Mat element = getStructuringElement(MORPH_CROSS, Size(3, 3));
// 迭代细化
do {
morphologyEx(bin, temp, MORPH_OPEN, element);
bitwise_not(temp, temp);
bitwise_and(bin, temp, temp);
bitwise_or(skel, temp, skel);
erode(bin, bin, element);
} while (countNonZero(bin) != 0);
// 北、南、东、西提取
for (int i = 1; i < skel.rows - 1; i++) {
for (int j = 1; j < skel.cols - 1; j++) {
if (skel.at<uchar>(i, j) == 255) {
int n = skel.at<uchar>(i - 1, j);
int s = skel.at<uchar>(i + 1, j);
int e = skel.at<uchar>(i, j + 1);
int w = skel.at<uchar>(i, j - 1);
int sum = n + s + e + w;
if (sum == 255) {
skel.at<uchar>(i, j) = 0;
}
}
}
}
// 显示结果
imshow("Skeleton", skel);
waitKey(0);
return 0;
}
```
阅读全文