C++实现图像的领域与中值滤波

opencv学习笔记

领域平均法滤波:邻域平法就是通过对图像进行卷积操作,把像素点大值拉低,把像素点小值拉高,由于噪声像素值一般较大,所以起到滤波的作用。由于是对像素进行均值处理,使图像变得模糊,所以也会丢失重要的信息。

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

/*选择卷积[1, 1, 1]
*         [1, 1, 1]
*         [1, 1, 1]*/
double conv_3x3(Mat& image)
{
	int h = image.rows;
	int w = image.cols;
	Mat dst = image.clone();
	for (int row = 0; row < h; row++) //遍历图像像素的每行
	{
		for (int col = 0; col < w; col++) //遍历图像像素的每列
		{
			uchar p1 = image.at(row, col); //找出3x3卷积核对应的9个像素点
			uchar p2 = image.at(row, col + 1);
			uchar p3 = image.at(row, col + 2);
			uchar p4 = image.at(row + 1, col);
			uchar p5 = image.at(row + 1, col + 1);
			uchar p6 = image.at(row + 1, col + 2);
			uchar p7 = image.at(row + 2, col);
			uchar p8 = image.at(row + 2, col + 1);
			uchar p9 = image.at(row + 2, col + 2);

			//pixel_sum为一次卷积之和,再用pixel_sum / 9 替代原像素点
			int pixel_sum = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9; 
			dst.at(row, col) = saturate_cast(pixel_sum / 9);
		}
	}
	imshow("邻域平均滤波", dst);
}
int main()
{
	Mat src = imread("D:/Destop/233_noise.jpg", 0);
	if (src.empty())
	{
		cout << "图片读取失败" << endl;
		return -1;
	}
	imshow("原始图像", src);
	conv_3x3(src);
	waitKey(0);
	destroyAllWindows();

	return 0;
}

中值滤波:中值滤波就是取当前像素点及其周围临近像素点的像素值,将这些像素值从小达到排序,然后取中间位置的像素值作为当前像素点的像素值,效果会好于邻域平均法滤波。

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

/*选择卷积[1, 1, 1]
*         [1, 1, 1]
*         [1, 1, 1]*/
double conv_3x3(Mat& image)
{
	int h = image.rows;
	int w = image.cols;
	Mat dst = image.clone();
	for (int row = 0; row < h; row++) //遍历图像像素的每行
	{
		for (int col = 0; col < w; col++) //遍历图像像素的每列
		{
			uchar p1 = image.at(row, col); //找出3x3卷积核对应的9个像素点
			uchar p2 = image.at(row, col + 1);
			uchar p3 = image.at(row, col + 2);
			uchar p4 = image.at(row + 1, col);
			uchar p5 = image.at(row + 1, col + 1);
			uchar p6 = image.at(row + 1, col + 2);
			uchar p7 = image.at(row + 2, col);
			uchar p8 = image.at(row + 2, col + 1);
			uchar p9 = image.at(row + 2, col + 2);

			//使用冒泡排序法找出中间像素值pixels[4],并用它替代原像素值
			int pixels[9] = { p1, p2, p3, p4, p5, p6, p7, p8, p9 };	
			for (int j = 0; j < 9; j++)
			{
				for (int i = 0; i < 9 - 1 - j; i++)
				{
					if (pixels[i] > pixels[i + 1])
					{
						int tmp = pixels[i];
						pixels[i] = pixels[i + 1];
						pixels[i + 1] = tmp;
					}
				}
			}
			dst.at(row, col) = saturate_cast(pixels[4]);
		}
	}
	imshow("中值滤波", dst);
}
int main()
{
	Mat src = imread("D:/Destop/233_noise.jpg", 0);
	if (src.empty())
	{
		cout << "图片读取失败" << endl;
		return -1;
	}
	imshow("原始图像", src);
	conv_3x3(src);
	waitKey(0);
	destroyAllWindows();

	return 0;
}

 

 

你可能感兴趣的:(c++,计算机视觉,opencv)