天天看點

圖像處理:均值濾波

濾波

濾波是将信号中特定波段頻率濾除的操作,是從含有幹擾的接收信号中提取有用信号的一種技術。

均值濾波

均值濾波是典型的線性濾波算法,它是指在圖像上對目标像素給一個模闆,該模闆包括了其周圍的臨近像素(如3×3模闆:以目标象素為中心的周圍8個象素,構成一個濾波模闆,即去掉目标象素本身),再用模闆中的全體像素的平均值來代替原來像素值。

效果

平滑線性濾波處理降低了圖像的“尖銳”變化。由于典型的随機噪聲由灰階級的急劇變化組成,是以常見的平滑處理的應用就是降低噪聲。均值濾波器的主要應用是去除圖像中的不相關細節,其中“不相關”是指與濾波器模闆尺寸相比較小的像素區域。然而,由于圖像的邊緣也是由圖像灰階的尖銳變化帶來的特性,是以均值濾波處理還是存在着邊緣模糊的負面效應。

實驗

使用OpenCV進行實驗的部分代碼:

IplImage *pImgTmp = cvCloneImage(m_pImg);

	// 第二種邊界處理:對邊界特殊處理
	for (i = 0; i < m_pImg->width; i++)
	{
		for (j = 0; j < m_pImg->height; j++)
		{
			CvScalar color;
			CvScalar colorTmp;
			int m, n, cnt = 0;
			color.val[0] = color.val[1] = color.val[2] = 0;		
			for (m = i - nKernelSize/2; m <= i+nKernelSize/2; m++)
			{
				for (n = j-nKernelSize/2; n <= j+nKernelSize/2; n++)
				{
					// 處理邊界和中心像素
					if ( (m == i && n == j) || m < 0 || m >= m_pImg->width 
						|| n < 0 || n >= m_pImg->height )
						continue;
					
					cvGetPixel(pImgTmp, n, m, colorTmp);
					color.val[0] += colorTmp.val[0];
					color.val[1] += colorTmp.val[1];
					color.val[2] += colorTmp.val[2];
					cnt++;
				}
			}
			// 取鄰域中像素的平均值
			color.val[0] /= cnt;
			color.val[1] /= cnt;
			color.val[2] /= cnt;
			cvSetPixel(m_pImg, j, i, color);
		}
	}
	cvReleaseImage(&pImgTmp);
           

其中cvGetPixel和cvSetPixel的定義為:

void  cvGetPixel(const IplImage* pIplImg, int row, int col, CvScalar &color)
{
	if (col >= pIplImg->width || col < 0 ||
		row >= pIplImg->height || row < 0 )
		return;
	
	uchar *p = ((uchar*)(pIplImg->imageData + pIplImg->widthStep * row + col * 3));
	color = cvScalar(p[0], p[1], p[2]);
}

void  cvSetPixel(IplImage* pIplImg, int row, int col, CvScalar color)
{
	if (col >= pIplImg->width || col < 0 ||
		row >= pIplImg->height || row < 0 )
		return;
	
	uchar *p = ((uchar*)(pIplImg->imageData + pIplImg->widthStep * row + col * 3));
	p[2] = color.val[2];
	p[1] = color.val[1];
	p[0] = color.val[0];
}
           

測試圖原圖:

圖像處理:均值濾波
圖像處理:均值濾波

3×3模闆結果:

圖像處理:均值濾波
圖像處理:均值濾波

5×5模闆結果:

圖像處理:均值濾波
圖像處理:均值濾波

21×21模闆結果:

圖像處理:均值濾波
圖像處理:均值濾波

參考

http://baike.baidu.com/view/1220844.htm

http://page.renren.com/601107605/note/803745240

繼續閱讀