中值滤波和均值滤波代码
%均值滤波
clc,clear;
f=imread('2.bmp');
subplot(221),imshow(f);
f1=imnoise(f,'gaussian',0.002,0.0008);
subplot(222),imshow(f1);
k1=floor(3/2)+1;
k2=floor(3/2)+1;
X=f1;
[M,N]=size(X);
uint8 Y=zeros(M,N);
funBox=zeros(3,3);
for i=1:M-3
for j=1:N-3
funBox=X(i:i+3,j:j+3);
s=sum(funBox(:));
h=s/9;
Y(i+k1,j+k2)=h;
end;
end;
Y=Y/255;
subplot(223),imshow(Y);
注意:在matlab中,我们常使用imshow()函数来显示图像,而此时的图像矩阵可能经过了某种运算。
在matlab中,为了保证精度,经过了运算的图像矩阵I其数据类型会从unit8型变成double型。
如果直接运行imshow(I),我们会发现显示的是一个白色的图像。
这是因为imshow()显示图像时对double型是认为在0~1范围内,即大于1时都是显示为白色,而imshow显示uint8型时是0~255范围。
而经过运算的范围在0-255之间的double型数据就被不正常得显示为白色图像了。
那么如何解决这个问题呢?笔者曾经用fix()函数把图像矩阵由实数形式转化成整数形式,但这样仍无法改变图像矩阵是double型的事实。
通过搜索,找到两个解决方法:
imshow(I/256); ----------将图像矩阵转化到0-1之间
imshow(I,[]); -----------自动调整数据的范围以便于显示(不明白原理!)
PS:imshow(I,[]),将I的最小值看作0,最大值看作255,所以黑白明显
从实验结果看两种方法都解决了问题,但是从显示的图像看,第二种方法显示的图像明暗黑白对比的强烈些!不知什么原理!
此外还找到一些方法,还没有试过,记录如下:
uint8和im2uint8的区别
图像数据在计算前需要转换为double,以保证精度; 很多矩阵数据也都是double的,要想显示其,必须先转换为图像的标准数据格式. 如果转换前的数据符合图像数据标准(比如如果是double则要位于0~1之间),那么可以直接使用im2uint8
如果转换前的数据分布不合规律,则使用uint8,将其自动切割至0~255(超过255的按255)
最好使用mat2gray,将一个矩阵转化为灰度图像的数据格式(double)
另外,可以用isgray判断矩阵是否是一个图像数据矩阵
总之,im2uint8、im2double要跟uint8、double
%均值滤波
k=floor(3*3/2)+1;
[M,N]=size(X);
uint8 Z=zeros(M,N);
funBox=zeros(3,3);
temp=zeros(3*3);
for i=1:M-3
for j=1:N-3
funBox=X(i:i+3,j:j+3);
temp=funBox(:);
tempSort=sort(temp);
Z(i,j)=tempSort(k);
end;
end;
subplot(224),imshow(Z);。
一些软件滤波算法的原理和程序源代码
一些软件滤波算法的原理和程序源代码滤波算法是信号处理中常用的技术,用于去除信号中的噪声或抽取感兴趣的信号特征。
在本文中,我将介绍几种常见的软件滤波算法的原理和程序源代码,包括均值滤波、中值滤波和高斯滤波。
1.均值滤波均值滤波是一种简单直观的滤波算法。
其原理是通过计算像素周围邻近像素的平均值,来替换掉原始图像像素的值。
均值滤波的算法步骤如下:-创建一个大小为n的窗口(n通常为奇数),以当前像素为中心。
-计算窗口中所有像素的平均值。
-将当前像素的值替换为计算得到的平均值。
-按顺序处理所有像素。
以下是均值滤波的C++程序源代码示例:```cppvoid meanFilter(const cv::Mat& src, cv::Mat& dst, int kernelSize)int kernelHalfSize = kernelSize / 2;dst.create(src.size(, src.type();for (int y = 0; y < src.rows; y++)for (int x = 0; x < src.cols; x++)cv::Vec3f sum = cv::Vec3f(0, 0, 0);int numPixels = 0;for (int ky = -kernelHalfSize; ky <= kernelHalfSize; ky++) for (int kx = -kernelHalfSize; kx <= kernelHalfSize; kx++) int px = x + kx;int py = y + ky;if (px >= 0 && py >= 0 && px < src.cols && py < src.rows) sum += src.at<cv::Vec3b>(py, px);numPixels++;}}}cv::Vec3f average = sum / numPixels;dst.at<cv::Vec3b>(y, x) = average;}}```2.中值滤波中值滤波是一种非线性滤波算法,主要用于去除图片中的椒盐噪声。
10种简单的数字滤波算法(C++源程序)
10种简单的数字滤波算法(C++源程序)以下是10种简单的数字滤波算法C++实现示例:1. 均值滤波均值滤波是数字滤波算法的一种常见形式,它可以通过计算一定范围内像素值的平均值来平滑图像。
其C++实现如下:#include <iostream>#include <opencv2/opencv.hpp>using namespace std;using namespace cv;// Function to implement mean filtervoid meanBlur(Mat& img, Mat& result, int k_size){int img_rows = img.rows;int img_cols = img.cols;// Create a same sized blank imageresult.create(img_rows, img_cols, img.type());for(int r=0; r<img_rows; r++){for(int c=0; c<img_cols; c++){// Define the window of radius k_sizeint r_min = max(0, r-k_size/2);int r_max = min(img_rows-1, r+k_size/2);int c_min = max(0, c-k_size/2);int c_max = min(img_cols-1, c+k_size/2);// Calculate the mean valueint sum = 0;int count = 0;for (int i=r_min; i<=r_max; i++){for (int j=c_min; j<=c_max; j++){sum += img.at<uchar>(i,j);count++;}}result.at<uchar>(r,c) = (uchar) (sum/count);}}}int main(int argc, char** argv){// Load the imageMat img = imread("image.jpg", 0);// Check if image is loaded properlyif(!img.data){cout << "Failed to load image" << endl;return -1;}// Define the kernel sizeint k_size = 3;// Apply mean filterMat result;meanBlur(img, result, k_size);// Display the resultnamedWindow("Original Image", WINDOW_NORMAL);namedWindow("Mean Filtered Image", WINDOW_NORMAL);imshow("Original Image", img);imshow("Mean Filtered Image", result);waitKey(0);return 0;}在上述代码中,`meanBlur()` 函数接收一个输入图像`img` 和一个输出图像`result`,以及一个整数参数`k_size`,该参数指定滤波器的大小,即窗口的半径。
matlab光滑函数代码
MATLAB光滑函数代码一、引言在MATLAB中,光滑函数是一类常用的数学工具,它们提供了处理并光滑噪声信号的功能。
这些函数可以有效地对信号进行平滑处理,以便更好地识别信号的趋势和结构。
本文将介绍MATLAB中常用的光滑函数代码,并提供详细的示例和应用场景。
二、常用的光滑函数2.1 平均值滤波平均值滤波是一种简单的光滑函数,它通过计算信号中一定长度窗口内的均值来光滑信号。
MATLAB提供了函数smoothdata来实现平均值滤波。
下面是一个使用平均值滤波的示例代码:data = [1, 1, 2, 4, 3, 6, 5, 8, 10, 9];smoothed_data = smoothdata(data,'movmean',3);2.2 中值滤波中值滤波是一种常用的非线性滤波方法,它通过对信号中一定长度窗口内的数据进行排序,然后取中间值作为光滑后的数值。
MATLAB中的medfilt1函数可以实现中值滤波。
以下是一个中值滤波的示例代码:data = [1, 1, 2, 4, 3, 6, 5, 8, 10, 9];smoothed_data = medfilt1(data,3);2.3 Savitzky-Golay滤波Savitzky-Golay滤波是一种基于多项式拟合的光滑函数方法。
它通过在信号上进行多项式拟合来提取信号的趋势,并利用拟合结果对信号进行光滑处理。
MATLAB中的sgolayfilt函数可以实现Savitzky-Golay滤波。
以下是一个使用Savitzky-Golay滤波的示例代码:data = [1, 1, 2, 4, 3, 6, 5, 8, 10, 9];smoothed_data = sgolayfilt(data,3,5);三、光滑函数的应用场景光滑函数在数据处理和信号处理中有广泛的应用,以下是一些常见的应用场景:3.1 信号去噪光滑函数可以有效地去除信号中的噪声,使得信号更加清晰和易于分析。
种滤波算法程序大全(含源代码分享)
种滤波算法程序大全(含源代码分享)一、均值滤波1.1包络滤波其原理是将每个像素值替换为周围像素点的加权平均值,即取该点的邻域像素点的均值作为替换像素点的值,通过提高平均灰度和减少椒盐噪声作用。
//源代码// 函数名:meanFilte//功能:均值滤波// 输入:srcImg:源图像; meanImg:均值flied后的图像// 返回:voidvoid meanFilter(Mat srcImg, Mat meanImg)int m=srcImg.rows;int n=srcImg.cols;//掩模矩阵int mask_i, mask_j;int i, j;int sum;int mask_size=3;//maskSize=3时,卷积核为3*3的矩阵,mask_i代表卷积核中行,mask_j代表列for (mask_i = -mask_size/2;mask_i<=mask_size/2;mask_i++)for (mask_j = -mask_size/2;mask_j<=mask_size/2;mask_j++)//遍历源图像的每个像素点for (i=0;i<m;i++)for (j=0;j<n;j++)if ((mask_i+i>=0) && (mask_i+i<m) &&(mask_j+j>=0) && (mask_j+j<n))sum+=srcImg.at<uchar>(mask_i+i,mask_j+j);meanImg.at<uchar>(i,j)=sum/9;}}}1.2高斯滤波其原理是将每个像素值替换为其周围像素点与其距离的加权平均值,通过减小噪声频率,降低噪声增强图像边缘的作用。
//源代码// 函数名:gaussianFilte//功能:高斯滤波// 输入:srcImg:源图像; gausImg:高斯滤波后的图像// 返回:voidvoid gaussianFilter(Mat srcImg, Mat gausImg)int m=srcImg.rows;int n=srcImg.cols;//掩模矩阵int mask_i, mask_j;int i, j;int sum;。
最常用数字滤波方法及源代码
最常用数字滤波方法及源代码在数字信号处理中,常用的数字滤波方法有以下几种:1) 移动平均滤波(Moving Average Filter):将输入信号的过去N 个样本的平均值作为输出样本的值。
这种滤波器可以有效地平滑信号,但对于快速变化的信号可能引入较大的延迟。
2) 中值滤波(Median Filter):将输入信号的过去N个样本的中间值作为输出样本的值。
中值滤波器可以有效地去除噪声,但对于快速变化的信号可能引入较大的失真。
3) 低通滤波(Lowpass Filter):通过去除高频成分来平滑信号。
常用的低通滤波器有巴特沃斯滤波器、切比雪夫滤波器等。
以下是Python中实现这些滤波方法的简单源代码示例:移动平均滤波方法:```pythondef moving_average_filter(input_signal, window_size):filtered_signal = []for i in range(len(input_signal) - window_size + 1):window = input_signal[i:i+window_size]filtered_signal.append(sum(window) / window_size)return filtered_signal```中值滤波方法:```pythondef median_filter(input_signal, window_size):filtered_signal = []for i in range(len(input_signal) - window_size + 1):window = input_signal[i:i+window_size]filtered_signal.append(sorted(window)[window_size//2])return filtered_signal```低通滤波方法:```pythonimport scipy.signal as signaldef lowpass_filter(input_signal, cutoff_freq, fs):nyquist_freq = 0.5 * fsnormalized_cutoff_freq = cutoff_freq / nyquist_freqb, a = signal.butter(4, normalized_cutoff_freq, btype='low') filtered_signal = signal.lfilter(b, a, input_signal)return filtered_signal```注意:以上代码示例仅为简单实现,并未考虑边界情况和参数校验等细节。
图像处理——均值滤波+中值滤波(Matlab)
题目:均值滤波和中值滤波在自己的证件照中加入椒盐噪声、高斯白噪声。
分别用3*3、5*5、7*7的均值滤波器和中值滤波器进行滤波。
处理过程1.用imnoise函数在图像中分别加入椒盐噪声和高斯白噪声;2.均值滤波:用fspecial函数创建各模板大小的均值滤波器,并用imfilter函数进行滤波。
中值滤波:直接用matlab提供的medfilt2中值滤波器进行滤波即可。
处理结果程序清单(1)均值滤波rgb=imread('photo.jpg');J1=imnoise(rgb,'salt & pepper',0.02);J2=imnoise(J1,'gaussian',0,0.01);h1=fspecial('average',[3,3]);h2=fspecial('average',[5,5]);h3=fspecial('average',[7,7]);rgb1=imfilter(J2,h1);rgb2=imfilter(J2,h2);rgb3=imfilter(J2,h3);figure;subplot(2,3,1);imshow(rgb)title('原图像');subplot(2,3,2);imshow(J2)title('加入噪声后的图像');subplot(2,3,4);imshow(rgb1)title('3*3均值滤波图像');subplot(2,3,5);imshow(rgb2)title('5*5均值滤波图像');subplot(2,3,6);imshow(rgb3)title('7*7均值滤波图像');(2)中值滤波rgb=imread('photo.jpg');J1=imnoise(rgb,'salt & pepper',0.02);J2=imnoise(J1,'gaussian',0,0.01);J3=rgb2gray(J2);rgb1=medfilt2(J3,[3 3]);rgb2=medfilt2(J3,[5 5]);rgb3=medfilt2(J3,[7 7]);figure;subplot(2,3,1);imshow(rgb) title('原图像');subplot(2,3,2);imshow(J3) title('加入噪声后的图像'); subplot(2,3,4);imshow(rgb1) title('3*3中值滤波图像'); subplot(2,3,5);imshow(rgb2) title('5*5中值滤波图像'); subplot(2,3,6);imshow(rgb3) title('7*7中值滤波图像');。
中值和均值滤波---matlab...
中值和均值滤波---matlab实现(Median and mean filter ---matlabimplementation)%x is the image that needs filtering, and N is the template size (that is, n * n)Function d=avg_filter (x, n)A (1:n, 1:n) =1;%a, that is, n * n template, the element is 1[height, width]=size (x);% input image is hightxwidth, and hight>n, width>nX1=double (x);X2=x1;For i=1:hight-n+1For j=1:width-n+1C=x1 (i:i+ (n-1), j:j+ (n-1)),.*a;%, take out X1 from J (I), start n row, n column element, and template multiplyS=sum (sum (c));% the sum of the elements in the C matrixX2 (i+ (n-1), /2, j+ (n-1), /2) =s/ (n*n);% will assign the mean of the elements after the template operation to the central location of the templateEndEndNot assigned elements from% of original valueD=uint8 (x2);Self compiled median filter function. X is the image that needs filtering, and N is the template size (that is, n * n)Function d=mid_filter (x, n)[height, width]=size (x);% input images are p * q, and p>n, q>nX1=double (x);X2=x1;For i=1:height-n+1For j=1:height-n+1C=x1 (i:i+ (n-1), j:j+ (n-1));% out X1 from J (I); n row n column element, that is template (n * n)E=c (1::);% is the first row of the C matrixFor u=2:nE=[e, C (U::));% turns the C matrix into a row matrixEndMm=median (E);%mm is the medianX2 (i+ (n-1), /2, j+ (n-1) /2) =mm;%, the median of the template elements assigned to the center of the templateEndEndNot assigned elements from% of original valueD=uint8 (x2);% of the Gauss filter function, S is the need to filter the image, n is the mean, and K is the varianceFunction, d=gaussfilt (k, N, s)Img = double (s);N1=floor ((n+1) /2)% computed image centerFor i=1:nFor j=1:nB (I, J) =exp (- (i-n1) ^2+ (j-n1) ^2) / (4*k)) / (4*pi*k);EndEnd% generates Gauss sequence B.Img1=conv2 (Img, B,'same');% Gauss convolution is performed with the generated Gauss sequence convolutionD=uint8 (Img1);(5) MATLAB code of median filteringGlobal ImagenUmbral% defines a global variable, ImagenUmbralGlobal J% uses global variables JA=J% assigns J to A[m, n] = size (A);% measure image size parameterB=A;% assigns A to BPixel_block = zeros (1,9);% open up a row of nine columns of the array, were given an initial value of 0For I = 2:m-1% for each pixel in the A (excluding borders)For J = 2:n-2Pixel_block = reshape (A (i-1:i+1, j-1:j+1), 9,1);% takes the window of 3*3, and puts a pixel point and its 8 points aroundit,Store in the newly opened array pixel_blockSorted_block = sort (pixel_block);% sorted the arraypixel_blockBlock_median = sorted_block (5);%, the median value of the array is given to block_medianB (I, J) = block_median;% gives block_median the pixel value of the corresponding position of BEnd;%end, of, for, j = 2:n-2End;%end, of, for, I = 2:m-1B = uint8 (B);% converts all elements in B to integers between 0~255The subplot (224)% split drawing window is two rows and two columns, and moves the handle to fourth positionsImshow (B)% display image BImagenUmbral=B% assigns the B to the global variable ImagenUmbral(6) MATLAB implementation of mean filterA=J% assigns J to A[m, n] = size (A); the row number of%m is A, and the column number of n is AB=A;% assigns A to BPixel_block = zeros (1,9);% open up a row of nine columns of the array, were given an initial value of 0For I = 2:m-1% for each pixel in the A (excluding borders)For J = 2:n-1Pixel_block = reshape (A (i-1:i+1, j-1:j+1), 3^2,1);% uses the window of 3*3 to place a pixel and its surrounding 8 points into the newly opened array pixel_block at a timeMean_block = mean (pixel_block);%; finds the average value of all elements in an arrayB (I, J) = mean_block;% gives mean_block the pixel value of the corresponding position of BEnd;%end, of, for, j = 2:n-2End;%end, of, for, I = 2:m-1B = uint8 (B);% converts all elements in B to integers between 0~255The subplot (224)% split drawing window is two rows and twocolumns, and moves the handle to fourth positions Imshow (B)% display image BImagenUmbral=B% assigns the B to the global variable ImagenUmbral。
c语言里面平滑滤波函数
c语言里面平滑滤波函数平滑滤波在数字信号处理中起着非常重要的作用,它可以有效的去除信号中的噪声,使得信号变得更加平滑和连续。
在C语言中,我们可以利用一些算法来实现平滑滤波,比如均值滤波、中值滤波和高斯滤波等。
在本文中,我们将重点介绍这些算法的实现原理和具体的C 语言代码。
1.均值滤波均值滤波是一种最简单的平滑滤波算法,它的原理是取邻域内像素的平均值作为当前像素的值。
在C语言中,我们可以通过编写一个函数来实现均值滤波算法。
下面是一个简单的均值滤波函数的示例代码:```c#include <stdio.h>#define N 3 //邻域大小int mean_filter(int input[], int width, int height) {int output[width * height];int i, j, m, n, sum;for (i = 0; i < height; i++) {for (j = 0; j < width; j++) {sum = 0;for (m = -N/2; m <= N/2; m++) {for (n = -N/2; n <= N/2; n++) {if (i + m >= 0 && i + m < height && j + n >= 0 && j + n < width) {sum += input[(i + m) * width + (j + n)];}}}output[i * width + j] = sum / (N * N);}return output;}int main() {int input[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; //输入信号int width = 3; //信号宽度int height = 3; //信号高度int output = mean_filter(input, width, height); //平滑滤波后的信号//打印输出for (int i = 0; i < height; i++) {for (int j = 0; j < width; j++) {printf("%d ", output[i * width + j]);printf("\n");}return 0;}```上面的代码中,我们定义了一个大小为3x3的邻域,然后通过两层循环遍历所有的像素点,计算邻域内像素值的平均值,并将结果存储在output数组中。
matlab统计滤波
matlab统计滤波统计滤波是一种常用的信号处理方法,常用于滤除噪声、提取信号等方面。
它是利用一些基本的统计量来处理数据的,例如均值、标准差、中位数等等。
本文将介绍matlab中的统计滤波方法。
matlab中的统计滤波方法包括:均值滤波、中值滤波、高斯滤波等。
下面我们将逐一介绍。
1. 均值滤波均值滤波是一种简单的滤波方法,它的原理是用一个滑动窗口在信号的每个点上进行计算,将窗口内数据的平均值作为该点的值。
这样可以将信号中的噪声平滑掉,但是也会使信号的边缘模糊化。
matlab中的均值滤波函数为:smooth、filter、conv。
其中,smooth函数可以设置滑动窗口的大小和类型:y = smooth(x,span,type);其中x为输入信号,span为窗口大小,type为平均类型,包括moving、lowess、loess、sgolay等。
filter函数可以用fir低通滤波器实现均值滤波:b = ones(1, N)/N;y = filter(b, 1, x);其中,N为窗口大小,x为输入信号,y为输出信号。
y = medfilt1(x, w);3. 高斯滤波高斯滤波是一种基于高斯函数的滤波方法,它的原理是应用高斯函数对信号进行平滑,可以有效地滤除高斯白噪声、高斯随机噪声等。
imgaussfilt函数可以实现一维和二维高斯滤波:其中x为输入信号,sigma为标准差。
fspecial函数可以生成高斯滤波核:h = fspecial('gaussian', hsize, sigma);以上就是matlab中的统计滤波方法介绍,读者可根据自己的需求选择合适的方法进行信号处理。
21种nr的iqa处理算法及通用函数
21种nr的iqa处理算法及通用函数引言在数字图像处理中,图像质量评估(I QA)是一个重要的研究领域。
其中,噪声降低(N R)算法被广泛应用于提高图像的质量。
本文将介绍21种常用的NR的I Q A处理算法及通用函数。
1.均值滤波均值滤波是一种常见的降噪算法。
它通过计算像素周围邻域的均值来减小噪声。
均值滤波可以使用以下通用函数实现:d e fm ea n_fi lt er(im a ge):"""均值滤波"""实现算法代码r e tu rn fi lt er ed_im a ge2.中值滤波中值滤波也是一种常用的NR算法,它使用像素点周围邻域中的中值来减小噪声的影响。
以下是中值滤波的通用函数:d e fm ed ia n_fi lt er(i ma ge):"""中值滤波"""实现算法代码r e tu rn fi lt er ed_im a ge3.高斯滤波高斯滤波是一种基于高斯函数的线性平滑滤波器。
它通过计算像素点周围邻域的加权平均值来降低噪声。
以下是高斯滤波的通用函数:d e fg au ss ia n_fi lte r(i ma ge):"""高斯滤波"""实现算法代码r e tu rn fi lt er ed_im a ge4.双边滤波双边滤波是一种保留图像边缘的滤波方法。
它通过考虑像素点的空间距离和像素值之间的差异来平滑图像。
以下是双边滤波的通用函数:d e fb il at er al_f ilt e r(im ag e):"""双边滤波"""实现算法代码r e tu rn fi lt er ed_im a ge5.小波去噪小波去噪是一种基于小波变换的降噪方法。
