MATLAB图像分割代码

合集下载

MATLAB纹理分割方法对细胞图片分割

MATLAB纹理分割方法对细胞图片分割

MATLAB纹理分割方法对细胞图片分割%1.读取图像。

代码如下:I = imread('F:\xb\xb.tif');%读取图像figure(1); imshow(I);%显示原图像%2.创建纹理图像。

代码如下:E = entropyfilt(I);%创建纹理图像Eim = mat2gray(E);%转化为灰度图像figure(2),imshow(Eim);%显示灰度图像BW1 = im2bw(Eim, .8);%转化为二值图像figure(3), imshow(BW1);%显示二值图像%3.分别显示图像的底部纹理和顶部纹理。

代码如下:BWao = bwareaopen(BW1,2000);%提取底部纹理figure(4), imshow(BWao);%显示底部纹理图像nhood = true(9);closeBWao = imclose(BWao,nhood);%形态学关操作figure(5), imshow(closeBWao)%显示边缘光滑后的图像roughMask = imfill(closeBWao,'holes');%填充操作figure(6),imshow(roughMask);%显示填充后的图像I2 = I;I2(roughMask) = 0;%底部设置为黑色figure(7), imshow(I2);%突出显示图像的顶部%4.使用entropyfilt进行滤波分割。

代码如下:E2 = entropyfilt(I2);%创建纹理图像E2im = mat2gray(E2);%转化为灰度图像figure(8),imshow(E2im);%显示纹理图像BW2 = im2bw(E2im,graythresh(E2im));%转化为二值图像figure(9), imshow(BW2)%显示二值图像mask2 = bwareaopen(BW2,1000);%求取图像顶部的纹理掩膜figure(10),imshow(mask2);%显示顶部纹理掩膜图像texture1 = I; texture1(~mask2) = 0;%底部设置为黑色texture2 = I; texture2(mask2) = 0;%顶部设置为黑色figure(11),imshow(texture1);%显示图像顶部figure(12),imshow(texture2);%显示图像底部boundary = bwperim(mask2);%求取边界segmentResults = I;segmentResults(boundary) = 255;%边界处设置为白色figure(13),imshow(segmentResults);%显示分割结果%5.使用stdfilt和rangefilt进行滤波分割。

部分图像分割的方法(matlab)

部分图像分割的方法(matlab)

部分图像分割的方法(matlab)大津法:function y1=OTSU(image,th_set)image=imread('color1.bmp');gray=rgb2gray(image);%原图像的灰度图low_high=stretchlim(gray);%增强图像,似乎也不是一定需要gray=imadjust(gray,low_high,[]);% subplot(224);imshow(gray);title('after adjust');count=imhist(gray);[r,t]=size(gray);n=r*t;l=256;count=count/n;%各级灰度出现的概率for i=2:lif count(i)~=0st=i-1;breakendend%以上循环语句实现寻找出现概率不为0的最小灰度值for i=l:-1:1if count(i)~=0;nd=i-1;breakendend%实现找出出现概率不为0的最大灰度值f=count(st+1:nd+1);p=st;q=nd-st;%p和分别是灰度的起始和结束值u=0;for i=1:q;u=u+f(i)*(p+i-1);ua(i)=u;end程序二:clc; clear;cd 'D:\My Documents\MATLAB' time = now;I = imread('qr4.bmp');figure(1),imshow(I),title('p1_1.bmp'); % show the pictureI2 = rgb2gray(I);figure(2),imshow(I2),title('I2.bmp'); %ÖÐÖµÂ˲¨J = medfilt2(I2); figure(3),imshow(J);imwrite(J,'J.bmp'); [M N] = size(J);J1 = J(1:M/2,1:fix(N/2)); J2 = J(1:M/2,fix(N/2)+1:N); J3 = J(M/2+1:M, 1:fix( N/2)); J4 = J(M/2+1:M, fix(N/2)+1:N); % figure(4), img = J1;T1 = test_gray2bw( img ); % figure(5), img = J2;T2 = test_gray2bw( img ); % figure(6), img = J3;T3 = test_gray2bw( img ); % figure(7), img = J4;T4 = test_gray2bw( img ); T = [T1,T2;T3,T4]; figure,imshow(T)% T1 = edge(T,'sobel'); % figure,imshow(T1); % BW = edge(T,'sobel'); % f igure,imshow(BW);function [bw_img] = test_gray2bw( img ) %大津法[row_img col_img ] = size( img ) all_pix = row_img * col_img% get probability of each pixel(ÏñËØ). count_pix = zeros(1,256) % pro_pix = []for i = 1 : 1 : row_img for j = 1 : 1 : col_imgcount_pix(1,img(i,j)+1) = count_pix(1,img(i,j)+1) + 1 %ͳ¼Æ´ÎÊý end en dpro_pix = count_pix / all_pix% choose k value; max_kesi = -1 T = 0for k = 1 : 1 :while( i <= k )wa = wa + pro_pix(1,i+1) %Ç°k¸öi£¬Ã¿¸öÏñËصĻҶȸÅÂÊ£¬¸ÅÂÊºÍ ua = ua + i * pro_pix(1,i+1) i = i + 1 endif ( wa == 0.0 ) continue; elseua = ua / wa endub = 0 wb = 0 i = k + 1while( i <= 255 )wb = wb + pro_pix( 1 , i + 1 )ub = ub + i * pro_pix( 1 , i + 1 ) i = i + 1 endif ( wb == 0.0 ) continue; elseub = ub / wb endu = wa * ua + wb * ub% kesi = wa * ( ua - u ) * ( ua - u ) + wb * ( ub - u ) * ( ub -u ) % %ÉÏÏÂÕâÁ½¸ö¹«Ê½Êǵȼ۵Äkesi = wa * wb * (ua - ub)^2; if( kesi > max_kesi ) max_kesi = kesi T = k end end% get bw img bw_img = imgfor i = 1 : 1 : row_img for j = 1 : 1 : col_img if ( img(i,j) <= T ) bw_img(i,j) = 0elsebw_img( i,j ) = 255 end end endimwrite(bw_img,'bw_img.bmp')figure(),imshow('bw_img.bmp')%,title('bw_ing')区域生长法:close all;clear all;clc;A=dicomread('im.dcm');%读入图像(医学CT图像)% seed=[200,220];%选择起始位置thresh=6.3;%相似性选择阈值%A=rgb2gray(A0);%A=A0;%灰度化%A=imadjust(A,[min(min(double(A)))/255,max(max(double(A)))/255],[]); figure,imshow(A,[]);A=double(A); %将图像灰度化[y,x]=getpts; %获得区域生长起始点x1=round(x); %横坐标取整y1=round(y); %纵坐标取整seed=A(x1,y1);B=A;%将A赋予B[r,c]=size(B);%图像尺寸r为行数,c为列数n=r*c;%计算图像所包含点的个数pixel_seed=seed;%原图起始点灰度值q=[x1 y1];%q用来装载起始位置top=1;%循环判断flagM=zeros(r,c);%建立一个与原图形同等大小的矩阵M(x1,y1)=1;%将起始点赋为1,其余为0count=1;%计数器while top~=0%也可以写成top!=0 循环结束条件r1=q(1,1);%起始点行位置c1=q(1,2);%起始点列位置p=A(r1,c1);%起始点灰度值dge=0;for i=-1:1%周围点的循环判断for j=-1:1if r1+i<=r&r1+i>0&c1+j<=c&c1+j>0%保证在点周围范围之内if abs(A(r1+i,c1+j)-p)<=thresh&M(r1+i,c1+j)~=1%判定条件?top=top+1;%满足判定条件top加1,top为多少,则q的行数有多少行q(top,:)=[r1+i c1+j];%将满足判定条件的周围点的位置赋予q,q记载了满足判定的每一外点M(r1+i,c1+j)=1;%满足判定条件将M中相对应的点赋为1count=count+1;%统计满足判定条件的点个数,其实与top此时的值一样B(r1+i,c1+j)=1;%满足判定条件将B中相对应的点赋为1endif M(r1+i,c1+j)==0;%如果M中相对应点的值为0将dge赋为1,也是说这几个点不满足条件dge=1;%将dge赋为1endelsedge=1;%点在图像外将dge赋为1endendend%此时对周围几点判断完毕,在点在图像外或不满足判定条件则将dge赋为1,满足条件dge为0if dge~=1%最后判断的周围点(i=1,j=1)是否满足条件,如dge=0,满足。

