4. RGB 彩色图像分割
function [C,m]=covmatrix(X) [K,n]=size(X); X=double(X); if n==1 C=0; m=x; else
m=sum(X,1)/K;
X=X-m(ones(K,1),:); C=(X'*X)/(K-1); m=m'; end
function I=colorseg(varargin) f=varargin{2};
if(ndims(f)~=3)|(size(f,3)~=3) error('Input image must be RGB!'); end
M=size(f,1); N=size(f,2); [f,L]=imstack2vectors(f); f=double(f); I=zeros(M*N,1); T=varargin{3}; m=varargin{4};
m=m(:)';%make sure that m is a row vetor if length(varargin)==4 method='euclidean';
elseif length(varargin)==5 method='mahalanobis'; else
error('wrong number of inputs!'); end
switch method case 'euclidean' p=length(f);
D=sqrt(sum(abs(f-repmat(m,p,1)).^2,2)); case 'mahalanobis' C=varargin{5};
D=mahalanobis(f,C,m); otherwise
error('Unknown segmentation method!'); end
J=find(D<=T); I(J)=1;
I=reshape(I,M,N);
function [X,R]=imstack2vectors(S,MASK) [M,N,n]=size(S); if nargin==1
MASK=true(M,N); else
MASK=MASK~=0; end
[I,J]=find(MASK); R=[I,J]; Q=M*N;
X=reshape(S,Q,n);
MASK=reshape(MASK,Q,1); X=X(MASK,:);
%%%%%%RGB 图像分割主程序
clear all
clc
f=imread('D:\\Fig0630(01)(strawberries_fullcolor).tif'); mask=roipoly(f);
subplot(2,3,1),imshow(mask)%mask 是一幅2 值图像(大小与f 相同) red=immultiply(mask,f(:,:,1)); subplot(2,3,2),imshow(red) title('red 分量');
green=immultiply(mask,f(:,:,2)); subplot(2,3,3),imshow(green) title('green 分量');
blue=immultiply(mask,f(:,:,3)); subplot(2,3,4),imshow(blue) title('blue 分量');
g=cat(3,red,green,blue); subplot(2,3,5),imshow(g)
%计算ROI 中的点的均值向量和协方差矩阵 [M,N,K]=size(g); I=reshape(g,M*N,3); idx=find(mask);
I=double(I(idx,1:3)); [C,m]=covmatrix(I); d=diag(C); sd=sqrt(d)'
E25=colorseg('euclidean',f,25,m);
%colorseg('m',f,T,m)T 值可取的值为25 的倍数时得到的不同结果
实验六小波变换
一、 实验目的
1 Haar、尺度和小波函数;
2 比较函数wavefast 和函数wavedec2 的执行时间; 3 小波的方向性和边缘检测。
二、 实验步骤
1.1. Haar、尺度和小波函数
[Lo_D,Hi_D,Lo_R,Hi_R]=wfilters('haar')%Haar 变换的分解和重构滤波器的长度 为2
waveinfo('haar');
[phi,psi,xval]=wavefun('haar',10); xaxis=zeros(size(xval));
subplot(121);plot(xval,phi,'k',xval,xaxis,'--k'); axis([0 1 -1.5 1.5]);axis square; title('haar scaling function');