5.13 图像平滑
图像平滑常用于图像的预处理中,如计算梯度时先对图像进行平滑处理,可以减少噪声对梯度的影响。图像平滑一般是通过模板卷积运算实现。模板可以看做是一个大小为nxn的小图像,例如3x3,5x5等等,模板的每个像素都对应一个系数值。模板卷积运算的过程是首先将模板中心依次与图像每个像素重合,通过模板各个系数与图像对应像素相乘来计算模板对应像素的加权平均值,最后将运算结果赋给图像中模板中心对应的像素。
5.13.1 均值滤波
均值滤波是一种经常用到的平滑方法,其对应的模板各个像素的值为1。在VTK中没有直接实现均值滤波的类,但是我们可以通过图像卷积运算来实现。卷积运算通过vtkImageConvolve类实现。通过vtkImageConvolve类,只需要设置相应的卷积模板,便可以实现多种空域图像滤波。下面代码说明了怎样使用vtkImageConvolve类来实现图像的均值滤波。
1: vtkSmartPointer<vtkJPEGReader>reader =
2: vtkSmartPointer<vtkJPEGReader>::New();
3: reader->SetFileName("lena2.jpg");
4: reader->Update();
5:
6: vtkSmartPointer<vtkImageCast> originalCastFilter =
7: vtkSmartPointer<vtkImageCast>::New();
8: originalCastFilter->SetInputConnection(reader->GetOutputPort());
9: originalCastFilter->SetOutputScalarTypeToFloat();
10: originalCastFilter->Update();
11:
12: vtkSmartPointer<vtkImageConvolve> convolveFilter =
13: vtkSmartPointer<vtkImageConvolve>::New();
14: convolveFilter->SetInputConnection(originalCastFilter->GetOutputPort());
15: double kernel[25] ={0.04,0.04,0.04,0.04,0.04,
16: 0.04,0.04,0.04,0.04,0.04,
17: 0.04,0.04,0.04,0.04,0.04,
18: