使用MATLAB 基于贝叶斯决策的图像分割
OpenCV下载使用
使用MATLAB 基于贝叶斯决策的Nemo鱼像素点分类
参数方法
灰度图像分割
clc
clear all
%load array_sample and Mask data
sample=cell2mat(struct2cell(load('C:\Users\Tony Stack\Desktop\第二次大作业\array_sample')));
Mask=cell2mat(struct2cell(load('C:\Users\Tony Stack\Desktop\第二次大作业\Mask.mat')));
%Load imgage
I=im2double(imread('C:\Users\Tony Stack\Desktop\第二次大作业\309.bmp'));
Ig=im2double(rgb2gray(I));%灰色图片
nemo_gray=Ig.*Mask;%灰色nemo
imshow(nemo_gray)
%%参数计算及pdf的确定
%提取两类灰度样本
j=1;
for i=1:length(sample)
if(sample(i,5)==1)
sample_gray1(i)=sample(i,1);
else
sample_gray2(j)=sample(i,1);
j=j+1;
end
end
%计算先验概率
p1=length(sample_gray1)/length(sample);
p2=length(sample_gray2)/length(sample);
%计算两类灰度样本的mu和sigma
%使得似然函数偏导为0
mu1=1/length(sample_gray1)*sum(sample_gray1(:));
A1=(sample_gray1-mu1).^2;
sigma1=sqrt(1/length(sample_gray1)*sum(A1(:)));
mu2=1/length(sample_gray2)*sum(sample_gray2(:));
A2=(sample_gray2-mu2).^2;
sigma2=sqrt(1/length(sample_gray2)*sum(A2(:)));
% %plot 两类pdf
% figure()
% fplot(@(x)normpdf(x,mu1,sigma1),[0,1]),hold on
% fplot(@(x)normpdf(x,mu2,sigma2),[0,1])
% title ('pdf')
% legend('sample gray1','sample gray2')
%%gray segment
[M,N]=size(Ig);%灰度图像大小
Gray=reshape(nemo_gray,M*N,1);
for i=1:M*N
if Gray(i)==0
out(i)=0;
else
%判别函数
g1=p1*normpdf(Gray(i),mu1,sigma1);
g2=p2*normpdf(Gray(i),mu2,sigma2);
if (g1>g2)
out(i)=255;
else
out(i)=0;
end
end
end
gray_segment=reshape(out,[M,N]);
figure()
imshow(gray_segment)
title('gray segmented image')
results:
彩色图像分割
clc
clear all
%load array_sample and Mask data
sample=cell2mat(struct2cell(load('C:\Users\Tony Stack\Desktop\第二次大作业\array_sample')));
Mask=cell2mat(struct2cell(load('C:\Users\Tony Stack\Desktop\第二次大作业\Mask.mat')));
%Load imgage
I=im2double(imread('C:\Users\Tony Stack\Desktop\第二次大作业\309.bmp'));
nemo=I.*Mask;%彩色nemo
imshow(nemo)
%提取两类RGB样本
j=1;
for i=1:length(sample)
if(sample(i,5)==1)
RGB1(i,1:3)=sample(i,2:4);
else
RGB2(j,1:3)=sample(i,2:4);
j=j+1;
end
end
%计算先验概率
p1=length(RGB1)/length(sample);
p2=length(RGB2)/length(sample);
%确定pdf的参数
mu1=mean(RGB1);
mu2=mean(RGB2);
%协方差矩阵
delta1=cov(RGB1);
delta2=cov(RGB2);
%分割彩色图像
[M,N,H]=size(I);%彩色图像大小
Color=reshape(nemo,M*N,3)';
%plot pdf
for i=1:M*N
if(Color(:,i)==[0;0;0])
out(:,i)=[0;0;0];
else
g1=p1*mvnpdf(Color(:,i)',mu1,delta1);
g2=p2*mvnpdf(Color(:,i)',mu2,delta2);
if(g1>=g2)
out(:,i)=[1,0,0];
else
out(:,i)=[0,0,1];
end
end
end
Color_segmented=reshape((out)',M,N,H);
figure()
imshow(Color_segmented)
title('color segmented image')
results: