conv2()
在不使用函数的情况下通过卷积过滤图像(移动过滤器)
填充图像:
可以通过沿图像两侧连接零来填充图像。每个大小所需的填充量取决于过滤器/内核的大小。下图总结了所需的填充量。请注意,确保过滤器具有奇数尺寸(高度和宽度)可能是最佳实践。如果过滤器没有奇数维度,那么用零填充过滤器可能是一个好主意,我将把它留给读者实现的进一步任务。有关填充的更多详细信息,请参阅此问题的答案:Rotating image with trigonometric functions and image padding。一个很棒的动画 GIF(不是我创建的),可以很好地可视化卷积过程:动画图像卷积过程。
Image = imread("Pikachu.png");
Test_Filter = [-1 0 1; -2 0 2; -1 0 1];
%Grabbing the dimensions of the filter and image%
[Filter_Height,Filter_Width] = size(Test_Filter);
[Image_Height,Image_Width] = size(Image);
%Evaluating the padding thickness required%
Side_Padding_Size = floor(Filter_Width/2);
Top_And_Bottom_Padding_Size = floor(Filter_Height/2);
%Creating the blocks of zeros to concantenate to the image%
Side_Padding = zeros(Image_Height,Side_Padding_Size);
Top_And_Bottom_Padding = zeros(Top_And_Bottom_Padding_Size,Image_Width+2*Side_Padding_Size);
%Padding the sides of the image by concatenating%
Padded_Image = [Side_Padding Image Side_Padding];
Padded_Image = [Top_And_Bottom_Padding; Padded_Image ;Top_And_Bottom_Padding];
subplot(1,2,1); imshow(Image);
subplot(1,2,2); imshow(Padded_Image);
对图像应用滤镜:
要将过滤器应用于图像,必须设置遍历的限制/边界。外部 for 循环由变量递增,Row
并Column
指示左上角像素在给定时间开始扫描与过滤器重叠的区域。下图指示了由过滤器大小设置的界限。下图中的红色方块表示 for 循环(过滤器的左上角像素)可以遍历的最大边界。您可能还希望通过旋转过滤器内核并应用相同的方法来添加垂直和水平过滤。您可能希望在进行水平和垂直过滤后获取结果的大小。下面的示例仅在一个方向上进行过滤。描述卷积和伪实现的完整 PDF:GitHub PDF:图像卷积
%Calculating bounds of traversing through the image%
[Padded_Image_Height,Padded_Image_Width] = size(Padded_Image);
Row_Limit = Padded_Image_Height - Filter_Height + 1;
Column_Limit = Padded_Image_Width - Filter_Width + 1;
Filtered_Image = zeros(Image_Height,Image_Width);
for Row = 1: Row_Limit
for Column = 1: Column_Limit
%Grabbing pixels overlapping filter%
Overlap = Padded_Image(Row:Row+(Filter_Height-1),Column:Column+(Filter_Width-1));
Filtered_Portion = double(Test_Filter).*double(Overlap);
Filtered_Portion = sum(Filtered_Portion,'all');
Filtered_Image(Row,Column) = Filtered_Portion;
end
end
subplot(1,2,1); imshow(Image);
title("Original Image");
subplot(1,2,2); imshow(uint8(Filtered_Image));
title("Filtered with Sobel Edge Filter");
使用 MATLAB R2019b 运行