基于Matlab的彩色图像分割

基于Matlab的彩色图像分割

3 Matlab编程实现3.1 Matlab编程过程用Matlab来分割彩色图像的过程如下:1)获取图像的RGB颜色信息。

通过与用户的交互操作来提示用户输入待处理的彩色图像文件路径;2)RGB彩色空间到lab彩色空间的转换。

通过函数makecform()和applycform()来实现; 3)对ab分量进行Kmean聚类。

调用函数kmeans()来实现;4)显示分割后的各个区域。

用三副图像分别来显示各个分割目标,背景用黑色表示。

3.2 Matlab程序源码%文件读取clear;clc;file_name = input('请输入图像文件路径:','s');I_rgb = imread(file_name); %读取文件数据figure();imshow(I_rgb); %显示原图title('原始图像');%将彩色图像从RGB转化到lab彩色空间C = makecform('srgb2lab'); %设置转换格式I_lab = applycform(I_rgb, C);%进行K-mean聚类将图像分割成3个区域ab = double(I_lab(:,:,2:3)); %取出lab空间的a分量和b分量nrows = size(ab,1);ncols = size(ab,2);ab = reshape(ab,nrows*ncols,2);nColors = 3; %分割的区域个数为3[cluster_idx cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean','Replicates',3); %重复聚类3次pixel_labels = reshape(cluster_idx,nrows,ncols);figure();imshow(pixel_labels,[]), title('聚类结果');%显示分割后的各个区域segmented_images = cell(1,3);rgb_label = repmat(pixel_labels,[1 1 3]);for k = 1:nColorscolor = I_rgb;color(rgb_label ~= k) = 0;segmented_images{k} = color;endfigure(),imshow(segmented_images{1}), title('分割结果——区域1'); figure(),imshow(segmented_images{2}), title('分割结果——区域2'); figure(),imshow(segmented_images{3}), title('分割结果——区域3');。

MATLAB图像分割代码

MATLAB图像分割代码

[matlab图像处理]阈值分割%迭代式阈值分割otsu阈值分割二值化close all;%关闭所有窗口clear;% 清除变量的状态数据clc;% 清除命令行I=imread('rice.png');subplot(2,2,1);imshow(I);title('1 rice的原图');%迭代式阈值分割zmax=max(max(I));% 取出最大灰度值zmin=min(min(I));%取出最小灰度值tk=(zmax+zmin)/2;bcal=1;[m,n]=size(I);while(bcal)%定义前景和背景数iforeground=0;ibackground=0;%定义前景和背景灰度总和foregroundsum=0;backgroundsum=0;for i=1:mfor j=1:ntmp=I(i,j);if(tmp>=tk)%前景灰度值iforeground=iforeground+1;foregroundsum=foregroundsum+double(tmp );elseibackground=ibackground+1;backgroundsum=backgroundsum+double(tmp );endendend%计算前景和背景的平均值z1=foregroundsum/iforeground;z2=foregroundsum/ibackground;tktmp=uint8((z1+z2)/2);if(tktmp==tk)bcal=0;elsetk=tktmp;end%当阈值不再变化时, 说明迭代结束enddisp(strcat(' 迭代的阈值迭代的阈值: 阈值:',num2str(tk)));%在 command window里显示出:newI=im2bw(I,double(tk)/255);%函数 im2bw 使用阈值( threshold )变换法把灰度图像( grayscale image)%转换成二值图像。

MATLAB图像分割算法源代码

MATLAB图像分割算法源代码

MATLAB图像分割算法源代码MATLAB图像分割算法源代码 1.图像反转MATLAB程序实现如下:I=imread('xian.bmp'); J=double(I);J=-J+(256-1); %图像反转线性变换H=uint8(J);subplot(1,2,1),imshow(I); subplot(1,2,2),imshow(H); 2.灰度线性变换MATLAB程序实现如下:I=imread('xian.bmp'); subplot(2,2,1),imshow(I); title('原始图像');axis([50,250,50,200]); axis on; %显示坐标系I1=rgb2gray(I);subplot(2,2,2),imshow(I1); title('灰度图像');axis([50,250,50,200]); axis on; %显示坐标系J=imadjust(I1,[0.1 0.5],[]); %局部拉伸,把[0.1 0.5]内的灰度拉伸为[0 1]subplot(2,2,3),imshow(J); title('线性变换图像[0.1 0.5]');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系K=imadjust(I1,[0.3 0.7],[]); %局部拉伸,把[0.3 0.7]内的灰度拉伸为[0 1]subplot(2,2,4),imshow(K); title('线性变换图像[0.3 0.7]');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系3.非线性变换MATLAB程序实现如下:I=imread('xian.bmp'); I1=rgb2gray(I);subplot(1,2,1),imshow(I1); title('灰度图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系J=double(I1); J=40*(log(J+1)); H=uint8(J);subplot(1,2,2),imshow(H);title('对数变换图像');axis([50,250,50,200]);grid on; %显示网格线 axis on; %显示坐标系 4.直方图均衡化MATLAB程序实现如下:I=imread('xian.bmp');I=rgb2gray(I); figure;subplot(2,2,1); imshow(I);subplot(2,2,2); imhist(I);I1=histeq(I); figure;subplot(2,2,1); imshow(I1);subplot(2,2,2);imhist(I1);5.线性平滑滤波器用MATLAB实现领域平均法抑制噪声程序:I=imread('xian.bmp');subplot(231)imshow(I)title('原始图像')I=rgb2gray(I);I1=imnoise(I,'salt & pepper',0.02);subplot(232)imshow(I1)title('添加椒盐噪声的图像')k1=filter2(fspecial('average',3),I1)/255; %进行3*3模板平滑滤波k2=filter2(fspecial('average',5),I1)/255; %进行5*5模板平滑滤波k3=filter2(fspecial('average',7),I1)/255; %进行7*7模板平滑滤波k4=filter2(fspecial('average',9),I1)/255; %进行9*9模板平滑滤波subplot(233),imshow(k1);title('3*3模板平滑滤波');subplot(234),imshow(k2);title('5*5模板平滑滤波');subplot(235),imshow(k3);title('7*7模板平滑滤波');subplot(236),imshow(k4);title('9*9模板平滑滤波'); 6.中值滤波器用MATLAB实现中值滤波程序如下:I=imread('xian.bmp'); I=rgb2gray(I);J=imnoise(I,'salt&pepper',0.02);subplot(231),imshow(I);title('原图像');subplot(232),imshow(J);title('添加椒盐噪声图像'); k1=medfilt2(J); %进行3*3模板中值滤波 k2=medfilt2(J,[5,5]); %进行5*5模板中值滤波k3=medfilt2(J,[7,7]); %进行7*7模板中值滤波 k4=medfilt2(J,[9,9]); %进行9*9模板中值滤波 subplot(233),imshow(k1);title('3*3模板中值滤波'); subplot(234),imshow(k2);title('5*5模板中值滤波');subplot(235),imshow(k3);title('7*7模板中值滤波');subplot(236),imshow(k4);title('9*9模板中值滤波'); 7.用Sobel算子和拉普拉斯对图像锐化:I=imread('xian.bmp'); subplot(2,2,1),imshow(I); title('原始图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I1=im2bw(I);subplot(2,2,2),imshow(I1); title('二值图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系H=fspecial('sobel'); %选择sobel算子 J=filter2(H,I1); %卷积运算subplot(2,2,3),imshow(J); title('sobel算子锐化图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系h=[0 1 0,1 -4 1,0 1 0]; %拉普拉斯算子J1=conv2(I1,h,'same'); %卷积运算subplot(2,2,4),imshow(J1);title('拉普拉斯算子锐化图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系8.梯度算子检测边缘用MATLAB实现如下:I=imread('xian.bmp'); subplot(2,3,1);imshow(I);title('原始图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I1=im2bw(I);subplot(2,3,2);imshow(I1);title('二值图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I2=edge(I1,'roberts'); figure;subplot(2,3,3);imshow(I2);title('roberts算子分割结果');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I3=edge(I1,'sobel'); subplot(2,3,4); imshow(I3);title('sobel算子分割结果');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I4=edge(I1,'Prewitt'); subplot(2,3,5); imshow(I4);title('Prewitt算子分割结果');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系9.LOG算子检测边缘用MATLAB程序实现如下:I=imread('xian.bmp'); subplot(2,2,1);imshow(I);title('原始图像');I1=rgb2gray(I);subplot(2,2,2); imshow(I1);title('灰度图像');I2=edge(I1,'log'); subplot(2,2,3); imshow(I2);title('log算子分割结果');10.Canny算子检测边缘用MATLAB程序实现如下:I=imread('xian.bmp');subplot(2,2,1); imshow(I);title('原始图像')I1=rgb2gray(I); subplot(2,2,2); imshow(I1);title('灰度图像');I2=edge(I1,'canny');subplot(2,2,3); imshow(I2);title('canny算子分割结果'); 11.边界跟踪(bwtraceboundary函数) clcclear allI=imread('xian.bmp'); figureimshow(I);title('原始图像');I1=rgb2gray(I); %将彩色图像转化灰度图像 threshold=graythresh(I1); %计算将灰度图像转化为二值图像所需的门限BW=im2bw(I1, threshold); %将灰度图像转化为二值图像 figureimshow(BW);title('二值图像');dim=size(BW);col=round(dim(2)/2)-90; %计算起始点列坐标 row=find(BW(:,col),1); %计算起始点行坐标 connectivity=8;num_points=180;contour=bwtraceboundary(BW,[row,col],'N',connectivity,num_points);%提取边界figureimshow(I1);hold on;plot(contour(:,2),contour(:,1), 'g','LineWidth' ,2);title('边界跟踪图像');12.Hough变换I= imread('xian.bmp'); rotI=rgb2gray(I);subplot(2,2,1);imshow(rotI);title('灰度图像');axis([50,250,50,200]); grid on; axis on;BW=edge(rotI,'prewitt'); subplot(2,2,2);imshow(BW);title('prewitt算子边缘检测后图像');axis([50,250,50,200]); grid on; axis on;[H,T,R]=hough(BW);subplot(2,2,3);imshow(H,[],'XData',T,'YData',R,'InitialMagnification','fit'); title('霍夫变换图');xlabel('\theta'),ylabel('\rho');axis on , axis normal, hold on;P=houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));x=T(P(:,2));y=R(P(:,1));plot(x,y,'s','color','white');lines=houghlines(BW,T,R,P,'FillGap',5,'MinLength',7);subplot(2,2,4);,imshow(rotI);title('霍夫变换图像检测');axis([50,250,50,200]);grid on;axis on;hold on;max_len=0;for k=1:length(lines)xy=[lines(k).point1;lines(k).point2];plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');len=norm(lines(k).point1-lines(k).point2);if(len>max_len)max_len=len;xy_long=xy;endendplot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','cyan');13.直方图阈值法用MATLAB实现直方图阈值法:I=imread('xian.bmp'); I1=rgb2gray(I);figure;subplot(2,2,1);imshow(I1);title('灰度图像')axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系[m,n]=size(I1); %测量图像尺寸参数 GP=zeros(1,256); %预创建存放灰度出现概率的向量for k=0:255GP(k+1)=length(find(I1==k))/(m*n); %计算每级灰度出现的概率,将其存入GP中相应位置endsubplot(2,2,2),bar(0:255,GP,'g') %绘制直方图 title('灰度直方图') xlabel('灰度值')ylabel('出现概率')I2=im2bw(I,150/255); subplot(2,2,3),imshow(I2); title('阈值150的分割图像')axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I3=im2bw(I,200/255); % subplot(2,2,4),imshow(I3); title('阈值200的分割图像')axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系14. 自动阈值法:Otsu法用MATLAB实现Otsu算法:clcclear allI=imread('xian.bmp');subplot(1,2,1),imshow(I); title('原始图像')axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系level=graythresh(I); %确定灰度阈值BW=im2bw(I,level); subplot(1,2,2),imshow(BW); title('Otsu法阈值分割图像')axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系15.膨胀操作I=imread('xian.bmp'); %载入图像I1=rgb2gray(I);subplot(1,2,1);imshow(I1);title('灰度图像')axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系se=strel('disk',1); %生成圆形结构元素I2=imdilate(I1,se); %用生成的结构元素对图像进行膨胀subplot(1,2,2);imshow(I2);title('膨胀后图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系16.腐蚀操作MATLAB实现腐蚀操作I=imread('xian.bmp'); %载入图像I1=rgb2gray(I);subplot(1,2,1);imshow(I1);title('灰度图像')axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系se=strel('disk',1); %生成圆形结构元素 I2=imerode(I1,se); %用生成的结构元素对图像进行腐蚀 subplot(1,2,2);imshow(I2);title('腐蚀后图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系17.开启和闭合操作用MATLAB实现开启和闭合操作I=imread('xian.bmp'); %载入图像subplot(2,2,1),imshow(I); title('原始图像');axis([50,250,50,200]); axis on; %显示坐标系I1=rgb2gray(I);subplot(2,2,2),imshow(I1); title('灰度图像');axis([50,250,50,200]); axis on; %显示坐标系se=strel('disk',1); %采用半径为1的圆作为结构元素 I2=imopen(I1,se); %开启操作I3=imclose(I1,se); %闭合操作subplot(2,2,3),imshow(I2); title('开启运算后图像');axis([50,250,50,200]); axis on; %显示坐标系subplot(2,2,4),imshow(I3); title('闭合运算后图像');axis([50,250,50,200]); axis on; %显示坐标系18.开启和闭合组合操作I=imread('xian.bmp'); %载入图像subplot(3,2,1),imshow(I); title('原始图像');axis([50,250,50,200]); axis on; %显示坐标系I1=rgb2gray(I);subplot(3,2,2),imshow(I1); title('灰度图像');axis([50,250,50,200]); axis on; %显示坐标系se=strel('disk',1); I2=imopen(I1,se); %开启操作I3=imclose(I1,se); %闭合操作subplot(3,2,3),imshow(I2); title('开启运算后图像');axis([50,250,50,200]); axis on; %显示坐标系subplot(3,2,4),imshow(I3); title('闭合运算后图像');axis([50,250,50,200]); axis on; %显示坐标系se=strel('disk',1); I4=imopen(I1,se);I5=imclose(I4,se);—闭运算图像 subplot(3,2,5),imshow(I5); %开title('开—闭运算图像');axis([50,250,50,200]); axis on; %显示坐标系I6=imclose(I1,se); I7=imopen(I6,se);subplot(3,2,6),imshow(I7); %闭—开运算图像 title('闭—开运算图像'); axis([50,250,50,200]); axis on; %显示坐标系 19.形态学边界提取利用MATLAB实现如下:I=imread('xian.bmp'); %载入图像subplot(1,3,1),imshow(I); title('原始图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I1=im2bw(I);subplot(1,3,2),imshow(I1); title('二值化图像');axis([50,250,50,200]); grid on; %显示网格线axis on; %显示坐标系I2=bwperim(I1); %获取区域的周长subplot(1,3,3),imshow(I2); title('边界周长的二值图像');axis([50,250,50,200]); grid on;axis on; 20.形态学骨架提取利用MATLAB实现如下:I=imread('xian.bmp'); subplot(2,2,1),imshow(I); title('原始图像');axis([50,250,50,200]); axis on;I1=im2bw(I);subplot(2,2,2),imshow(I1); title('二值图像');axis([50,250,50,200]); axis on; I2=bwmorph(I1,'skel',1);subplot(2,2,3),imshow(I2); title('1次骨架提取');axis([50,250,50,200]); axis on; I3=bwmorph(I1,'skel',2);subplot(2,2,4),imshow(I3); title('2次骨架提取');axis([50,250,50,200]); axis on; 21.直接提取四个顶点坐标I = imread('xian.bmp'); I = I(:,:,1);BW=im2bw(I);figureimshow(~BW)[x,y]=getpts。

btd分解算法matlab代码

btd分解算法matlab代码

btd分解算法matlab代码BTD(Binary Tree Decomposition)分解算法是一种用于图像处理和计算机视觉领域的算法,用于对图像进行分割和分解。

在MATLAB中,你可以使用以下代码来实现BTD分解算法:matlab.function [segments, tree] = btd_decomposition(image)。

% 参数设置。

minSegmentSize = 100; % 最小分割尺寸。

maxLevels = 10; % 最大分解层数。

% 初始化二叉树。

tree = binary_tree_initialize(image);% 递归分解。

tree = recursive_decomposition(tree, 1, maxLevels, minSegmentSize);% 提取分割结果。

segments = extract_segments(tree, image);function tree = binary_tree_initialize(image)。

% 创建二叉树结构。

tree = struct('level', 0, 'segment', [], 'children', []);% 初始化根节点。

tree.level = 1;tree.segment = struct('bbox', [1, 1, size(image, 2), size(image, 1)], 'meanColor', mean(image(:)), 'size',numel(image));function tree = recursive_decomposition(tree, level, maxLevels, minSegmentSize)。

% 检查是否达到最大层数或者分割尺寸。

if level >= maxLevels || tree.segment.size <= minSegmentSize.return;end.% 在当前节点进行分割。

部分图像分割的方法(matlab)

部分图像分割的方法(matlab)

大津法:function y1=OTSU(image,th_set)image=imread('color1.bmp');gray=rgb2gray(image);%原图像的灰度图low_high=stretchlim(gray);%增强图像,似乎也不是一定需要gray=imadjust(gray,low_high,[]);% subplot(224);imshow(gray);title('after adjust');count=imhist(gray);[r,t]=size(gray);n=r*t;l=256;count=count/n;%各级灰度出现的概率for i=2:lif count(i)~=0st=i-1;breakendend%以上循环语句实现寻找出现概率不为0的最小灰度值for i=l:-1:1if count(i)~=0;nd=i-1;breakendend%实现找出出现概率不为0的最大灰度值f=count(st+1:nd+1);p=st;q=nd-st;%p和分别是灰度的起始和结束值u=0;for i=1:q;u=u+f(i)*(p+i-1);ua(i)=u;end%计算图像的平均灰度值for i=1:q;w(i)=sum(f(1:i));end%计算出选择不同k的时候,A区域的概率d=(u*w-ua).^2./(w.*(1-w));%求出不同k值时类间方差[y,tp]=max(d);%求出最大方差对应的灰度级th=tp+p;if th<th_setth=tp+p;elseth=th_set; %根据具体情况适当修正门限endy1=zeros(r,t);for i=1:rfor j=1:tx1(i,j)=double(gray(i,j));endendfor i=1:rfor j=1:tif (x1(i,j)>th)y1(i,j)=x1(i,j);elsey1(i,j)=0;endendend%上面一段代码实现分割% figure,imshow(y1);% title('灰度门限分割的图像');程序二:clc; clear;cd 'D:\My Documents\MATLAB' time = now;I = imread('qr4.bmp');figure(1),imshow(I),title('p1_1.bmp'); % show the pictureI2 = rgb2gray(I);figure(2),imshow(I2),title('I2.bmp'); %ÖÐÖµÂ˲¨J = medfilt2(I2); figure(3),imshow(J);imwrite(J,'J.bmp'); [M N] = size(J);J1 = J(1:M/2,1:fix(N/2)); J2 = J(1:M/2,fix(N/2)+1:N); J3 = J(M/2+1:M, 1:fix( N/2)); J4 = J(M/2+1:M, fix(N/2)+1:N); % figure(4), img = J1;T1 = test_gray2bw( img ); % figure(5), img = J2;T2 = test_gray2bw( img ); % figure(6), img = J3;T3 = test_gray2bw( img ); % figure(7), img = J4;T4 = test_gray2bw( img ); T = [T1,T2;T3,T4]; figure,imshow(T)% T1 = edge(T,'sobel'); % figure,imshow(T1); % BW = edge(T,'sobel'); % f igure,imshow(BW);function [bw_img] = test_gray2bw( img ) %大津法[row_img col_img ] = size( img ) all_pix = row_img * col_img% get probability of each pixel(ÏñËØ). count_pix = zeros(1,256) % pro_pix = []for i = 1 : 1 : row_img for j = 1 : 1 : col_imgcount_pix(1,img(i,j)+1) = count_pix(1,img(i,j)+1) + 1 %ͳ¼Æ´ÎÊý end en dpro_pix = count_pix / all_pix% choose k value; max_kesi = -1 T = 0for k = 1 : 1 :while( i <= k )wa = wa + pro_pix(1,i+1) %Ç°k¸öi£¬Ã¿¸öÏñËصĻҶȸÅÂÊ£¬¸ÅÂÊºÍ ua = ua + i * pro_pix(1,i+1) i = i + 1 endif ( wa == 0.0 ) continue; elseua = ua / wa endub = 0 wb = 0 i = k + 1while( i <= 255 )wb = wb + pro_pix( 1 , i + 1 )ub = ub + i * pro_pix( 1 , i + 1 ) i = i + 1 endif ( wb == 0.0 ) continue; elseub = ub / wb endu = wa * ua + wb * ub% kesi = wa * ( ua - u ) * ( ua - u ) + wb * ( ub - u ) * ( ub -u ) % %ÉÏÏÂÕâÁ½¸ö¹«Ê½Êǵȼ۵Äkesi = wa * wb * (ua - ub)^2; if( kesi > max_kesi ) max_kesi = kesi T = k end end% get bw img bw_img = imgfor i = 1 : 1 : row_img for j = 1 : 1 : col_img if ( img(i,j) <= T ) bw_img(i,j) = 0elsebw_img( i,j ) = 255 end end endimwrite(bw_img,'bw_img.bmp')figure(),imshow('bw_img.bmp')%,title('bw_ing')区域生长法:close all;clear all;clc;A=dicomread('im.dcm');%读入图像(医学CT图像)% seed=[200,220];%选择起始位置thresh=6.3;%相似性选择阈值%A=rgb2gray(A0);%A=A0;%灰度化%A=imadjust(A,[min(min(double(A)))/255,max(max(double(A)))/255],[]); figure,imshow(A,[]);A=double(A); %将图像灰度化[y,x]=getpts; %获得区域生长起始点x1=round(x); %横坐标取整y1=round(y); %纵坐标取整seed=A(x1,y1);B=A;%将A赋予B[r,c]=size(B);%图像尺寸r为行数,c为列数n=r*c;%计算图像所包含点的个数pixel_seed=seed;%原图起始点灰度值q=[x1 y1];%q用来装载起始位置top=1;%循环判断flagM=zeros(r,c);%建立一个与原图形同等大小的矩阵M(x1,y1)=1;%将起始点赋为1,其余为0count=1;%计数器while top~=0%也可以写成top!=0 循环结束条件r1=q(1,1);%起始点行位置c1=q(1,2);%起始点列位置p=A(r1,c1);%起始点灰度值dge=0;for i=-1:1%周围点的循环判断for j=-1:1if r1+i<=r&r1+i>0&c1+j<=c&c1+j>0%保证在点周围范围之内if abs(A(r1+i,c1+j)-p)<=thresh&M(r1+i,c1+j)~=1%判定条件?top=top+1;%满足判定条件top加1,top为多少,则q的行数有多少行q(top,:)=[r1+i c1+j];%将满足判定条件的周围点的位置赋予q,q记载了满足判定的每一外点M(r1+i,c1+j)=1;%满足判定条件将M中相对应的点赋为1count=count+1;%统计满足判定条件的点个数,其实与top此时的值一样B(r1+i,c1+j)=1;%满足判定条件将B中相对应的点赋为1endif M(r1+i,c1+j)==0;%如果M中相对应点的值为0将dge赋为1,也是说这几个点不满足条件dge=1;%将dge赋为1endelsedge=1;%点在图像外将dge赋为1endendend%此时对周围几点判断完毕,在点在图像外或不满足判定条件则将dge赋为1,满足条件dge为0if dge~=1%最后判断的周围点(i=1,j=1)是否满足条件,如dge=0,满足。

图像分割技术的matlab实现

图像分割技术的matlab实现

f=rgb2gray(f); % 将彩色图像转换为灰度图像f=im2double(f); % 转换为双精度,便于后面的计算figure, imshow(f),title('Original Image'),PF=edge(f,'prewitt'); % 边缘探测,算子为prewitt figure,imshow(PF),title('Prewitt Filter');RF=edge(f,'roberts'); % 边缘探测,算子为roberts figure,imshow(RF),title('Roberts Filter');LF=edge(f,'log'); % 边缘探测,算子为logfigure,imshow(LF),title('Laplacian of Gaussian (LoG) Filter');CF=edge(f,'canny'); % 边缘探测,算子为canny figure,imshow(CF),title('Canny Filter');f=rgb2gray(f); % 灰度转换f=im2double(f); % 数据类型转换% 使用垂直Sobel算子,自动选择阈值[VSFAT Threshold]=edge(f,'sobel','vertical'); % 边缘探测figure, imshow(f),title('Original Image'), % 显示原始图像figure,imshow(VSFAT),title('Sobel Filter - Automatic Threshold'); % 显示边缘探测图像%使用水平和垂直Sobel算子,自动选择阈值SFST=edge(f,'sobel',Threshold);figure,imshow(SFST),title('Sobel Filter (Horizontal and Vertical)'); % 显示边缘探测图像%使用指定45度角Sobel算子滤波器,指定阈值s45=[-2 -1 0;-1 0 1;0 1 2];SFST45=imfilter(f,s45,'replicate');SFST45=SFST45>=Threshold;figure,imshow(SFST45),title('Sobel Filter (45 Degree)'); % 显示边缘探测图像%使用指定-45度角Sobel算子滤波器,指定阈值sm45=[0 1 2;-1 0 1;-2 -1 0];SFSTM45=imfilter(f,sm45,'replicate');SFSTM45=SFSTM45>=Threshold;figure,imshow(SFSTM45),title('Sobel Filter (-45 Degree)'); % 显示边缘探测图像I = imread('circuit.tif');rotI = imrotate(I,33,'crop'); % 图像旋转,该函数具体用法在本书13.3.3有介绍。

如何使用MATLAB进行图像分割处理

如何使用MATLAB进行图像分割处理

如何使用MATLAB进行图像分割处理图像分割是计算机视觉领域中的一项重要任务,它可以将图像中的不同区域分割出来,为后续的图像分析和理解提供基础。

MATLAB作为一种强大的数学计算工具和编程语言,提供了丰富的图像处理函数和工具箱,可以方便地进行图像分割处理。

本文将介绍如何使用MATLAB进行图像分割处理。

首先,我们需要加载图像。

MATLAB提供了imread函数用于读取图像文件。

例如,我们可以使用以下代码加载一张名为"image.jpg"的图像:```matlabimage = imread('image.jpg');```加载图像后,我们可以对图像进行预处理。

预处理的目的是为了减少噪声和增强图像的对比度,从而更好地进行分割。

MATLAB提供了丰富的图像预处理函数,如imresize、imadjust、imnoise等。

我们可以根据实际需求选择适当的函数进行预处理。

例如,以下代码使用imadjust函数对图像进行对比度增强:```matlabimage = imadjust(image);```接下来,我们可以选择合适的分割算法对图像进行分割。

MATLAB提供了多种图像分割算法,如阈值分割、区域生长、边缘检测等。

我们可以根据图像的特点和需求选择适合的算法。

以下是一种常用的阈值分割算法的示例代码:```matlabthreshold = graythresh(image);binaryImage = imbinarize(image, threshold);```在上述代码中,graythresh函数计算出一个合适的阈值,然后imbinarize函数将图像转化为二值图像。

通过调整阈值的大小,我们可以控制分割的精度和效果。

除了阈值分割,MATLAB还提供了更复杂的分割算法,如基于区域的分割算法。

这些算法可以根据图像中的区域特征进行分割,例如颜色、纹理、形状等。

以下是一种基于区域的分割算法的示例代码:```matlabsegmented = regiongrowing(image, seed);```在上述代码中,regiongrowing函数根据种子点对图像进行区域生长分割。

matlab图像分割程序

matlab图像分割程序

matlab图像分割程序Img = imread('t11.jpg'); % The same cell image in the paper is used hereImg=double(Img(:,:,1));sigma=1.5; % scale parameter in Gaussian kernel for smoothing.G=fspecial('gaussian',15,sigma);Img_smooth=conv2(Img,G,'same'); % smooth image by Gaussiin convolution[Ix,Iy]=gradient(Img_smooth);f=Ix.^2+Iy.^2;g=1./(1+f); % edge indicator function.epsilon=1.5; % the papramater in the definition of smoothed Dirac functiontimestep=5; % time step, try timestep=10, 20, ..., 50, ...mu=0.2/timestep; % coefficient of the internal (penalizing) energy term P(\phi)% Note: the product timestep*mu must be less than 0.25 for stability!lambda=5; % coefficient of the weighted length term Lg(\phi) alf=1.5; % coefficient of the weighted area term Ag(\phi);% Note: Choose a positive(negative) alf if the initial contour is outside(inside) the object.[nrow, ncol]=size(Img);figure;imagesc(Img, [0, 255]);colormap(gray);hold on;text(6,6,'Left click to get points, right click to get end point','FontSize',[12],'Color', 'r');% Click mouse to specify initial contour/regionBW = roipoly; % get a region R inside a polygon, BW is a binary image with 1 and 0 inside or outside the polygon;c0=4; % the constant value used to define binary level set function;initialLSF= c0*2*(0.5-BW); % initial level set function: -c0 inside R, c0 outside R;u=initialLSF;[c,h] = contour(u,[0 0],'r');u=initialLSF;figure;imagesc(Img, [0, 255]);colormap(gray);hold on;[c,h] = contour(u,[0 0],'r');title('Initial contour');% start level set evolutionfor n=1:300u=EVOLUTION(u, g ,lambda, mu, alf, epsilon, timestep, 1);if mod(n,20)==0pause(0.001);imagesc(Img, [0, 255]);colormap(gray);hold on;[c,h] = contour(u,[0 0],'r');iterNum=[num2str(n), ' iterations'];title(iterNum);hold off;endendclose ('figure 1')close ('figure 2')axes(handles.fgh);imagesc(Img, [0, 255]);colormap(gray);hold on;[c,h] = contour(u,[0 0],'r');totalIterNum=[num2str(n), ' iterations'];。

利用Matlab进行图像分割的常用方法与应用案例

利用Matlab进行图像分割的常用方法与应用案例

利用Matlab进行图像分割的常用方法与应用案例引言:图像分割是图像处理领域的一项重要技术,它将图像分割成具有相似特征的区域或像素。

图像分割在许多应用中起着关键作用,如医学图像分析、计算机视觉和机器人视觉等领域。

本文将介绍Matlab中常用的图像分割方法和应用案例。

一、基于阈值的图像分割方法基于阈值的图像分割方法是最简单和最常用的一种方法。

它根据像素的灰度值与预先设定的阈值进行比较,将图像分为前景和背景两个部分。

Matlab中提供了丰富的函数和工具箱来实现基于阈值的图像分割。

例如,可以使用im2bw函数将灰度图像转换为二值图像,代码如下:```matlabimage = imread('image.jpg');gray_image = rgb2gray(image);threshold = graythresh(gray_image);bw_image = im2bw(gray_image, threshold);imshow(bw_image);```二、基于边缘检测的图像分割方法边缘检测是图像分割中常用的一种方法,它基于图像中不同区域之间的边界。

常用的边缘检测算法有Sobel、Prewitt和Canny等。

在Matlab中,可以使用edge函数实现边缘检测,代码如下:```matlabimage = imread('image.jpg');gray_image = rgb2gray(image);edge_image = edge(gray_image, 'sobel');imshow(edge_image);```三、基于聚类分析的图像分割方法聚类分析是图像分割中一种常见的方法,它将图像中的像素分成不同的群集,每个群集代表一个区域或对象。

常用的聚类算法有K-means和Mean-shift等。

在Matlab中,可以使用kmeans函数实现K-means聚类,代码如下:```matlabimage = imread('image.jpg');feature_vector = reshape(image, [], 3);[cluster_index, cluster_center] = kmeans(double(feature_vector), 2);segmented_image = reshape(cluster_index, size(image, 1), size(image, 2));imshow(segmented_image);```四、图像分割的应用案例1. 医学图像分割医学图像分割在临床诊断和研究中具有重要意义。

matlab颜色分割代码

matlab颜色分割代码

matlab颜色分割代码在Matlab中,可以使用一些图像处理函数来实现颜色分割。

颜色分割是一种将图像分割成不同颜色区域的方法,通常用于目标检测、图像分割和识别等应用中。

首先,我们需要读取图像并将其转换为HSV色彩空间。

HSV色彩空间由色调(Hue)、饱和度(Saturation)和亮度(Value)三个分量组成,相比于RGB色彩空间,HSV能更好地表示颜色信息。

```matlabimage = imread('image.jpg');hsv_image = rgb2hsv(image);```接下来,我们可以选择一个感兴趣的颜色,并使用阈值将该颜色分割出来。

阈值是指将特定范围内的像素值设定为前景,其他像素值设定为背景。

假设我们想要分割红色区域,我们可以选择色调通道的范围为[0.9, 1]和[0, 0.1]。

```matlabhue_channel = hsv_image(:,:,1);binary_image = (hue_channel >= 0.9 | hue_channel <= 0.1); ```上述代码将创建一个二值图像,其中大于等于0.9或小于等于0.1的像素值为前景(红色区域),其他像素值为背景。

最后,我们可以通过对二值图像进行形态学操作来改善分割效果。

形态学操作主要包括腐蚀和膨胀。

```matlabse = strel('disk', 5); % 创建一个半径为5的圆形结构元素eroded_image = imerode(binary_image, se); % 腐蚀操作dilated_image = imdilate(eroded_image, se); % 膨胀操作```腐蚀操作可以去除前景中的小噪点,而膨胀操作可以填充前景中的空洞。

通过上述步骤,我们可以实现简单的颜色分割。

然而,对于复杂的图像和颜色分布,简单的阈值分割可能效果不佳。

如何进行图像分割的Matlab实现

如何进行图像分割的Matlab实现

如何进行图像分割的Matlab实现引言:图像分割是计算机视觉领域的一项基础技术,它将图像中的像素点分为不同的区域,使得具有相似特征的像素被聚类到一起。

在图像分析、目标检测、图像处理等任务中,图像分割起着至关重要的作用。

本文将介绍如何使用Matlab实现图像分割算法,包括传统的阈值分割、基于区域的分割以及基于深度学习的分割等。

一、传统的阈值分割1.1 简介阈值分割是最简单和常用的图像分割方法之一,它根据像素的灰度值与阈值的比较结果将像素分为两类:前景和背景。

在Matlab中,可以使用函数`im2bw`实现二值化分割任务。

1.2 实现步骤(1)加载图像:使用`imread`函数读取待分割的图像,并将其转换为灰度图像。

(2)确定阈值:根据图像的灰度直方图,可以通过分析波峰和波谷来确定一个适合的阈值。

(3)二值化分割:使用`im2bw`函数将灰度图像二值化,得到分割后的图像。

(4)结果显示:使用`imshow`函数将原图像和分割结果进行显示。

二、基于区域的分割2.1 简介基于区域的分割方法将图像划分为具有一定连续性和相似性质的区域,其基本思想是将图像中相似的像素组成区域,并对区域进行合并或分裂,以达到分割的目的。

2.2 实现步骤(1)加载图像:同样使用`imread`函数读取待分割的图像。

(2)图像预处理:可选的预处理步骤包括噪声去除、图像增强等,以提供更好的分割效果。

(3)区域生长:选择一个适当的种子点作为起始点,在附近的像素中根据一定的准则来判断是否属于同一区域,并逐步生长扩展区域,直至满足停止准则。

(4)结果显示:使用`imshow`函数将原图像和分割结果进行显示。

三、基于深度学习的分割3.1 简介基于深度学习的分割方法是近年来发展起来的一种高效且准确的分割技术,主要基于深度卷积神经网络(CNN)和全卷积网络(FCN)。

深度学习模型通过学习大量标注的图像,能够学习到图像的高级特征,从而实现更准确的图像分割。

matlab二值化分割代码

matlab二值化分割代码

matlab二值化分割代码
以下是一个简单的 MATLAB 代码示例,用于对图像进行二值化分割:
matlab.
% 读取图像。

img = imread('your_image.jpg');
% 将图像转换为灰度图像。

gray_img = rgb2gray(img);
% 使用Otsu方法进行图像二值化。

level = graythresh(gray_img);
bw_img = imbinarize(gray_img,level);
% 显示原始图像和二值化图像。

subplot(1,2,1), imshow(gray_img), title('Original Image');
subplot(1,2,2), imshow(bw_img), title('Binary Image');
在这个示例中,首先使用 `imread` 函数读取图像,然后使用`rgb2gray` 函数将图像转换为灰度图像。

接下来,使用
`graythresh` 函数确定阈值,并使用 `imbinarize` 函数将灰度图像转换为二值化图像。

最后,使用 `subplot` 和 `imshow` 函数显示原始图像和二值化图像。

需要注意的是,这只是一个简单的二值化分割示例。

实际应用中可能需要根据具体的图像特征和要求进行参数调整和算法优化。

FCM图像分割算法MATLAB源代码

FCM图像分割算法MATLAB源代码

FCM图像分割算法function fcmapp(file, cluster_n)% FCMAPP% fcmapp(file, cluter_n) segments a image named file using the algorithm% FCM.% [in]% file: the path of the image to be clustered.% cluster_n: the number of cluster for FCM.eval(['info=imfinfo(''',file, ''');']);switch info.ColorTypecase 'truecolor'eval(['RGB=imread(''',file, ''');']);% [X, map] = rgb2ind(RGB, 256);I = rgb2gray(RGB);clear RGB;case 'indexed'eval(['[X, map]=imread(''',file, ''');']);I = ind2gray(X, map);clear X;case 'grayscale'eval(['I=imread(''',file, ''');']);end;I = im2double(I);filename = file(1 : find(file=='.')-1);data = reshape(I, numel(I), 1);tic[center, U, obj_fcn]=fcm(data, cluster_n);elapsedtime = toc;%eval(['save(', filename, int2str(cluster_n),'.mat'', ''center'', ''U'', ''obj_fcn'', ''elapsedtime'');']); fprintf('elapsedtime = %d', elapsedtime);maxU=max(U);temp = sort(center, 'ascend');for n = 1:cluster_n;eval(['cluster',int2str(n), '_index = find(U(', int2str(n), ',:) == maxU);']);index = find(temp == center(n));switch indexcase 1color_class = 0;case cluster_ncolor_class = 255;otherwisecolor_class = fix(255*(index-1)/(cluster_n-1));endeval(['I(cluster',int2str(n), '_index(:))=', int2str(color_class),';']);end;filename = file(1:find(file=='.')-1);I = mat2gray(I);%eval(['imwrite(I,', filename,'_seg', int2str(cluster_n), '.bmp'');']);imwrite(I, 'temp\tu2_4.bmp','bmp');imview(I);function fcmapp(file, cluster_n)% FCMAPP% fcmapp(file, cluter_n) segments a image named file using the algorithm% FCM.% [in]% file: the path of the image to be clustered.% cluster_n: the number of cluster for FCM.eval(['info=imfinfo(''',file, ''');']);switch info.ColorTypecase 'truecolor'eval(['RGB=imread(''',file, ''');']);% [X, map] = rgb2ind(RGB, 256);I = rgb2gray(RGB);clear RGB;case 'indexed'eval(['[X, map]=imread(''',file, ''');']);I = ind2gray(X, map);clear X;case 'grayscale'eval(['I=imread(''',file, ''');']);end;I = im2double(I);filename = file(1 : find(file=='.')-1);data = reshape(I, numel(I), 1);tic[center, U, obj_fcn]=fcm(data, cluster_n);elapsedtime = toc;%eval(['save(', filename, int2str(cluster_n),'.mat'', ''center'', ''U'', ''obj_fcn'', ''elapsedtime'');']); fprintf('elapsedtime = %d', elapsedtime);maxU=max(U);temp = sort(center, 'ascend');for n = 1:cluster_n;eval(['cluster',int2str(n), '_index = find(U(', int2str(n), ',:) == maxU);']);index = find(temp == center(n));switch indexcase 1color_class = 0;case cluster_ncolor_class = 255;otherwisecolor_class = fix(255*(index-1)/(cluster_n-1));endeval(['I(cluster',int2str(n), '_index(:))=', int2str(color_class),';']); end;filename = file(1:find(file=='.')-1);I = mat2gray(I);%eval(['imwrite(I,', filename,'_seg', int2str(cluster_n), '.bmp'');']); imwrite(I, 'r.bmp');imview(I);主程序1ImageDir='.\';%directory containing the images%path('..') ;%cmpviapath('..') ;img=im2double(imresize(imread([ImageDir '12.png']),2)) ;figure(1) ; imagesc(img) ; axis image[ny,nx,nc]=size(img) ;imgc=applycform(img,makecform('srgb2lab')) ;d=reshape(imgc(:,:,2:3),ny*nx,2) ;d(:,1)=d(:,1)/max(d(:,1)) ; d(:,2)=d(:,2)/max(d(:,2)) ;%d=d ./ (repmat(sqrt(sum(d.^2,2)),1,3)+eps()) ;k=4 ; % number of clusters%[l0 c] = kmeans(d, k,'Display','iter','Maxiter',100);[l0 c] = kmeans(d, k,'Maxiter',100);l0=reshape(l0,ny,nx) ;figure(2) ; imagesc(l0) ; axis image ;%c=[ 0.37 0.37 0.37 ; 0.77 0.73 0.66 ; 0.64 0.77 0.41 ; 0.81 0.76 0.58 ; ...%0.85 0.81 0.73 ] ;%c=[0.99 0.76 0.15 ; 0.55 0.56 0.15 ] ;%c=[ 0.64 0.64 0.67 ; 0.27 0.45 0.14 ] ;%c=c ./ (repmat(sqrt(sum(c.^2,2)),1,3)+eps()) ;% Data termDc=zeros(ny,nx,k) ;for i=1:k,dif=d-repmat(c(i,:),ny*nx,1) ;Dc(:,:,i)= reshape(sum(dif.^2,2),ny,nx) ;end ;% Smoothness termSc=(ones(k)-eye(k)) ;% Edge termsg = fspecial('gauss', [13 13], 2);dy = fspecial('sobel');vf = conv2(g, dy, 'valid');Vc = zeros(ny,nx);Hc = Vc;for b=1:nc,Vc = max(Vc, abs(imfilter(img(:,:,b), vf, 'symmetric')));Hc = max(Hc, abs(imfilter(img(:,:,b), vf', 'symmetric'))); endgch=char;gch = GraphCut('open', 1*Dc, Sc,exp(-5*Vc),exp(-5*Hc)); [gch l] = GraphCut('expand',gch);gch = GraphCut('close', gch);label=l(100,200) ;lb=(l==label) ;lb=imdilate(lb,strel('disk',1))-lb ;figure(3) ; image(img) ; axis image ; hold on ;contour(lb,[1 1],'r') ; hold off ; title('no edges') ;figure(4) ; imagesc(l) ; axis image ; title('no edges') ;gch = GraphCut('open', Dc, 5*Sc,exp(-10*Vc),exp(-10*Hc)); [gch l] = GraphCut('expand',gch);gch = GraphCut('close', gch);lb=(l==label) ;lb=imdilate(lb,strel('disk',1))-lb ;figure(5) ; image(img) ; axis image ; hold on ;contour(lb,[1 1],'r') ; hold off ; title('edges') ;figure(6) ; imagesc(l) ; axis image ; title('edges') ;主程序2I = imread( '12.png' );I = rgb2gray(I);subplot(5,3,1),imshow(I);k=medfilt2(I,[5,5]);subplot(5,3,2),imshow(k);title('5*5中值滤波图像');%f=imread('tuxiang1.tif');%subplot(1,2,1),imshow(f);%title('原图像');g1=histeq(k,256);subplot(5,3,3),imshow(g1);title('直方图匹配');%g2=histeq(k2,256);%subplot(2,2,2),imshow(g2);%title('5*5直方图匹配');%k=medfilt2(f,[5,5]);%k2=medfilt2(f,[5,5]);%j=imnoise(f,'gaussian',0,0.005);%subplot(1,3,3),imshow(k2);%title('5*5中值滤波图像');hy = fspecial( 'sobel' );hx = hy;Iy = imfilter(double(g1), hy, 'replicate' );Ix = imfilter(double(g1), hx, 'replicate' );gradmag = sqrt(Ix.^2 + Iy.^2);subplot(5,3,4), imshow(gradmag,[ ]), title( 'gradmag' );L = watershed(gradmag);Lrgb = label2rgb(L);subplot(5,3,5), imshow(Lrgb), title( 'Lrgb' );se = strel( 'disk' , 9);Io = imopen(g1, se);subplot(5,3,6), imshow(Io), title( 'Io' )Ie = imerode(g1, se);Iobr = imreconstruct(Ie, g1);subplot(5,3,7), imshow(Iobr), title( 'Iobr' );Ioc = imclose(Io, se);subplot(5,3,8), imshow(Ioc), title( 'Ioc' );Iobrd = imdilate(Iobr, se);Iobrcbr = imreconstruct(imcomplement(Iobrd), imcomplement(Iobr)); Iobrcbr = imcomplement(Iobrcbr);subplot(5,3,9), imshow(Iobrcbr), title( 'Iobrcbr' );fgm = imregionalmax(Iobrcbr);subplot(5,3,10), imshow(fgm), title( 'fgm' );I2 = g1; I2(fgm) = 255;subplot(5,3,11),imshow(I2), title( 'fgm superimposed on original image' );se2 = strel(ones(5,5)); I3 = g1; I3(fgm) = 255;subplot(5,3,12) ,imshow(I3);title( 'fgm4 superimposed on original image' );bw = im2bw(Iobrcbr, graythresh(Iobrcbr));subplot(5,3,13) , imshow(bw), title( 'bw' );D = bwdist(bw); DL = watershed(D);bgm = DL == 0;subplot(5,3,14) , imshow(bgm), title( 'bgm' );gradmag2 = imimposemin(gradmag, bgm | fgm);L = watershed(gradmag2);I4 = g1;I4(imdilate(L == 0, ones(3, 3)) | bgm | fgm) = 255;figure, imshow(I4);title( 'Markers and object boundaries superimposed on original image' ); Lrgb = label2rgb(L, 'jet' , 'w' , 'shuffle' );figure, imshow(Lrgb);title( 'Lrgb' );figure, imshow(I), hold onhimage = imshow(Lrgb);set(himage, 'AlphaData' , 0.3);title( 'Lrgb superimposed transparently on original image' );。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

[matlab图像处理]阈值分割%迭代式阈值分割?otsu阈值分割?二值化closeall;%关闭所有窗口
clear;%清除变量的状态数据
clc;%清除命令行
I=imread('rice.png');
subplot(2,2,1);
imshow(I);
title('1rice的原图');
%迭代式阈值分割?
zmax=max(max(I));%取出最大灰度值
zmin=min(min(I));%取出最小灰度值
tk=(zmax+zmin)/2;
bcal=1;
[m,n]=size(I);
while(bcal)
???%定义前景和背景数
???iforeground=0;
???ibackground=0;
???%定义前景和背景灰度总和
???foregroundsum=0;
???backgroundsum=0;
???fori=1:m
???????forj=1:n
???????????tmp=I(i,j);
???????????if(tmp>=tk)
???????????????%前景灰度值???????????????iforeground=iforeground+1; ???????????????foregroundsum=foregroundsum+double(tmp); ???????????else
???????????????ibackground=ibackground+1; ???????????????backgroundsum=backgroundsum+double(tmp); ???????????end
???????end
???end
???%计算前景和背景的平均值
???z1=foregroundsum/iforeground;
???z2=foregroundsum/ibackground;
???tktmp=uint8((z1+z2)/2);
???if(tktmp==tk)
???????bcal=0;
???else
???????tk=tktmp;
???end
???%当阈值不再变化时,说明迭代结束
end
disp(strcat('迭代的阈值:',num2str(tk)));%在commandwindow里显示出:迭代的阈值:阈值
newI=im2bw(I,double(tk)/255);%函数im2bw使用阈值(threshold)变换法把灰度图像(grayscaleimage)
????%转换成二值图像。

所谓二值图像,一般意义上是指只有纯黑(0)、纯白(255)两种颜色的图像。

????%语法
???%BW=im2bw(I,level)
???%BW=im2bw(X,map,level)
???%BW=im2bw(RGB,level)
???%其中level就是设置阈值的。

level取值范围[0,1]。

subplot(2,2,2);
imshow(newI);
title('2rice的迭代法分割效果图');
%otsu阈值分割
bw=graythresh(I);
disp(strcat('otsu阈值分割的阈值:',num2str(bw*255)));%在commandwindow里显示出:迭代的阈值:阈值
newII=im2bw(I,bw);
subplot(2,2,3);
imshow(newII);
title('3rice的otsu阈值分割');
%二值化阈值为135
[width,height,bmsize]=size(I); fori=1:width
???forj=1:height ???????ifI(i,j)>135 ???????????I(i,j)=255; ???????else? ???????????I(i,j)=0; ???????end
???end
end???
subplot(2,2,4);
imshow(I);
title('4rice的二值阈值分割');。

相关文档
最新文档