图像平滑opencv c++ matlab实现

图像平滑

均值平滑函数

代码实现

c++

灰度图均值平滑

Mat smoothImage(const Mat& inputImage, int Sx, int Sy)
{
	Mat smoothed;
	inputImage.copyTo(smoothed);

	int channels = smoothed.channels();
	int width = smoothed.cols;
	int height = smoothed.rows;

	// 遍历图像像素
	for (int i = Sy; i < height - Sy; i++)
	{
		for (int j = Sx; j < width - Sx; j++)
		{
			// 计算窗口内像素的平均灰度
			double sum = 0;
			for (int m = -Sy; m <= Sy; m++)
			{
				for (int n = -Sx; n <= Sx; n++)
				{
					if (channels == 1)
						sum += smoothed.at<uchar>(i + m, j + n);
					else if (channels == 3)
						sum += smoothed.at<Vec3b>(i + m, j + n)[0]; // 取B通道进行平滑,可根据需要调整通道

				}
			}

			// 将平均灰度赋给中心像素
			if (channels == 1)
				smoothed.at<uchar>(i, j) = static_cast<uchar>(sum / ((2 * Sx + 1) * (2 * Sy + 1)));
			else if (channels == 3)
			{
				Vec3b& pixel = smoothed.at<Vec3b>(i, j);
				pixel[0] = static_cast<uchar>(sum / ((2 * Sx + 1) * (2 * Sy + 1))); // 更新B通道的值
				pixel[1] = pixel[2] = pixel[0]; // 将G和R通道设为与B通道相同的值
			}
		}
	}

	return smoothed;
}
matlab
function smoothed_image = smooth_rgb(image, Sx, Sy)
% 彩色图像均值平滑
[rows, cols, channels] = size(image);

% 创建一个空矩阵,用于存储平滑后的图像
smoothed_image = zeros(rows, cols, channels);

% 遍历图像中的每个像素
for y = 1:rows
    for x = 1:cols
        % 计算窗口的边界
        x_min = max(1, x - Sx);
        x_max = min(cols, x + Sx);
        y_min = max(1, y - Sy);
        y_max = min(rows, y + Sy);
        
        % 获取窗口内的像素值
        window = image(y_min:y_max, x_min:x_max, :);
        
        % 计算平均值
        avg = mean(window, [1 2]);
        
        % 将平均值存储在平滑后的图像中
        smoothed_image(y, x, :) = avg;
    end
end

实验结果

c++(灰度图)

输入参数

int Sx = 3; // 窗口大小参数Sx
	int Sy = 3; // 窗口大小参数Sy
	cv::Mat smoothedImage = smoothImage(img, Sx, Sy);
	cv::imshow("均值滤波", smoothedImage);

在这里插入图片描述

matlab

输入参数

%实现平滑函数
Sx=10;
Sy=10;
smoothed_image =smooth_rgb(scrimage,Sx,Sy);
subplot(334);imshow(uint8(smoothed_image));title('平滑函数');
axis on;

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值