程式功能:提取單通道圖像輪廓
#include <opencv.hpp>
#include <iostream>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
Mat SrcImage = imread("1.png");
Mat grayImage, dstImage;
//namedWindow("原圖", 2);
imshow("原圖", SrcImage);
cvtColor(SrcImage, grayImage, COLOR_RGB2GRAY);//灰階圖
threshold(grayImage, dstImage, 100, 255, THRESH_BINARY);//二值化圖
uchar *data = dstImage.data;
int height = dstImage.rows;
int width = dstImage.cols*dstImage.channels();
cout << height << " " << width << endl;
vector<vector<int>> state(height, vector<int>(width, 0)); //動态二維數組,存儲狀态
for (int i = 0; i < height; i++)
{
uchar *p = dstImage.ptr<uchar>(i); //行指針
for (int j = 0; j < width; j++)
{
if (data[i*dstImage.step + j] == 0)
{
for (int m = i - 1; m <= i + 1; m++)
{
for (int n = j - 1; n <= j + 1; n++)
{
if (data[m*dstImage.step + n] == 255)
{
state[i][j] = 1;
}
}
}
}
}
}
for (int i = 0; i < height; i++)
{
uchar *p = dstImage.ptr<uchar>(i);
for (int j = 0; j < width; j++)
{
if (state[i][j] == 1)
{
p[j] = 255;
}
else
{
p[j] = 0;
}
}
}
//namedWindow("輪廓圖", 2);
imshow("輪廓圖", dstImage);
waitKey(0);
return 0;
}
程式結果: