基于边缘颜色变化的边缘提取:
原理是该位置的像素值与周边像素值的R G B存在较大差别,即判定其为边缘像素
#include<opencv2\opencv.hpp>
#include<vector>
#include<iostream>
using namespace std;
using namespace cv;
int main()
{
IplImage *image = cvLoadImage("D:\\8.jpg");
if (image == NULL)
{
cout << "打开图像失败!";
return -1;
}
struct Label
{
int row;
int column;
};
vector<Label> Boundary;
Label temp;
CvScalar scalar;
double thres = 100;
for (int i = 2; i <= image->height-2; i++)
{
for (int j = 2; j < image->width-2; j++)
{
int R1 = cvGet2D(image, i-1, j-1).val[2]; int G1 = cvGet2D(image, i-1, j-1).val[0]; int B1 = cvGet2D(image, i-1, j-1).val[1];
int R2 = cvGet2D(image, i-1, j).val[2]; int G2 = cvGet2D(image, i-1, j).val[0]; int B2 = cvGet2D(image, i-1, j).val[1];
int R3 = cvGet2D(image, i-1, j+1).val[2]; int G3 = cvGet2D(image, i-1, j+1).val[0]; int B3 = cvGet2D(image, i-1, j+1).val[1];
int R4 = cvGet2D(image, i, j-1).val[2]; int G4 = cvGet2D(image, i, j-1).val[0]; int B4 = cvGet2D(image, i, j-1).val[1];
int R5 = cvGet2D(image, i, j).val[2]; int G5 = cvGet2D(image, i, j).val[0]; int B5 = cvGet2D(image, i, j).val[1];
int R6 = cvGet2D(image, i, j+1).val[2]; int G6 = cvGet2D(image, i, j+1).val[0]; int B6 = cvGet2D(image, i, j+1).val[1];
int R7 = cvGet2D(image, i+1, j-1).val[2]; int G7 = cvGet2D(image, i+1, j-1).val[0]; int B7 = cvGet2D(image, i+1, j-1).val[1];
int R8 = cvGet2D(image, i+1, j).val[2]; int G8 = cvGet2D(image, i+1, j).val[0]; int B8 = cvGet2D(image, i+1, j).val[1];
int R9 = cvGet2D(image, i+1, j+1).val[2]; int G9 = cvGet2D(image, i+1, j+1).val[0]; int B9 = cvGet2D(image, i+1, j+1).val[1];
bool judge01 = (abs(R5 - R1) >= thres || abs(G5 - G1) >= thres || abs(B5 - B1) >= thres);
bool judge02 = (abs(R5 - R2) >= thres || abs(G5 - G2) >= thres || abs(B5 - B2) >= thres);
bool judge03 = (abs(R5 - R3) >= thres || abs(G5 - G3) >= thres || abs(B5 - B3) >= thres);
bool judge04 = (abs(R5 - R4) >= thres || abs(G5 - G4) >= thres || abs(B5 - B4) >= thres);
bool judge05 = (abs(R5 - R6) >= thres || abs(G5 - G6) >= thres || abs(B5 - B6) >= thres);
bool judge06 = (abs(R5 - R7) >= thres || abs(G5 - G7) >= thres || abs(B5 - B7) >= thres);
bool judge07 = (abs(R5 - R8) >= thres || abs(G5 - G8) >= thres || abs(B5 - B8) >= thres);
bool judge08 = (abs(R5 - R9) >= thres || abs(G5 - G9) >= thres || abs(B5 - B9) >= thres);
//只要其中有个不对,则直接为边界点
bool last = (judge01 == 1 || judge02 == 1 || judge03 == 1 || judge04 == 1 || judge05 == 1 || judge06 == 1 || judge07 == 1 || judge08 == 1);
if (last )
{
temp.row = i;
temp.column = j;
Boundary.push_back(temp);
}
}
}
cv::Mat Img(image, 0);//格式转换
for (int i = 0; i < Boundary.size(); i++)
{
int row = Boundary[i].row;
int column = Boundary[i].column;
//设置成绿色
Img.ptr<uchar>(row)[column * 3] = 0;
Img.ptr<uchar>(row)[column * 3 + 1] = 255;
Img.ptr<uchar>(row)[column * 3 + 2] = 0;
}
imshow("test", Img);
waitKey(0);
return 0;
}