⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gc_example.m

📁 Graph Cut algorithm implementation. Includes MATLAB compiled codes.
💻 M
字号:
function gc_example()% An example of how to segment a color image according to pixel colors.% Fisrt stage identifies k distinct clusters in the color space of the% image. Then the image is segmented according to these regions; each pixel% is assigned to its cluster and the GraphCut poses smoothness constraint% on this labeling.close all% read an imageim = im2double(imread('outdoor_small.jpg'));im = im2double(imread('C:\Documents and Settings\Mahalingam\Desktop\FACE DETECTION\pic.jpg'));sz = size(im);% try to segment the image into k different regionsk = 4;% color space distancedistance = 'sqEuclidean';% cluster the image colors into k regionsdata = ToVector(im);[idx c] = kmeans(data, k, 'distance', distance,'maxiter',200);% calculate the data cost per cluster centerDc = zeros([sz(1:2) k],'single');for ci=1:k    % use covariance matrix per cluster    icv = inv(cov(data(idx==ci,:)));        dif = data - repmat(c(ci,:), [size(data,1) 1]);    % data cost is minus log likelihood of the pixel to belong to each    % cluster according to its RGB value    Dc(:,:,ci) = reshape(sum((dif*icv).*dif./2,2),sz(1:2));end% cut the graph% smoothness term: % constant partSc = ones(k) - eye(k);% spatialy varying part% [Hc Vc] = gradient(imfilter(rgb2gray(im),fspecial('gauss',[3 3]),'symmetric'));[Hc Vc] = SpatialCues(im);gch = GraphCut('open', Dc, 10*Sc, exp(-Vc*5), exp(-Hc*5));[gch L] = GraphCut('expand',gch);gch = GraphCut('close', gch);% show resultsimshow(im);hold on;PlotLabels(L);%---------------- Aux Functions ----------------%function v = ToVector(im)% takes MxNx3 picture and returns (MN)x3 vectorsz = size(im);v = reshape(im, [prod(sz(1:2)) 3]);%-----------------------------------------------%function ih = PlotLabels(L)L = single(L);bL = imdilate( abs( imfilter(L, fspecial('log'), 'symmetric') ) > 0.1, strel('disk', 1));LL = zeros(size(L),class(L));LL(bL) = L(bL);Am = zeros(size(L));Am(bL) = .5;ih = imagesc(LL); set(ih, 'AlphaData', Am);colorbar;colormap 'jet';%-----------------------------------------------%function [hC vC] = SpatialCues(im)g = fspecial('gauss', [13 13], sqrt(13));dy = fspecial('sobel');vf = conv2(g, dy, 'valid');sz = size(im);vC = zeros(sz(1:2));hC = vC;for b=1:size(im,3)    vC = max(vC, abs(imfilter(im(:,:,b), vf, 'symmetric')));    hC = max(hC, abs(imfilter(im(:,:,b), vf', 'symmetric')));end

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -