图像平滑
均值平滑函数
代码实现
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;