- 卷積簡介
卷積廣泛應用於信號、圖像和機器學習等領域,但是對於非數學專業的同學來說,是一個比較陌生和懵懂的概念。卷積(Convolution)是數學上的一種積分變換,主要作用是爲了獲取某個函數的局部信息。。
- 算法實現
function [ mF, nF, half_mF, half_nF ] = FilterRadius( filter )
%功能:
% 獲取濾波器的維數信息
%輸入參數:
% filter:濾波器
%輸出參數:
% mF:高度
% nF:寬度
% half_mF:高度一半
% half_nF:寬度一半
[mF, nF] = size( filter );
half_mF = mF / 2;
half_nF = nF / 2;
function imData = ImageExtension( image, fWidth, fHeight, fHalfWidht, fHalfHeight )
%功能:
% 在圖像的四周擴展像素,得到擴展的圖像,以方便圖像卷積運算後圖像的維數不變
% 擴展的圖像像素值均爲0
%輸入參數:
% image:圖像數據
% fWidth:濾波器的寬度
% fHeight:濾波器的高度
% fHalfWidht:濾波器的寬度的一半
% fHalfHeight:濾波器的高度度的一半
%輸出參數:
% imData:擴展後的圖像數據
[mI, nI] = size( image );
tempImage = zeros( mI + fHeight, nI + fWidth );
aUp = zeros( fHalfHeight, nI + fWidth );%
aLeft = zeros( mI, fHalfWidht ); %
aMiddle = [aLeft, image, aLeft]; %
tempImage = [aUp; aMiddle; aUp]; %擴展之後的圖像數據
imData = tempImage;
%擴展之後的圖像示意圖:
%中間 ‘|’ 表示原始圖像
%四周 ‘0’ 表示增加的數據
%00000000000000000000000000%
%00||||||||||||||||||||||00%
%00||||||||||||||||||||||00%
%00||||||||||||||||||||||00%
%00||||||||||||||||||||||00%
%00||||||||||||||||||||||00%
%00||||||||||||||||||||||00%
%00||||||||||||||||||||||00%
%00||||||||||||||||||||||00%
%00000000000000000000000000%
%00000000000000000000000000%
function result = Dot2D( localImage, filter )
%圖像局部數據與濾波器的內積
result = sum( sum( localImage .* filter ) );
if result < 0
result = -result;
elseif result > 255
result = 255;
end
function imageConv = ImageConvolution( image, filter, initialHeight, intitialWidth )
%功能:
% 圖像的卷積運算
%輸入參數:
% image:擴展後的圖像
% filter:濾波器
% initialHeight:原圖像的高度
% intitialWidth:原圖像的寬度
%輸出參數:
% imageConv:卷積後的圖像
mI = initialHeight;
nI = intitialWidth;
[mF, nF] = size( filter );
convImage = zeros(mI, nI);
for i = 1:mI-1
for j = 1:nI-1
localImage = [];
localImage = image(i:i+mF-1, j:j+nF-1);
convImge(i, j) = Dot2D( localImage, filter );
end
end
imageConv = uint8( convImge );
clear
clc
image = double( imread('lena.bmp') );
[iHeight, iWidth] = size( image );
%四個濾波器
filter1 = [ 1, 1; 1, 1 ] * 0.25;
filter2 = [ 1, -1; 1, -1 ];
filter3 = [ 1, -1; -1,1 ];
filter4 = [ 1, 1; -1, -1 ];
%獲取濾波器的長度、寬度、長度的一半、寬度的一半
[fWidth, fHeight, halfWidht, halfHeight ] = FilterRadius( filter1 )
%根據濾波器的尺寸擴展圖像像素
imData = ImageExtension( image, fWidth, fHeight, halfWidht, halfHeight );
figure(1);imshow( uint8(imData) );
%利用第一個濾波器對圖像進行卷積
imageConv = ImageConvolution( image, filter1, iHeight, iWidth );
figure(2);imshow( imageConv );
%利用第二個濾波器對圖像進行卷積
imageConv = ImageConvolution( image, filter2, iHeight, iWidth );
figure(3);imshow( imageConv );
%利用第三個濾波器對圖像進行卷積
imageConv = ImageConvolution( image, filter3, iHeight, iWidth );
figure(4);imshow( imageConv );
%利用第四個濾波器對圖像進行卷積
imageConv = ImageConvolution( image, filter4, iHeight, iWidth );
figure(5);imshow( imageConv );
- 運行結果
作者:YangYF