OPENCV灰度图像的共生矩阵C+代码

OPENCV灰度图像的共生矩阵C+代码

原理

OPENCV灰度图像的共生矩阵C+代码_第1张图片
OPENCV灰度图像的共生矩阵C+代码_第2张图片

因为图像是离散的灰度像素,所以很容易找到各个角度的像素位置。 例如要找135度方向,距离为1的共生矩阵。设点坐标为(i,j)则此方向的坐标为(i+1,j-1)。不同方向改变i,j。

例题
OPENCV灰度图像的共生矩阵C+代码_第3张图片

#include
#include 
#include
using namespace cv;
using namespace std;

void P0img_maritx(Mat& src_img, Mat& dst2_img, const int maxvaule);//距离1角度0的共生矩阵
void P135img_maritx(Mat& src_img, Mat& dst2_img, const int maxvaule); //距离1角度135的共生矩阵

void P0img_maritx(Mat& src_img, Mat& dst2_img, const int maxvaule)
{
	Mat_<uchar> im = src_img;
	Mat dst_img = cv::Mat::zeros(maxvaule + 1, maxvaule + 1, CV_8UC1);
	Mat m1 = dst_img;
	Mat m2 = dst_img;
	for (int m = 0; m < maxvaule+1 ; m++)
	{
		for (int n = 0; n < maxvaule + 1; n++)
		{
			for (int i = 0; i < src_img.rows; i++)
			{
				for (int j = 0; j < src_img.cols - 1; j++)
				{
					if (m == im(i, j) && n == im(i, j + 1))
					{
						m1.ptr<uchar>(m)[n] += 1;
					}

				}
			}
			for (int i = 0; i < src_img.rows; i++)
			{
				for (int j = 1; j < src_img.cols; j++)
				{
					if (m == im(i, j) && n == im(i, j - 1))
					{
						m2.ptr<uchar>(m)[n] += 1;
					}

				}

			}
		}
	}
	dst2_img = (m1+m2)/2;
}


void P135img_maritx(Mat& src_img, Mat& dst2_img, const int maxvaule)
{
	Mat_<uchar> im = src_img;
	Mat dst_img = cv::Mat::zeros(maxvaule + 1, maxvaule + 1, CV_8UC1);
	Mat m1 = dst_img;
	Mat m2 = dst_img;
	for (int m = 0; m < maxvaule + 1; m++)
	{
		for (int n = 0; n < maxvaule + 1; n++)
		{
			for (int i = 0; i < src_img.rows-1; i++)
			{
				for (int j = 1; j < src_img.cols ; j++)
				{
					if (m == im(i, j) && n == im(i+1, j -1))
					{
						m1.ptr<uchar>(m)[n] += 1;
					}

				}
			}
			for (int i = 1; i < src_img.rows; i++)
			{
				for (int j = 0; j < src_img.cols-1; j++)
				{
					if (m == im(i, j) && n == im(i-1, j +1))
					{
						m2.ptr<uchar>(m)[n] += 1;
					}

				}

			}
		}
	}
	dst2_img = (m1 + m2) / 2;
}
int main()
{

	//int a[6][6] = { 0, 1, 2, 3, 0, 1, 1, 2, 3, 0, 1, 2, 2, 3, 0, 1, 2, 3, 3, 0, 1, 2, 3, 0, 0, 1, 2, 3, 0, 1, 1, 2, 3, 0, 1, 2 };
	int a[4][4] = { 0,0,1,1,0,0,1,1,0,2,2,2,2,2,3,3 };
	Mat src_img(4, 4, CV_32S, a);
	Mat dst0_img, dst135_img;
	cout << "原图片矩阵" << endl;
	cout << src_img<<endl;
	P0img_maritx(src_img, dst0_img, 3);
	cout << "0度距离1共生矩阵" << endl;
	cout << dst0_img<<endl;
	P135img_maritx(src_img, dst135_img, 3);
	cout << "135度距离1共生矩阵" << endl;
	cout << dst135_img << endl;
	return 0;
}

OPENCV灰度图像的共生矩阵C+代码_第4张图片
此代码有些繁琐,编程时没考虑太多,但是理解直观。网络上有更多简洁代码可以使用

你可能感兴趣的:(OPenCV,opencv,计算机视觉,人工智能,图像识别,机器学习)