colorgrad.m算法
%梯度邊緣提取算法 function [VG, A, PPG] = colorgrad(f, T) if (ndims(f)~=3) || (size(f,3)~=3) %ndims是matlab中求一個數組維數的函數,size(f,3)返回f的行數 error('Input image must be RGB'); end sh = fspecial('sobel'); %sobel用於邊緣提取 sv = sh'; %轉置 Rx = imfilter(double(f(:,:,1)), sh, 'replicate');%線性空間濾波函數;replicate表示圖像大小經過複製外邊界的值來擴展, Ry = imfilter(double(f(:,:,1)), sv, 'replicate');%symmetric表示圖像大小經過沿自身的邊界進行濾鏡 Gx = imfilter(double(f(:,:,2)), sh, 'replicate');%circular表示經過將圖像做爲二位周期函數的一個週期來擴展 Gy = imfilter(double(f(:,:,2)), sv, 'replicate'); Bx = imfilter(double(f(:,:,3)), sh, 'replicate'); By = imfilter(double(f(:,:,3)), sv, 'replicate'); gxx = Rx.^2 + Gx.^2 + Bx.^2; gyy = Ry.^2 + Gy.^2 + By.^2; gxy = Rx.*Ry + Gx.*Gy + Bx.*By; A = 0.5*(atan(2*gxy./(gxx-gyy+eps))); %%atan計算反正切函數 ||||| %%./點除 ||||| 若是a、b是矩陣,a./b就是a、b中對應的每一個元素相除,獲得一個新的矩陣;若是a、b是兩個數,那麼a./b就是普通的除法 %%eps是一個函數,能夠返回某一個數N的最小浮點數精度||||| G1 = 0.5*((gxx+gyy) + (gxx-gyy).*cos(2*A) + 2*gxy.*sin(2*A)); % A = A + pi/2; G2 = 0.5*((gxx+gyy) + (gxx-gyy).*cos(2*A) + 2*gxy.*sin(2*A)); G1 = G1.^0.5; G2 = G2.^0.5; VG = mat2gray(max(G1, G2)); %mat2gray實現圖像矩陣的歸一化操做 RG = sqrt(Rx.^2 + Ry.^2); GG = sqrt(Gx.^2 + Gy.^2); BG = sqrt(Bx.^2 + By.^2); PPG = mat2gray(RG + GG + BG); if nargin ==2 %是用來判斷輸入變量個數的函數 VG = (VG>T).*VG; PPG = (PPG>T).*PPG; end
demo.m數組
close all;clear all;clc; f = imread('wo.jpg'); [VG,A,PPG] = colorgrad(f); ppg = im2uint8(PPG); %把圖像數據類型轉換爲無符號八位整型 ppgf = 255 - ppg; [M,N] = size(ppgf); T=150; ppgf1 = zeros(M,N); for ii = 1:M for jj = 1:N if ppgf(ii,jj)<T %邊緣區域 % ppgf1(ii,jj)=0; ppgf1(ii,jj)=(T-ppgf1(ii,jj))/5; else %平滑區域 ppgf1(ii,jj)=235/(255-T)*(ppgf(ii,jj)-T); end end end ppgf1 = uint8(ppgf1); figure; subplot(221);imshow(ppgf); subplot(222);imshow(ppgf1); subplot(223);imhist(ppgf); subplot(224);imhist(ppgf1); figure;imshow(ppgf1);
實驗原圖:函數
實驗效果:
ui