├── AffinityBasedMattingToolbox-master ├── KNNMatting.m ├── LICENSE ├── Training4.png ├── Training4Trimap.png ├── abmtSetup.m ├── affinity │ ├── colorMixtureAffinities.m │ ├── colorSimilarityAffinities.m │ ├── knownToUnknownColorMixture.m │ └── mattingAffinity.m ├── closedFormMatting.m ├── common │ ├── affinityMatrixToLaplacian.m │ ├── detectHighlyTransparent.m │ ├── findNonlocalNeighbors.m │ ├── getMattingParams.m │ ├── localLinearEmbedding.m │ ├── localRGBnormalDistributions.m │ └── solveForAlphas.m ├── demo.m ├── informationFlowMatteRefinement.m ├── informationFlowMatting.m ├── readme.md ├── sharedMattingMatteRefinement.m └── trimming │ ├── patchBasedTrimming.m │ └── trimmingFromKnownUnknownEdges.m ├── BayesianMatting ├── app.fig ├── app.m ├── bayesmat.m ├── cluster_OrachardBouman.asv ├── cluster_OrachardBouman.m ├── getTrimap.m ├── images │ ├── bag │ │ ├── plasticbag.png │ │ └── trimap.png │ ├── bear │ │ ├── Thumbs.db │ │ ├── background.jpg │ │ ├── input.jpg │ │ └── trimap.png │ ├── dog │ │ ├── Thumbs.db │ │ ├── background.png │ │ ├── input.jpg │ │ └── trimap.png │ ├── gandalf │ │ ├── Thumbs.db │ │ ├── background-small.png │ │ ├── background.jpg │ │ ├── input-small.png │ │ ├── mytrimap.png │ │ └── trimap.png │ ├── knockout │ │ ├── background.png │ │ ├── input.png │ │ └── trimap.png │ ├── lighthouse │ │ ├── background.png │ │ ├── input.png │ │ └── trimap.png │ ├── me │ │ ├── background.png │ │ ├── cheng.jpg │ │ ├── input.jpg │ │ └── trimap.png │ ├── net │ │ ├── alpha.png │ │ ├── bayesian.mat │ │ ├── net.png │ │ ├── pineapple.png │ │ ├── trimap.png │ │ └── troll.png │ └── woman │ │ ├── Thumbs.db │ │ ├── background.png │ │ ├── compose.jpg │ │ ├── input.png │ │ └── trimap.png ├── makeComposite.m ├── makeParameters.m ├── progressbar.m ├── script.m ├── solve.m └── woman.mat ├── FCM ├── 3096.jpg ├── distfcm.m ├── fcm.m ├── fcm_stepfcm.m └── main_fcm.m ├── FRFCM_Leitao ├── 2018TFS_FRFCM.pdf ├── 3096.jpg ├── FRFCM.m ├── FRFCM_c.m ├── Label_image.m ├── PCA_color.m ├── Readme.txt ├── VOI_h.m ├── V_pcpe.m ├── centerMVP.m ├── colorspace.m ├── fcm_image.m ├── fcm_image_color.m ├── main_color.m ├── main_gray.m ├── renumber.m ├── w_ColorRecons_CO.m └── w_recons_CO.m ├── IFCM ├── 1.tiff ├── 124084.jpg ├── 2..tiff ├── 3.1..tiff ├── 3096.jpg ├── distifcmMVP.m ├── ifcm.m ├── ifcm_step.m ├── initifcmmvp.m ├── initifcmv.m └── main_IFCM.m ├── IFFCM ├── 1.1.tiff ├── 1.2.tiff ├── 3.tiff ├── 3096.jpg ├── compute_mean_median.m ├── datahistprocess.m ├── distffcm.m ├── iffcm.m ├── iffcm_step.m ├── initifcmv.m ├── main_FFCM.m └── u_return.m ├── JSEG ├── 124084.jpg ├── Borsotti.m ├── DrawLine.m ├── EVisible.m ├── Evaluation.m ├── Fratio.m ├── GenerateWindow.m ├── JAverage.m ├── JCalculation.m ├── JImage.m ├── LiuYang.m ├── PNN_fast.m ├── PNN_fast_RGBo.m ├── QuantizedC.m ├── RegionMerge.m ├── RegionMerge_RGB.m ├── SeedGrowing.m ├── SegEval.m ├── SpatialSeg.m ├── ValleyD.m ├── ValleyG1.m ├── ValleyG2.m ├── build_heap.m ├── class2Img.m ├── heap_add.m ├── heap_pop.m ├── jseg.fig ├── jseg.m ├── kmeansO.m ├── script.m ├── sqdist.m └── ssim_index.m ├── Kmeans ├── 3096.jpg └── Main_Kmeans.m ├── Otsu全局阈值处理 ├── 3096.jpg └── main_OTSU_local.m ├── README.md ├── SegbyEntrory ├── 3096.jpg ├── Main_Seg.m └── Myfun.m ├── WOA ├── Get_Functions_details.m ├── WOA.m ├── WOA.pdf ├── WOA.png ├── func_plot.m ├── initialization.m └── main.m ├── otsu ├── 3096.jpg └── Otsu_Test.m └── 分水岭阈值分割 ├── watershed_Test2.m └── watershed_demo.m /AffinityBasedMattingToolbox-master/KNNMatting.m: -------------------------------------------------------------------------------- 1 | 2 | % KNN Matting 3 | % This function implements the image matting approach described in 4 | % Qifeng Chen, Dingzeyu Li, Chi-Keung Tang, "KNN Matting", IEEE 5 | % TPAMI, 2013. 6 | % Optional input parameter 'params' can be customized by editing the 7 | % values in the struct returned by 'getMattingParams('CF'). 8 | % - knn_K defines the number of nonlocal neighbors 9 | % - knn_xyw defines the weight of the spatial coordinates in KNN search 10 | % - knn_hsv defines the color space (RGB or HSV) for KNN search 11 | 12 | function alpha = KNNMatting(image, trimap, params, suppressMessages) 13 | abmtSetup 14 | tic; 15 | if ~exist('params', 'var') || isempty(params) 16 | params = getMattingParams('KNN'); 17 | end 18 | if ~exist('suppressMessages', 'var') || isempty(suppressMessages) 19 | suppressMessages = false; 20 | end 21 | if(~suppressMessages) display('KNN Matting started...'); end 22 | 23 | image = im2double(image); 24 | trimap = im2double(trimap(:,:,1)); 25 | 26 | % Compute KNN affinities 27 | unk = trimap < 0.8 & trimap > 0.2; 28 | dilUnk = imdilate(unk, ones(3, 3)); 29 | if(~suppressMessages) display(' Computing KNN affinities...'); end 30 | Lap = affinityMatrixToLaplacian(colorSimilarityAffinities(image, params.knn_K, [], [], params.knn_xyw, params.knn_hsv)); 31 | 32 | if(~suppressMessages) display(' Solving for alphas...'); end 33 | alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve); 34 | 35 | alpha = reshape(alpha, [size(image, 1), size(image, 2)]); 36 | 37 | dur = toc; 38 | if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end 39 | end 40 | -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017, Yagiz Aksoy. All rights reserved. 2 | 3 | This software is for academic use only. A redistribution of this 4 | software, with or without modifications, has to be for academic 5 | use only, while giving the appropriate credit to the original 6 | authors of the software. The methods implemented as a part of 7 | this software may be covered under patents or patent applications. 8 | 9 | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED 10 | WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 11 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR 12 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 13 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 14 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 15 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 16 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 17 | ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/Training4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/AffinityBasedMattingToolbox-master/Training4.png -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/Training4Trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/AffinityBasedMattingToolbox-master/Training4Trimap.png -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/abmtSetup.m: -------------------------------------------------------------------------------- 1 | % Yagiz Aksoy 2 | % 2017 3 | 4 | tbloc = fileparts(mfilename('fullpath')); 5 | addpath(fullfile(tbloc, 'affinity')); 6 | addpath(fullfile(tbloc, 'trimming')); 7 | addpath(fullfile(tbloc, 'common')); 8 | clear tbloc; -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/affinity/colorMixtureAffinities.m: -------------------------------------------------------------------------------- 1 | 2 | % Color Mixture Non-local Pixel Affinities 3 | % This function implements the color-mixture information flow in 4 | % Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, "Designing Effective 5 | % Inter-Pixel Information Flow for Natural Image Matting", CVPR, 2017 6 | % when the input parameter 'useXYinLLEcomp' is false (default), and 7 | % the affinity definition used in 8 | % Xiaowu Chen, Dongqing Zou, Qinping Zhao, Ping Tan, "Manifold 9 | % preserving edit propagation", ACM TOG, 2012 10 | % when 'useXYinLLEcomp' is true. 11 | % All parameters other than image are optional. The output is a sparse 12 | % matrix which has non-zero element for the non-local neighbors of 13 | % the pixels given by binary map inMap. 14 | % - K defines the number of neighbors from which LLE weights are 15 | % computed. 16 | % - outMap is a binary map that defines where the nearest neighbor 17 | % search is done. 18 | % - xyWeight determines how much importance is given to the spatial 19 | % coordinates in the nearest neighbor selection. 20 | 21 | function Wcm = colorMixtureAffinities(image, K, inMap, outMap, xyWeight, useXYinLLEcomp) 22 | 23 | [h, w, ~] = size(image); 24 | N = h * w; 25 | 26 | if ~exist('K', 'var') || isempty(K) 27 | K = 20; 28 | end 29 | if ~exist('inMap', 'var') || isempty(inMap) 30 | inMap = true(h, w); 31 | end 32 | if ~exist('outMap', 'var') || isempty(outMap) 33 | outMap = true(h, w); 34 | end 35 | if ~exist('xyWeight', 'var') || isempty(xyWeight) 36 | xyWeight = 1; 37 | end 38 | if ~exist('useXYinLLEcomp', 'var') || isempty(useXYinLLEcomp) 39 | useXYinLLEcomp = false; 40 | end 41 | 42 | [inInd, neighInd, features] = findNonlocalNeighbors(image, K, xyWeight, inMap, outMap); 43 | 44 | if ~useXYinLLEcomp 45 | features = features(:, 1 : end - 2); 46 | end 47 | flows = zeros(size(inInd, 1), size(neighInd, 2)); 48 | 49 | for i = 1 : size(inInd, 1) 50 | flows(i, :) = localLinearEmbedding(features(inInd(i), :)', features(neighInd(i, :), :)', 1e-10); 51 | end 52 | flows = flows ./ repmat(sum(flows, 2), [1, K]); 53 | 54 | inInd = repmat(inInd, [1, K]); 55 | Wcm = sparse(inInd(:), neighInd(:), flows, N, N); 56 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/affinity/colorSimilarityAffinities.m: -------------------------------------------------------------------------------- 1 | 2 | % Color Similarity Non-local Pixel Affinities 3 | % This function implements the affinity based on color differences 4 | % first used for image matting in the paper 5 | % Qifeng Chen, Dingzeyu Li, Chi-Keung Tang, "KNN Matting", IEEE 6 | % TPAMI, 2013. 7 | % All parameters other than image are optional. The output is a sparse 8 | % matrix which has non-zero element for the non-local neighbors of 9 | % the pixels given by binary map inMap. 10 | % - K defines the number of neighbors from which LLE weights are 11 | % computed. 12 | % - outMap is a binary map that defines where the nearest neighbor 13 | % search is done. 14 | % - xyWeight determines how much importance is given to the spatial 15 | % coordinates in the nearest neighbor selection. 16 | % - When useHSV is false (default), the search is done i [r g b x y] space, 17 | % otherwise the feature space is [cos(h) sin(h), s, v, x, y]. 18 | 19 | function Wcs = colorSimilarityAffinities(image, K, inMap, outMap, xyWeight, useHSV) 20 | 21 | [h, w, ~] = size(image); 22 | N = h * w; 23 | 24 | if ~exist('K', 'var') || isempty(K) 25 | K = 5; 26 | end 27 | if ~exist('inMap', 'var') || isempty(inMap) 28 | inMap = true(h, w); 29 | end 30 | if ~exist('outMap', 'var') || isempty(outMap) 31 | outMap = true(h, w); 32 | end 33 | if ~exist('xyWeight', 'var') || isempty(xyWeight) 34 | xyWeight = 0.05; 35 | end 36 | if ~exist('useHSV', 'var') || isempty(useHSV) 37 | useHSV = false; 38 | end 39 | 40 | if useHSV 41 | image = rgb2hsv(image); 42 | image = cat(3, cos(image(:, :, 1)) * 2 * pi, sin(image(:, :, 1)) * 2 * pi, image(:,:,2:3)); 43 | end 44 | 45 | [~, neighInd, ~] = findNonlocalNeighbors(image, K, xyWeight, inMap, outMap); 46 | 47 | % This behaviour below, decreasing the xy-weight and finding a new set of neighbors, is taken 48 | % from the public implementation of KNN matting by Chen et al. 49 | [inInd, neighInd2, features] = findNonlocalNeighbors(image, ceil(K / 5), xyWeight / 100, inMap, outMap); 50 | neighInd = [neighInd, neighInd2]; 51 | features(:, end-1 : end) = features(:, end-1 : end) / 100; 52 | 53 | inInd = repmat(inInd, [1, size(neighInd, 2)]); 54 | flows = max(1 - sum(abs(features(inInd(:), :) - features(neighInd(:), :)), 2) / size(features, 2), 0); 55 | 56 | Wcs = sparse(inInd(:), neighInd(:), flows, N, N); 57 | Wcs = (Wcs + Wcs') / 2; % If p is a neighbor of q, make q a neighbor of p 58 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/affinity/knownToUnknownColorMixture.m: -------------------------------------------------------------------------------- 1 | 2 | % Known-to-Unknown Information Flow 3 | % This function implements the known-to-unknown information flow in 4 | % Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, "Designing Effective 5 | % Inter-Pixel Information Flow for Natural Image Matting", CVPR, 2017. 6 | % All parameters other than image and the trimap are optional. The outputs 7 | % are the weight of FG pixels inside the unknown region, and the confidence 8 | % on these estimated values. 9 | % - K defines the number of neighbors found in FG and BG from which 10 | % LLE weights are computed. 11 | % - xyWeight determines how much importance is given to the spatial 12 | % coordinates in the nearest neighbor selection. 13 | 14 | function [alphaEst, conf] = knownToUnknownColorMixture(image, trimap, K, xyWeight) 15 | 16 | if ~exist('K', 'var') || isempty(K) 17 | K = 7; 18 | end 19 | if ~exist('xyWeight', 'var') || isempty(xyWeight) 20 | xyWeight = 10; 21 | end 22 | 23 | image= im2double(image); 24 | trimap = im2double(trimap(:,:,1)); 25 | bg = trimap < 0.2; 26 | fg = trimap > 0.8; 27 | unk = ~(bg | fg); 28 | 29 | % Find neighbors of unknown pixels in FG and BG 30 | [inInd, bgInd, features] = findNonlocalNeighbors(image, K, xyWeight, unk, bg); 31 | [~, fgInd] = findNonlocalNeighbors(image, K, xyWeight, unk, fg); 32 | neighInd = [fgInd, bgInd]; 33 | 34 | % Compute LLE weights and estimate FG and BG colors that got into the mixture 35 | features = features(:, 1 : end - 2); 36 | flows = zeros(size(inInd, 1), size(neighInd, 2)); 37 | fgCols = zeros(size(inInd, 1), 3); 38 | bgCols = zeros(size(inInd, 1), 3); 39 | for i = 1 : size(inInd, 1) 40 | flows(i, :) = localLinearEmbedding(features(inInd(i), :)', features(neighInd(i, :), :)', 1e-10); 41 | fgCols(i, :) = sum(features(neighInd(i, 1 : K), :) .* repmat(flows(i, 1 : K)', [1 3]), 1); 42 | bgCols(i, :) = sum(features(neighInd(i, K + 1 : end), :) .* repmat(flows(i, K + 1 : end)', [1 3]), 1); 43 | end 44 | 45 | % Estimated alpha is the sum of weights of FG neighbors 46 | alphaEst = trimap; 47 | alphaEst(unk) = sum(flows(:, 1 : K), 2); 48 | 49 | % Compute the confidence based on FG - BG color difference 50 | unConf = fgCols - bgCols; 51 | unConf = sum(unConf .* unConf, 2) / 3; 52 | conf = double(fg | bg); 53 | conf(unk) = unConf; 54 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/affinity/mattingAffinity.m: -------------------------------------------------------------------------------- 1 | 2 | % Matting Affinity 3 | % This function implements the image matting approach described in 4 | % Anat Levin, Dani Lischinski, Yair Weiss, "A Closed Form Solution to 5 | % Natural Image Matting", IEEE TPAMI, 2008. 6 | % All parameters other than image are optional. The output is a sparse 7 | % matrix which has non-zero element for the non-local neighbors of 8 | % the pixels given by binary map inMap. 9 | % - windowRadius defines the size of the window where the local normal 10 | % distributions are estimated. 11 | % - epsilon defines the regularization coefficient used before inverting 12 | % covariance matrices. It should be larger for noisy images. 13 | 14 | function W = mattingAffinity(image, inMap, windowRadius, epsilon) 15 | 16 | if ~exist('windowRadius', 'var') || isempty(windowRadius) 17 | windowRadius = 1; 18 | end 19 | if ~exist('epsilon', 'var') || isempty(epsilon) 20 | epsilon = 1e-7; 21 | end 22 | 23 | windowSize = 2 * windowRadius + 1; 24 | neighSize = windowSize^2; 25 | [h, w, c] = size(image); 26 | N = h * w; 27 | epsilon = epsilon / neighSize; 28 | 29 | % No need to compute affinities in known regions if a trimap is defined 30 | if nargin < 2 || isempty(inMap) 31 | inMap = true(size(image, 1), size(image, 2)); 32 | end 33 | 34 | [meanImage, covarMat] = localRGBnormalDistributions(image, windowRadius, epsilon); 35 | 36 | % Determine pixels and their local neighbors 37 | indices = reshape((1 : h * w), [h w]); 38 | neighInd = im2col(indices, [windowSize windowSize], 'sliding')'; 39 | inMap = inMap(windowRadius + 1 : end - windowRadius, windowRadius + 1 : end - windowRadius); 40 | neighInd = neighInd(inMap, :); 41 | inInd = neighInd(:, (neighSize + 1) / 2); 42 | pixCnt = size(inInd, 1); 43 | 44 | % Prepare in & out data 45 | image = reshape(image, [N, c]); 46 | meanImage = reshape(meanImage, [N, c]); 47 | flowRows = zeros(neighSize, neighSize, pixCnt); 48 | flowCols = zeros(neighSize, neighSize, pixCnt); 49 | flows = zeros(neighSize, neighSize, pixCnt); 50 | 51 | % Compute matting affinity 52 | for i = 1 : size(inInd, 1) 53 | neighs = neighInd(i, :); 54 | shiftedWinColors = image(neighs, :) - repmat(meanImage(inInd(i), :), [size(neighs, 2), 1]); 55 | flows(:, :, i) = shiftedWinColors * (covarMat(:, :, inInd(i)) \ shiftedWinColors'); 56 | neighs = repmat(neighs, [size(neighs, 2), 1]); 57 | flowRows(:, :, i) = neighs; 58 | flowCols(:, :, i) = neighs'; 59 | end 60 | flows = (flows + 1) / neighSize; 61 | W = sparse(flowRows(:), flowCols(:), flows(:), N, N); 62 | 63 | % Make sure it's symmetric 64 | W = W + W'; 65 | 66 | % Normalize 67 | sumW = full(sum(W, 2)); 68 | sumW(sumW < 0.05) = 1; 69 | W = spdiags(1 ./ sumW(:), 0, N, N) * W; 70 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/closedFormMatting.m: -------------------------------------------------------------------------------- 1 | 2 | % Closed-Form Matting 3 | % This function implements the image matting approach described in 4 | % Anat Levin, Dani Lischinski, Yair Weiss, "A Closed Form Solution to 5 | % Natural Image Matting", IEEE TPAMI, 2008. 6 | % Optional input parameter 'params' can be customized by editing the 7 | % default values in the struct returned by 'getMattingParams('CF'). 8 | % - loc_*** define the parameters for the matting Laplacian. 9 | 10 | function alpha = closedFormMatting(image, trimap, params, suppressMessages) 11 | abmtSetup 12 | tic; 13 | if ~exist('params', 'var') || isempty(params) 14 | params = getMattingParams('CF'); 15 | end 16 | if ~exist('suppressMessages', 'var') || isempty(suppressMessages) 17 | suppressMessages = false; 18 | end 19 | if(~suppressMessages) display('Closed-Form Matting started...'); end 20 | 21 | image = im2double(image); 22 | trimap = im2double(trimap(:,:,1)); 23 | 24 | % Compute matting Laplacian 25 | unk = trimap < 0.8 & trimap > 0.2; 26 | dilUnk = imdilate(unk, ones(2 * params.loc_win + 1)); 27 | if(~suppressMessages) display(' Computing matting Laplacian...'); end 28 | Lap = affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps)); 29 | 30 | if(~suppressMessages) display(' Solving for alphas...'); end 31 | alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve); 32 | 33 | alpha = reshape(alpha, [size(image, 1), size(image, 2)]); 34 | 35 | dur = toc; 36 | if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end 37 | end 38 | -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/common/affinityMatrixToLaplacian.m: -------------------------------------------------------------------------------- 1 | 2 | function Lap = affinityMatrixToLaplacian(aff) 3 | N = size(aff, 1); 4 | Lap = spdiags(sum(aff, 2), 0 , N, N) - aff; 5 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/common/detectHighlyTransparent.m: -------------------------------------------------------------------------------- 1 | 2 | % Detect if the expected matte is a highly-transparent one 3 | % This function implements the energy selection method described in 4 | % Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, "Designing Effective 5 | % Inter-Pixel Information Flow for Natural Image Matting", CVPR, 2017. 6 | % This is a very simple histogram-based classifier. 7 | 8 | function ht = detectHighlyTransparent(image, trimap) 9 | 10 | image = reshape(im2double(image), [size(image, 1) * size(image, 2), 3]); 11 | trimap = im2double(trimap(:,:,1)); 12 | 13 | fg = trimap > 0.8; 14 | bg = trimap < 0.2; 15 | unk = ~(fg | bg); 16 | fg = fg & imdilate(unk, ones(20)); 17 | bg = bg & imdilate(unk, ones(20)); 18 | 19 | fgi = image(fg, :); 20 | bgi = image(bg, :); 21 | uni = image(unk, :); 22 | 23 | fgh = [imhist(fgi(:, 1), 10); imhist(fgi(:, 3), 10); imhist(fgi(:, 3), 10);] / sum(fg(:)); 24 | bgh = [imhist(bgi(:, 1), 10); imhist(bgi(:, 3), 10); imhist(bgi(:, 3), 10);] / sum(bg(:)); 25 | unh = [imhist(uni(:, 1), 10); imhist(uni(:, 3), 10); imhist(uni(:, 3), 10);] / sum(unk(:)); 26 | 27 | weights = ([fgh bgh]' * [fgh bgh]) \ ([fgh bgh]' * unh); 28 | recError = [fgh bgh] * weights - unh; 29 | recError = sqrt(sum(recError(:) .* recError(:))) / size(recError(:), 1); 30 | 31 | ht = recError > 0.0099; 32 | 33 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/common/findNonlocalNeighbors.m: -------------------------------------------------------------------------------- 1 | 2 | % Find neighbors using the pixel colors and spatial ccordinates 3 | % - K is the number of neighbors to be found 4 | % - Parameters other than K and image are optional. 5 | % - xyWeight sets the relative importance of spatial coordinates 6 | % - inMap and outMap are binary maps determining the query and 7 | % search regions 8 | % - Self matches are detected and removed if eraseSelfMatches is true 9 | % - inInd and neighInd give pixel indices of query pixels and their neighbors. 10 | % - features is noOfPixels X dimensions matrix used in neighbor search. 11 | 12 | function [inInd, neighInd, features] = findNonlocalNeighbors(image, K, xyWeight, inMap, outMap, eraseSelfMatches) 13 | 14 | [h, w, c] = size(image); 15 | 16 | if ~exist('xyWeight', 'var') || isempty(xyWeight) 17 | xyWeight = 1; 18 | end 19 | if ~exist('inMap', 'var') || isempty(inMap) 20 | inMap = true(h, w); 21 | end 22 | if ~exist('outMap', 'var') || isempty(outMap) 23 | outMap = true(h, w); 24 | end 25 | if ~exist('eraseSelfMatches', 'var') || isempty(eraseSelfMatches) 26 | eraseSelfMatches = true; 27 | end 28 | 29 | features = reshape(image, [h*w, c]); 30 | if xyWeight > 0 31 | [x, y] = meshgrid(1 : w, 1 : h); 32 | x = xyWeight * double(x) / w; 33 | y = xyWeight * double(y) / h; 34 | features = [features x(:) y(:)]; 35 | end 36 | 37 | inMap = inMap(:); 38 | outMap = outMap(:); 39 | indices = (1 : h * w)'; 40 | inInd = indices(inMap); 41 | outInd = indices(outMap); 42 | 43 | if eraseSelfMatches 44 | % Find K + 1 matches to count for self-matches 45 | neighbors = knnsearch(features(outMap, :), features(inMap, :), 'K', K + 1); 46 | % Get rid of self-matches 47 | validNeighMap = true(size(neighbors)); 48 | validNeighMap(inMap(inInd) & outMap(inInd), 1) = 0; 49 | validNeighMap(:, end) = ~validNeighMap(:, 1); 50 | validNeighbors = zeros(size(neighbors, 1), size(neighbors, 2) - 1); 51 | for i = 1 : size(validNeighbors, 1) 52 | validNeighbors(i, :) = neighbors(i, validNeighMap(i, :)); 53 | end 54 | neighInd = outInd(validNeighbors); 55 | else 56 | neighbors = knnsearch(features(outMap, :), features(inMap, :), 'K', K); 57 | neighInd = outInd(neighbors); 58 | end 59 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/common/getMattingParams.m: -------------------------------------------------------------------------------- 1 | 2 | % The returned struct can be customized before given as 3 | % input to each of the methods available in this toolbox. 4 | % algName should be: 5 | % - 'IFM' for information flow matting 6 | % - 'CF' for closed-form matting 7 | % - 'KNN' for KNN matting 8 | % - 'IFMRefinement' for information flow matte refinement 9 | % - 'SharedMatting' for shared matting matte refinement 10 | 11 | function params = getMattingParams(algName) 12 | if strcmpi(algName, 'IFM') || strcmpi(algName, 'InformationFlowMatting') || strcmpi(algName, 'IFMrefinement') 13 | params.lambda = 100; 14 | params.usePCGtoSolve = true; 15 | 16 | % Switch to use known-to-unknown information flow 17 | % -1: automatic selection, 0: do not use, 1: use 18 | params.useKnownToUnknown = -1; 19 | 20 | % Switch to apply edge-based trimming after matte estimation 21 | % The value reported in the paper is true, although we leave the 22 | % default as false here. 23 | params.mattePostTrim = false; 24 | 25 | % Color mixture information flow parameters 26 | params.cm_K = 20; 27 | params.cm_xyw = 1; 28 | params.cm_mult = 1; 29 | 30 | % Known-to-unknown information flow parameters 31 | params.ku_K = 7; 32 | params.ku_xyw = 10; 33 | params.ku_mult = 0.05; 34 | 35 | % Intra-unknown information flow parameters 36 | params.iu_K = 5; 37 | params.iu_xyw = 0.05; 38 | params.iu_mult = 0.01; 39 | 40 | % Local information flow parameters 41 | params.loc_win = 1; 42 | params.loc_eps = 1e-6; 43 | params.loc_mult = 1; 44 | 45 | % Parameter for Information Flow Matting matte refinement 46 | params.refinement_mult = 0.1; 47 | end 48 | if strcmpi(algName, 'ClosedForm') || strcmpi(algName, 'CF') || strcmpi(algName, 'ClosedFormMatting')... 49 | || strcmpi(algName, 'SharedMatting') || strcmpi(algName, 'SharedMattingRefinement') 50 | params.lambda = 100; 51 | params.usePCGtoSolve = false; 52 | 53 | % Matting Laplacian parameters 54 | params.loc_win = 1; 55 | params.loc_eps = 1e-7; 56 | 57 | % Parameter for Shared Matting matte refinement 58 | params.refinement_mult = 0.1; 59 | end 60 | if strcmpi(algName, 'KNN') || strcmpi(algName, 'KNNMatting') 61 | params.lambda = 1000; 62 | params.usePCGtoSolve = true; 63 | 64 | % Parameters for the neighbor selection 65 | params.knn_K = 20; 66 | params.knn_xyw = 1; 67 | params.knn_hsv = true; 68 | end 69 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/common/localLinearEmbedding.m: -------------------------------------------------------------------------------- 1 | 2 | % Local Linear Embedding 3 | % This function implements the weight computation defined in 4 | % Sam T. Roweis, Lawrence K. Saul, "Nonlinear Dimensionality 5 | % Reduction by Local Linear Embedding", Science, 2000. 6 | % 'w' is the weights for representing the row-vector 'pt' in terms 7 | % of the dimensions x neighborCount matrix 'neighbors'. 8 | % 'conditionerMult' is the multiplier of the identity matrix added 9 | % to the neighborhood correlation matrix before inversion. 10 | 11 | function w = localLinearEmbedding(pt, neighbors, conditionerMult) 12 | % each column of neighbors represent a neighbor, each row a dimension 13 | % pt is a row vector 14 | corr = neighbors' * neighbors + conditionerMult * eye(size(neighbors, 2)); 15 | ptDotN = neighbors' * pt; 16 | alpha = 1 - sum(corr \ ptDotN); 17 | beta = sum(corr \ ones(size(corr, 1), 1)); % sum of elements of inv(corr) 18 | lagrangeMult = alpha / beta; 19 | w = corr \ (ptDotN + lagrangeMult); 20 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/common/localRGBnormalDistributions.m: -------------------------------------------------------------------------------- 1 | 2 | % RGB normal distributions fit to colors around each pixel 3 | 4 | function [meanImage, covarMat] = localRGBnormalDistributions(image, windowRadius, epsilon) 5 | 6 | if ~exist('windowRadius', 'var') || isempty(windowRadius) 7 | windowRadius = 1; 8 | end 9 | if ~exist('epsilon', 'var') || isempty(epsilon) 10 | epsilon = 1e-8; 11 | end 12 | 13 | [h, w, ~] = size(image); 14 | N = h * w; 15 | windowSize = 2 * windowRadius + 1; 16 | 17 | meanImage = imboxfilt(image, windowSize); 18 | covarMat = zeros(3, 3, N); 19 | 20 | for r = 1 : 3 21 | for c = r : 3 22 | temp = imboxfilt(image(:, :, r).*image(:, :, c), windowSize) - meanImage(:,:,r) .* meanImage(:,:,c); 23 | covarMat(r, c, :) = temp(:); 24 | end 25 | end 26 | 27 | for i = 1 : 3 28 | covarMat(i, i, :) = covarMat(i, i, :) + epsilon; 29 | end 30 | 31 | for r = 2 : 3 32 | for c = 1 : r - 1 33 | covarMat(r, c, :) = covarMat(c, r, :); 34 | end 35 | end 36 | 37 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/common/solveForAlphas.m: -------------------------------------------------------------------------------- 1 | 2 | % Constructs and solves the linear system 3 | 4 | function alphas = solveForAlphas(Lap, trimap, lambda, usePCG, alphaHat, conf, aHatMult) 5 | if ~exist('usePCG', 'var') || isempty(usePCG) 6 | usePCG = true; 7 | end 8 | [h, w, ~] = size(trimap); 9 | N = h * w; 10 | known = trimap > 0.8 | trimap < 0.2; 11 | A = lambda * spdiags(double(known(:)), 0, N, N); 12 | if exist('alphaHat', 'var') 13 | if ~exist('conf', 'var') || isempty(conf) 14 | conf = ones(size(alphaHat)); 15 | end 16 | if ~exist('aHatMult', 'var') || isempty(aHatMult) 17 | aHatMult = 0.1; 18 | end 19 | conf(known(:)) = 0; 20 | A = A + aHatMult * spdiags(conf(:), 0, N, N); 21 | b = A * alphaHat(:); 22 | else 23 | b = A * double(trimap(:) > 0.8); 24 | end 25 | A = A + Lap; 26 | if usePCG 27 | [alphas, ~] = pcg(A, b, [], 2000); 28 | else 29 | alphas = A \ b; 30 | end 31 | alphas(alphas < 0) = 0; 32 | alphas(alphas > 1) = 1; 33 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/demo.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/AffinityBasedMattingToolbox-master/demo.m -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/informationFlowMatteRefinement.m: -------------------------------------------------------------------------------- 1 | 2 | % Information-Flow Matte Refinement 3 | % This function implements the matte refinement approach described in 4 | % Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, "Designing Effective 5 | % Inter-Pixel Information Flow for Natural Image Matting", CVPR, 2017. 6 | % 'alphaHat' and 'confidences' parameters are typically obtained by a 7 | % sampling-based natural matting algorithm. 'confidences' is filled by 8 | % ones if not provided. Optional input parameter 'params' can be 9 | % customized by editing the default values in the struct returned 10 | % by 'getMattingParams('IFM'). 11 | % - **_K parameters represent the number of nonlocal neighbors found 12 | % for color mixture, and intra-U flows, while **_xyw define the effect of 13 | % spatial proximity. 14 | % - **_mult define the weight of each information flow. 15 | % - loc_*** define the parameters for the matting Laplacian. 16 | % - refinement_mult determines how much trust is given to the initial 17 | % alpha estimation 18 | 19 | function alpha = informationFlowMatteRefinement(image, trimap, alphaHat, confidences, params, suppressMessages) 20 | abmtSetup 21 | tic; 22 | if ~exist('confidences', 'var') || isempty(confidences) 23 | confidences = ones(size(alphaHat(:,:,1))); 24 | end 25 | if ~exist('params', 'var') || isempty(params) 26 | params = getMattingParams('IFM'); 27 | end 28 | if ~exist('suppressMessages', 'var') || isempty(suppressMessages) 29 | suppressMessages = false; 30 | end 31 | if(~suppressMessages) display('Matte refinement via Information-Flow Matting...'); end 32 | 33 | image = im2double(image); 34 | trimap = im2double(trimap(:,:,1)); 35 | alphaHat = im2double(alphaHat(:,:,1)); 36 | 37 | % Compute L_IFM 38 | unk = trimap < 0.8 & trimap > 0.2; 39 | dilUnk = imdilate(unk, ones(3, 3)); 40 | if(~suppressMessages) display(' Computing color mixture flow...'); end 41 | Lap = affinityMatrixToLaplacian(colorMixtureAffinities(image, params.cm_K, dilUnk, [], params.cm_xyw)); 42 | Lap = params.cm_mult * (Lap' * Lap); 43 | if(~suppressMessages) display(' Computing matting Laplacian...'); end 44 | Lap = Lap + params.loc_mult * affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps)); 45 | if(~suppressMessages) display(' Computing intra-U flow...'); end 46 | Lap = Lap + params.iu_mult * affinityMatrixToLaplacian(colorSimilarityAffinities(image, params.iu_K, unk, unk, params.iu_xyw)); 47 | 48 | if(~suppressMessages) display(' Solving for alphas...'); end 49 | alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve, alphaHat, confidences, params.refinement_mult); 50 | 51 | alpha = reshape(alpha, [size(image, 1), size(image, 2)]); 52 | 53 | dur = toc; 54 | if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end 55 | end 56 | -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/informationFlowMatting.m: -------------------------------------------------------------------------------- 1 | 2 | % Information-Flow Matting 3 | % This function implements the image matting approach described in 4 | % Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, "Designing Effective 5 | % Inter-Pixel Information Flow for Natural Image Matting", CVPR, 2017. 6 | % Optional input parameter 'params' can be customized by editing the 7 | % default values in the struct returned by 'getMattingParams('IFM'). 8 | % - The parameter useKnownToUnknown makes the decision to use 9 | % E_1 or E_2 as defined in the paper. A negative number means 10 | % automatic selection. 11 | % - **_K parameters represent the number of nonlocal neighbors found 12 | % for color mixture, K-to-U and intra-U flows, while **_xyw define the 13 | % effect of spatial proximity. 14 | % - **_mult define the weight of each information flow. 15 | % - loc_*** define the parameters for the matting Laplacian. 16 | % - mattePostTrim determines if edge-based trimming should be applied 17 | % as a post-processing to the estimated alpha. Here the defult is 18 | % false, but in the original paper it is reported to be 'true'. 19 | 20 | function alpha = informationFlowMatting(image, trimap, params, suppressMessages) 21 | abmtSetup 22 | tic; 23 | if ~exist('params', 'var') || isempty(params) 24 | params = getMattingParams('IFM'); 25 | end 26 | if ~exist('suppressMessages', 'var') || isempty(suppressMessages) 27 | suppressMessages = false; 28 | end 29 | if(~suppressMessages) display('Information-Flow Matting started...'); end 30 | 31 | image = im2double(image); 32 | trimap = im2double(trimap(:,:,1)); 33 | 34 | % Decide to use the K-to-U flow 35 | if params.useKnownToUnknown < 0 36 | useKU = ~detectHighlyTransparent(image, trimap); 37 | else 38 | useKU = params.useKnownToUnknown > 0; 39 | end 40 | if(~suppressMessages) 41 | if useKU 42 | display(' Known-to-unknown information flow will be used.'); 43 | else 44 | display(' Known-to-unknown information flow will NOT be used.'); 45 | end 46 | end 47 | 48 | if params.mattePostTrim || useKU 49 | % Trimap trimming for refining kToU flow or final matte 50 | if(~suppressMessages) display(' Trimming trimap from edges...'); end 51 | edgeTrimmed = trimmingFromKnownUnknownEdges(image, trimap); 52 | end 53 | 54 | % Compute L_IFM 55 | unk = trimap < 0.8 & trimap > 0.2; 56 | dilUnk = imdilate(unk, ones(2 * params.loc_win + 1)); 57 | if(~suppressMessages) display(' Computing color mixture flow...'); end 58 | Lap = affinityMatrixToLaplacian(colorMixtureAffinities(image, params.cm_K, unk, [], params.cm_xyw)); 59 | Lap = params.cm_mult * (Lap' * Lap); 60 | if(~suppressMessages) display(' Computing matting Laplacian...'); end 61 | Lap = Lap + params.loc_mult * affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps)); 62 | if(~suppressMessages) display(' Computing intra-U flow...'); end 63 | Lap = Lap + params.iu_mult * affinityMatrixToLaplacian(colorSimilarityAffinities(image, params.iu_K, unk, unk, params.iu_xyw)); 64 | 65 | if useKU 66 | % Compute kToU flow 67 | if(~suppressMessages) display(' Trimming trimap using patch similarity...'); end 68 | patchTrimmed = patchBasedTrimming(image, trimap, [], [], [], 5); % We set K = 5 here for better computation time 69 | if(~suppressMessages) display(' Computing K-to-U flow...'); end 70 | [kToU, kToUconf] = knownToUnknownColorMixture(image, patchTrimmed, params.ku_K, params.ku_xyw); 71 | kToU(edgeTrimmed < 0.2) = 0; 72 | kToU(edgeTrimmed > 0.8) = 1; 73 | kToUconf(edgeTrimmed < 0.2) = 1; 74 | kToUconf(edgeTrimmed > 0.8) = 1; 75 | if(~suppressMessages) display(' Solving for alphas...'); end 76 | alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve, kToU, kToUconf, params.ku_mult); 77 | else 78 | if(~suppressMessages) display(' Solving for alphas...'); end 79 | alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve); 80 | end 81 | 82 | alpha = reshape(alpha, [size(image, 1), size(image, 2)]); 83 | 84 | if params.mattePostTrim 85 | alpha(edgeTrimmed < 0.2) = 0; 86 | alpha(edgeTrimmed > 0.8) = 1; 87 | end 88 | 89 | dur = toc; 90 | if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end 91 | end 92 | -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/readme.md: -------------------------------------------------------------------------------- 1 | Affinity-Based Matting Toolbox 2 | ================================================================= 3 | 4 | About 5 | ------------ 6 | 7 | This toolbox includes a collection of common affinity-based image matting algorithms as well as matte refinement algorithms used by sampling-based image matting methods. 8 | It features the only public (re-)implementation of information-flow matting [AAP17], a faster matting Laplacian [LLW08] computation and a faster trimap trimming [SRPC13]. 9 | The parameters for each algorithm are easily customizable. 10 | 11 | The included matting algorithms are: 12 | 13 | - Information-flow matting [AAP17] 14 | - KNN matting [CLT13] 15 | - Closed-form matting [LLW08] 16 | 17 | The included matte refinement algorithms are: 18 | 19 | - Information-flow matte refinement [AAP17] 20 | - Shared matting matte refinement [GO10] 21 | 22 | The included trimap trimming methods are: 23 | 24 | - Patch-based trimming [AAP17] 25 | - Trimming from known-unknown edges [SRPC13] 26 | 27 | The toolbox is designed to be ease of use for an extended set of applications. 28 | Sparse affinity matrices defined and used in [AAP17, CLT13, CZZT12, LLW08] can be obtained by calling the corresponding functions inside 'affinity' directory. 29 | The functions in this directory allow defining regions for neighborhood search. 30 | 31 | An example image-trimap pair from the alpha matting benchmark [RRW09] is provided. 32 | Basic features are demonstrated in the demo file. 33 | Each function features an explanation and definitions of related parameters. 34 | 35 | The information-flow matting function in this toolbox is not the original implementation used in the paper. 36 | These are reimplementations of the original methods and may not give the exact same results as reported in the corresponding papers. 37 | 38 | Planned extensions 39 | ------------ 40 | I plan to add the layer color estimation methods, as well as LNSP matting and multiple-layer matte estimation methods in the near future. 41 | I may tweak the information-flow matting implementation to achieve its original performance on the benchmark. 42 | Feel free to contribute or propose a method to be added to the toolbox by [contacting me](http://people.inf.ethz.ch/aksoyy/contact/). 43 | 44 | License and citing the toolbox 45 | ------------ 46 | 47 | This toolbox is provided for academic use only. 48 | If you use this toolbox for an academic publication, please cite corresponding publications referenced in the description of each function, as well as this toolbox itself: 49 | 50 | @MISC{abmt, 51 | author={Ya\u{g}\{i}z Aksoy}, 52 | title={Affinity-based matting toolbox}, 53 | year={2017}, 54 | howpublished = {\url{https://github.com/yaksoy/AffinityBasedMattingToolbox}}, 55 | } 56 | 57 | References 58 | ------------ 59 | [AAP17] Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, "Designing Effective Inter-Pixel Information Flow for Natural Image Matting", CVPR, 2017. [[link](http://people.inf.ethz.ch/aksoyy/ifm/)] 60 | 61 | [CLT13] Qifeng Chen, Dingzeyu Li, Chi-Keung Tang, "KNN Matting", IEEE TPAMI, 2013. [[link](http://dingzeyu.li/projects/knn/)] 62 | 63 | [CZZT12] Xiaowu Chen, Dongqing Zou, Qinping Zhao, Ping Tan, "Manifold preserving edit propagation", ACM TOG, 2012 [[paper](http://www.cs.sfu.ca/~pingtan/Papers/sigasia12.pdf)] 64 | 65 | [GO10] Eduardo S. L. Gastal, Manuel M. Oliveira, "Shared Sampling for Real-Time Alpha Matting", Computer Graphics Forum, 2010. [[link](http://www.inf.ufrgs.br/~eslgastal/SharedMatting/)] 66 | 67 | [LLW08] Anat Levin, Dani Lischinski, Yair Weiss, "A Closed Form Solution to Natural Image Matting", IEEE TPAMI, 2008. [[paper](http://people.csail.mit.edu/alevin/papers/Matting-Levin-Lischinski-Weiss-PAMI.pdf)] 68 | 69 | [RRW09] Christoph Rhemann, Carsten Rother, Jue Wang, Margrit Gelautz, Pushmeet Kohli, Pamela Rott, "A Perceptually Motivated Online Benchmark for Image Matting", CVPR 2009. [[link](http://alphamatting.com)] 70 | 71 | [SRPC13] Ehsan Shahrian, Deepu Rajan, Brian Price, Scott Cohen, "Improving Image Matting using Comprehensive Sampling Sets", CVPR 2013 [[paper](http://www.cv-foundation.org/openaccess/content_cvpr_2013/papers/Shahrian_Improving_Image_Matting_2013_CVPR_paper.pdf)] -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/sharedMattingMatteRefinement.m: -------------------------------------------------------------------------------- 1 | 2 | % Shared Matting Matte Refinement 3 | % This function implements the matte refinement approach described in 4 | % Eduardo S. L. Gastal, Manuel M. Oliveira, "Shared Sampling for 5 | % Real-Time Alpha Matting", Computer Graphics Forum, 2010. 6 | % 'alphaHat' and 'confidences' parameters are typically obtained by a 7 | % sampling-based natural matting algorithm. 'confidences' is filled by 8 | % ones if not provided. Optional input parameter 'params' can be 9 | % customized by editing the default values in the struct returned 10 | % by 'getMattingParams('SharedMatting'). 11 | % - loc_*** define the parameters for the matting Laplacian. 12 | % - refinement_mult determines how much trust is given to the initial 13 | % alpha estimation 14 | 15 | function alpha = sharedMattingMatteRefinement(image, trimap, alphaHat, confidences, params, suppressMessages) 16 | abmtSetup 17 | tic; 18 | if ~exist('confidences', 'var') || isempty(confidences) 19 | confidences = ones(size(alphaHat(:,:,1))); 20 | end 21 | if ~exist('params', 'var') || isempty(params) 22 | params = getMattingParams('SharedMatting'); 23 | end 24 | if ~exist('suppressMessages', 'var') || isempty(suppressMessages) 25 | suppressMessages = false; 26 | end 27 | if(~suppressMessages) display('Matte refinement via Shared Matting...'); end 28 | 29 | image = im2double(image); 30 | trimap = im2double(trimap(:,:,1)); 31 | alphaHat = im2double(alphaHat(:,:,1)); 32 | 33 | % Compute matting Laplacian 34 | unk = trimap < 0.8 & trimap > 0.2; 35 | dilUnk = imdilate(unk, ones(3, 3)); 36 | if(~suppressMessages) display(' Computing matting Laplacian...'); end 37 | Lap = affinityMatrixToLaplacian(mattingAffinity(image, dilUnk, params.loc_win, params.loc_eps)); 38 | 39 | if(~suppressMessages) display(' Solving for alphas...'); end 40 | alpha = solveForAlphas(Lap, trimap, params.lambda, params.usePCGtoSolve, alphaHat, confidences, params.refinement_mult); 41 | 42 | alpha = reshape(alpha, [size(image, 1), size(image, 2)]); 43 | 44 | dur = toc; 45 | if(~suppressMessages) display(['Done. It took ' num2str(dur) ' seconds.']); end 46 | end 47 | -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/trimming/patchBasedTrimming.m: -------------------------------------------------------------------------------- 1 | 2 | % Patch-Based Trimming 3 | % This function implements the trimap trimming approach described in 4 | % Yagiz Aksoy, Tunc Ozan Aydin, Marc Pollefeys, "Designing Effective 5 | % Inter-Pixel Information Flow for Natural Image Matting", CVPR, 2017. 6 | % The input parameters other than image and trimap are optional. 7 | % - minDist and maxDist define a good match, and a match in BG that 8 | % rejects a good match in FG, and vice versa. 9 | % - windowRadius defines the size of the window where the local normal 10 | % distributions are estimated 11 | % - K defines the number of nearest neighbors found using the mean 12 | % vectors before the Bhattacharyya distance comparison. 13 | 14 | function trimap = patchBasedTrimming(image, trimap, minDist, maxDist, windowRadius, K) 15 | 16 | if ~exist('minDist', 'var') || isempty(minDist) 17 | minDist = 0.25; 18 | end 19 | if ~exist('maxDist', 'var') || isempty(maxDist) 20 | maxDist = 0.90; 21 | end 22 | if ~exist('windowRadius', 'var') || isempty(windowRadius) 23 | windowRadius = 1; 24 | end 25 | if ~exist('K', 'var') || isempty(K) 26 | K = 10; 27 | end 28 | 29 | image = im2double(image); 30 | trimap = im2double(trimap(:,:,1)); 31 | [h, w, ~] = size(image); 32 | 33 | epsilon = 1e-8; 34 | 35 | fg = trimap > 0.8; 36 | bg = trimap < 0.2; 37 | unk = ~(fg | bg); 38 | 39 | [meanImage, covarMat] = localRGBnormalDistributions(image, windowRadius, epsilon); 40 | 41 | [unkInd, fgNeigh] = findNonlocalNeighbors(meanImage, K, -1, unk, fg); 42 | [~, bgNeigh] = findNonlocalNeighbors(meanImage, K, -1, unk, bg); 43 | 44 | meanImage = reshape(meanImage, [h * w, size(meanImage, 3)]); 45 | 46 | fgBhatt = zeros(K, 1); 47 | bgBhatt = zeros(K, 1); 48 | for i = 1 : size(unkInd, 1) 49 | pixMean = meanImage(unkInd(i), :)'; 50 | pixCovar = covarMat(:, :, unkInd(i)); 51 | pixDet = det(pixCovar); 52 | for n = 1 : K 53 | nMean = meanImage(fgNeigh(i, n), :)' - pixMean; 54 | nCovar = covarMat(:, :, fgNeigh(i, n)); 55 | nDet = det(nCovar); 56 | nCovar = (pixCovar + nCovar) / 2; 57 | fgBhatt(n) = 0.125 * nMean' * (nCovar \ nMean) + 0.5 * log(det(nCovar) / sqrt(pixDet * nDet)); % Bhattacharyya distance 58 | end 59 | for n = 1 : K 60 | nMean = meanImage(bgNeigh(i, n), :)' - pixMean; 61 | nCovar = covarMat(:, :, bgNeigh(i, n)); 62 | nDet = det(nCovar); 63 | nCovar = (pixCovar + nCovar) / 2; 64 | bgBhatt(n) = 0.125 * nMean' * (nCovar \ nMean) + 0.5 * log(det(nCovar) / sqrt(pixDet * nDet)); % Bhattacharyya distance 65 | end 66 | minFGdist = min(fgBhatt); 67 | minBGdist = min(bgBhatt); 68 | if minFGdist < minDist 69 | if minBGdist > maxDist 70 | trimap(unkInd(i)) = 1; 71 | end 72 | elseif minBGdist < minDist 73 | if minFGdist > maxDist 74 | trimap(unkInd(i)) = 0; 75 | end 76 | end 77 | end 78 | end -------------------------------------------------------------------------------- /AffinityBasedMattingToolbox-master/trimming/trimmingFromKnownUnknownEdges.m: -------------------------------------------------------------------------------- 1 | 2 | % Trimming from Edges of the Unknown Region 3 | % This function implements the trimap trimming approach described in 4 | % Ehsan Shahrian, Deepu Rajan, Brian Price, Scott Cohen, "Improving 5 | % Image Matting using Comprehensive Sampling Sets", CVPR 2013 6 | % The implementation uses the public source code provided by the 7 | % authors as a guideline and has an iterative structure not explained 8 | % in the paper. The input parameters other than image and trimap 9 | % are optional. 10 | % - Maximum Manhattan distance of trimming is determined by iterCnt 11 | % such that maxManhDist = sum(1:iterCnt). 12 | % - paramU determines the (maximum) color threshold in the iterations. 13 | % - paramD determines how much this threshold is lowered as the 14 | % iterations progress. 15 | 16 | function trimap = trimmingFromKnownUnknownEdges(image, trimap, paramU, paramD, iterCnt) 17 | 18 | if ~exist('iterCnt', 'var') || isempty(iterCnt) 19 | iterCnt = 9; 20 | end 21 | if ~exist('paramD', 'var') || isempty(paramD) 22 | paramD = 1 / 256; 23 | end 24 | if ~exist('paramU', 'var') || isempty(paramU) 25 | paramU = 9 / 256; 26 | end 27 | 28 | image = im2double(image); 29 | trimap = im2double(trimap); 30 | bg = (trimap < 0.2); 31 | fg = (trimap > 0.8); 32 | paramD = paramU - paramD; 33 | 34 | for i = 1 : iterCnt 35 | iterColorThresh = paramU - i * paramD / iterCnt; % color threshold = paramU - iterNo * (paramU - paramD) / maxIter 36 | trimap = LabelExpansion(image, trimap, i, iterColorThresh); % distance threshold 1 to iterCnt 37 | end 38 | end 39 | 40 | function [extendedTrimap] = LabelExpansion(image, trimap, maxDist, colorThresh) 41 | [h, w, ~] = size(image); 42 | 43 | fg = trimap > 0.8; 44 | bg = trimap < 0.2; 45 | knownReg = (bg | fg); 46 | extendedTrimap = trimap; 47 | 48 | searchReg= ((imdilate(fg, ones(2 * maxDist + 1)) & ~fg) | (imdilate(bg, ones(2 * maxDist + 1)) & ~bg)); 49 | [cols, rows] = meshgrid(1 : w, 1 : h); 50 | cols = cols(searchReg(:)); 51 | rows = rows(searchReg(:)); 52 | 53 | winCenter = (2 * maxDist) / 2 + 1; 54 | distPlane = repmat((1 : 2 * maxDist + 1)', [1, 2 * maxDist + 1])'; 55 | distPlane = sqrt((distPlane - winCenter) .^ 2 + (distPlane' - winCenter) .^ 2); 56 | 57 | for pixNo = 1 : size(cols, 1) 58 | r = rows(pixNo); 59 | c = cols(pixNo); 60 | minR = max(r - maxDist, 1); % pixel limits 61 | minC = max(c - maxDist, 1); 62 | maxR = min(r + maxDist , h); 63 | maxC = min(c + maxDist, w); 64 | winMinR = winCenter - (r - minR); % pixel limits in window 65 | winMinC = winCenter - (c - minC); 66 | winMaxR = winCenter + (maxR - r); 67 | winMaxC = winCenter + (maxC - c); 68 | 69 | pixColor = image(r, c, :); 70 | imgWin = image(minR : maxR, minC : maxC, :); % colors 71 | trimapWin = trimap(minR : maxR, minC : maxC); 72 | 73 | winColorDiff = imgWin(:, :, 1) - pixColor(1); 74 | winColorDiff(:, :, 2) = imgWin(:, :, 2) - pixColor(2); 75 | winColorDiff(:, :, 3) = imgWin(: ,:, 3) - pixColor(3); 76 | winColorDiff = sqrt(sum(winColorDiff .* winColorDiff, 3)); 77 | 78 | candidates= (winColorDiff < colorThresh) & knownReg(minR : maxR, minC : maxC); % known pixels under thresh 79 | if sum(candidates(:)) > 0 80 | distWin = distPlane(winMinR : winMaxR, winMinC : winMaxC); % distance plane 81 | distWin = distWin(candidates); % distances of known 82 | [~, minDistInd] = min(distWin); % location of minimum 83 | trimapWin = trimapWin(candidates); 84 | extendedTrimap(r, c) = trimapWin(minDistInd); 85 | end 86 | end 87 | 88 | end 89 | -------------------------------------------------------------------------------- /BayesianMatting/app.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/app.fig -------------------------------------------------------------------------------- /BayesianMatting/app.m: -------------------------------------------------------------------------------- 1 | function varargout = app(varargin) 2 | % APP M-file for app.fig 3 | % APP, by itself, creates a new APP or raises the existing 4 | % singleton*. 5 | % 6 | % H = APP returns the handle to a new APP or the handle to 7 | % the existing singleton*. 8 | % 9 | % APP('CALLBACK',hObject,eventData,handles,...) calls the local 10 | % function named CALLBACK in APP.M with the given input arguments. 11 | % 12 | % APP('Property','Value',...) creates a new APP or raises the 13 | % existing singleton*. Starting from the left, property value pairs are 14 | % applied to the GUI before app_OpeningFunction gets called. An 15 | % unrecognized property name or invalid value makes property application 16 | % stop. All inputs are passed to app_OpeningFcn via varargin. 17 | % 18 | % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one 19 | % instance to run (singleton)". 20 | % 21 | % See also: GUIDE, GUIDATA, GUIHANDLES 22 | 23 | % Edit the above text to modify the response to help app 24 | 25 | % Last Modified by GUIDE v2.5 17-Feb-2009 13:58:39 26 | 27 | % Begin initialization code - DO NOT EDIT 28 | gui_Singleton = 1; 29 | gui_State = struct('gui_Name', mfilename, ... 30 | 'gui_Singleton', gui_Singleton, ... 31 | 'gui_OpeningFcn', @app_OpeningFcn, ... 32 | 'gui_OutputFcn', @app_OutputFcn, ... 33 | 'gui_LayoutFcn', [] , ... 34 | 'gui_Callback', []); 35 | if nargin && ischar(varargin{1}) 36 | gui_State.gui_Callback = str2func(varargin{1}); 37 | end 38 | 39 | if nargout 40 | [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); 41 | else 42 | gui_mainfcn(gui_State, varargin{:}); 43 | end 44 | % End initialization code - DO NOT EDIT 45 | 46 | 47 | % --- Executes just before app is made visible. 48 | function app_OpeningFcn(hObject, eventdata, handles, varargin) 49 | % This function has no output args, see OutputFcn. 50 | % hObject handle to figure 51 | % eventdata reserved - to be defined in a future version of MATLAB 52 | % handles structure with handles and user data (see GUIDATA) 53 | % varargin command line arguments to app (see VARARGIN) 54 | 55 | % Choose default command line output for app 56 | handles.output = hObject; 57 | 58 | % Update handles structure 59 | guidata(hObject, handles); 60 | 61 | % UIWAIT makes app wait for user response (see UIRESUME) 62 | % uiwait(handles.figure1); 63 | 64 | init(handles); 65 | 66 | % --- Outputs from this function are returned to the command line. 67 | function varargout = app_OutputFcn(hObject, eventdata, handles) 68 | % varargout cell array for returning output args (see VARARGOUT); 69 | % hObject handle to figure 70 | % eventdata reserved - to be defined in a future version of MATLAB 71 | % handles structure with handles and user data (see GUIDATA) 72 | 73 | % Get default command line output from handles structure 74 | varargout{1} = handles.output; 75 | 76 | % --- Initialization function 77 | function init(handles) 78 | 79 | global appdata; 80 | appdata.simg=[]; 81 | appdata.timg=[]; 82 | appdata.trimap=[]; 83 | appdata.matte=[]; 84 | appdata.result=[]; 85 | 86 | % clear axes 87 | imshow([],'Parent',handles.source_axes); 88 | imshow([],'Parent',handles.trimap_axes); 89 | imshow([],'Parent',handles.alpha_axes); 90 | drawnow; 91 | 92 | % -------------------------------------------------------------------- 93 | function menu_load_source_image_Callback(hObject, eventdata, handles) 94 | % hObject handle to menu_load_source_image (see GCBO) 95 | % eventdata reserved - to be defined in a future version of MATLAB 96 | % handles structure with handles and user data (see GUIDATA) 97 | 98 | global appdata; 99 | [filename,cancelled]=imgetfile; 100 | if ~cancelled 101 | init(handles); 102 | appdata.simg=imread(filename); 103 | imshow(appdata.simg,'Parent',handles.source_axes); 104 | end 105 | 106 | 107 | % -------------------------------------------------------------------- 108 | function menu_file_enter_trimap_Callback(hObject, eventdata, handles) 109 | % hObject handle to menu_file__enter_trimap (see GCBO) 110 | % eventdata reserved - to be defined in a future version of MATLAB 111 | % handles structure with handles and user data (see GUIDATA) 112 | 113 | global appdata; 114 | if isempty(appdata.simg) 115 | warndlg('Load source image first!'); 116 | return; 117 | end 118 | appdata.trimap=getTrimap(appdata.simg); 119 | close; % close trimap window 120 | imshow(appdata.trimap,'Parent',handles.trimap_axes); 121 | 122 | 123 | % -------------------------------------------------------------------- 124 | function menu_file_save_trimap_Callback(hObject, eventdata, handles) 125 | % hObject handle to menu_file_save_trimap (see GCBO) 126 | % eventdata reserved - to be defined in a future version of MATLAB 127 | % handles structure with handles and user data (see GUIDATA) 128 | 129 | global appdata; 130 | if isempty(appdata.trimap) 131 | warndlg('Trimap not entered!'); 132 | return; 133 | end 134 | [filename,pathname] = uiputfile('*.png'); 135 | if filename 136 | imwrite(appdata.trimap,[pathname filename]); 137 | end 138 | 139 | 140 | % -------------------------------------------------------------------- 141 | function menu_file_load_trimap_Callback(hObject, eventdata, handles) 142 | % hObject handle to menu_file_load_trimap (see GCBO) 143 | % eventdata reserved - to be defined in a future version of MATLAB 144 | % handles structure with handles and user data (see GUIDATA) 145 | 146 | global appdata; 147 | if isempty(appdata.simg) 148 | warndlg('Load source image first!'); 149 | return; 150 | end 151 | [filename,cancelled]=imgetfile; 152 | if ~cancelled 153 | appdata.trimap=imread(filename); 154 | imshow(appdata.trimap,'Parent',handles.trimap_axes); 155 | end 156 | 157 | 158 | % -------------------------------------------------------------------- 159 | function menu_file_load_alpha_Callback(hObject, eventdata, handles) 160 | % hObject handle to menu_file_load_alpha (see GCBO) 161 | % eventdata reserved - to be defined in a future version of MATLAB 162 | % handles structure with handles and user data (see GUIDATA) 163 | 164 | global appdata; 165 | 166 | % will override currently loaded data 167 | [filename,pathname] = uigetfile('*.mat'); 168 | if filename 169 | matte=load([pathname filename]); 170 | init(handles); 171 | % reconstruct source image 172 | simg=repmat(matte.alpha,[1,1,3]).*matte.F+repmat(1-matte.alpha,[1,1,3]).*matte.B; 173 | appdata.simg=simg; 174 | appdata.trimap=matte.trimap; 175 | appdata.matte.F=matte.F; 176 | appdata.matte.B=matte.B; 177 | appdata.matte.alpha=matte.alpha; 178 | imshow(appdata.simg,'Parent',handles.source_axes); 179 | imshow(appdata.trimap,'Parent',handles.trimap_axes); 180 | imshow(appdata.matte.alpha,'Parent',handles.alpha_axes); 181 | end 182 | 183 | 184 | % -------------------------------------------------------------------- 185 | function menu_compose_create_composite_Callback(hObject, eventdata, handles) 186 | % hObject handle to menu_compose_create_composite (see GCBO) 187 | % eventdata reserved - to be defined in a future version of MATLAB 188 | % handles structure with handles and user data (see GUIDATA) 189 | 190 | global appdata; 191 | if isempty(appdata.matte) 192 | warndlg('Calculate/Load matte first!'); 193 | return; 194 | end 195 | % get target image 196 | [filename,cancelled]=imgetfile; 197 | if ~cancelled 198 | appdata.timg=imread(filename); 199 | appdata.result=makeComposite(appdata.matte.F,appdata.timg,appdata.matte.alpha); 200 | figure('Name','New Composite','NumberTitle','off'); 201 | imshow(appdata.result); 202 | end 203 | 204 | 205 | 206 | % -------------------------------------------------------------------- 207 | function menu_run_calc_alpha_matte_Callback(hObject, eventdata, handles) 208 | % hObject handle to menu_run_calc_alpha_matte (see GCBO) 209 | % eventdata reserved - to be defined in a future version of MATLAB 210 | % handles structure with handles and user data (see GUIDATA) 211 | 212 | global appdata; 213 | 214 | if isempty(appdata.trimap) 215 | warndlg('Enter/Load trimap first!'); 216 | return; 217 | end 218 | p=makeParameters; 219 | p.guiMode=1; 220 | [F,B,alpha]=bayesmat(appdata.simg,appdata.trimap,p); 221 | appdata.matte.F=F; 222 | appdata.matte.B=B; 223 | appdata.matte.alpha=alpha; 224 | appdata.matte.trimap=appdata.trimap; 225 | imshow(appdata.matte.alpha,'Parent',handles.alpha_axes); 226 | 227 | % shop alpha in separate window 228 | figure('Name','Alpha Result','NumberTitle','off'); 229 | imshow(alpha); 230 | 231 | % -------------------------------------------------------------------- 232 | function menu_compose_save_composite_Callback(hObject, eventdata, handles) 233 | % hObject handle to menu_compose_save_composite (see GCBO) 234 | % eventdata reserved - to be defined in a future version of MATLAB 235 | % handles structure with handles and user data (see GUIDATA) 236 | 237 | global appdata; 238 | 239 | if isempty(appdata.result) 240 | warndlg('Create Composite first!'); 241 | return; 242 | end 243 | [filename,pathname] = uiputfile('*.png;*.jpg'); 244 | if filename 245 | imwrite(appdata.result,[pathname filename]); 246 | end 247 | 248 | 249 | % -------------------------------------------------------------------- 250 | function menu_run_save_alpha_matte_Callback(hObject, eventdata, handles) 251 | % hObject handle to menu_run_save_alpha_matte (see GCBO) 252 | % eventdata reserved - to be defined in a future version of MATLAB 253 | % handles structure with handles and user data (see GUIDATA) 254 | 255 | global appdata; 256 | 257 | if isempty(appdata.matte) 258 | warndlg('Calculate alpha matte first!'); 259 | return; 260 | end 261 | [filename,pathname] = uiputfile('*.mat'); 262 | if filename 263 | F=appdata.matte.F; 264 | B=appdata.matte.B; 265 | alpha=appdata.matte.alpha; 266 | trimap=appdata.trimap; 267 | save([pathname filename],'F','B','alpha','trimap'); 268 | end 269 | 270 | 271 | -------------------------------------------------------------------------------- /BayesianMatting/bayesmat.m: -------------------------------------------------------------------------------- 1 | function [F,B,alpha]=bayesmat(im,trimap,p) 2 | 3 | % BAYESMAT Calculates alpha matting for the given image and trimap. 4 | % input: 5 | % im - the input image 6 | % trimap - the given trimap mask (same size of im). It will be treated 7 | % as follows: pixels where trimap=0 will be considered as background; 8 | % pixels where trimap=1 (or 255) will be considered as foreground; all 9 | % other pixels will be considered as unknowns; 10 | % p - parameters structure as created by makeParameters.m 11 | % 12 | % returns: 13 | % F,B,alpha - decomposition of the image into (F)oreground, (B)ackground 14 | % and alpha channel. 15 | % 16 | % Author: Michael Rubinstein 17 | % 18 | 19 | % initialize progress bar if invoked via UI 20 | if p.guiMode 21 | progressbar; 22 | end 23 | 24 | im=im2double(im); 25 | trimap=im2double(trimap); 26 | 27 | bgmask=trimap==0; % background region mask 28 | fgmask=trimap==1; % foreground region mask 29 | unkmask=~bgmask&~fgmask; % unknow region mask 30 | 31 | % initialize F,B,alpha 32 | F=im; F(repmat(~fgmask,[1,1,3]))=0; 33 | B=im; B(repmat(~bgmask,[1,1,3]))=0; 34 | alpha=zeros(size(trimap)); 35 | alpha(fgmask)=1; 36 | alpha(unkmask)=NaN; 37 | 38 | nUnknown=sum(unkmask(:)); 39 | 40 | % guassian falloff. will be used for weighting each pixel neighborhood 41 | g=fspecial('gaussian', p.N, p.sigma); g=g/max(g(:)); 42 | % square structuring element for eroding the unknown region(s) 43 | se=strel('square',3); 44 | 45 | n=1; 46 | unkreg=unkmask; 47 | while n0,:); 80 | f_weights=f_weights(f_weights>0); 81 | 82 | % take surrounding background pixels 83 | b_pixels=getN(B,x,y,p.N); 84 | b_weights=((1-a).^2).*g; 85 | b_pixels=reshape(b_pixels,p.N*p.N,3); 86 | b_pixels=b_pixels(b_weights>0,:); 87 | b_weights=b_weights(b_weights>0); 88 | 89 | % if not enough data, return to it later... 90 | if length(f_weights)minVar) 21 | nodes=split(nodes); 22 | end 23 | 24 | for i=1:length(nodes) 25 | mu(:,i)=nodes(i).q; 26 | Sigma(:,:,i)=nodes(i).R; 27 | end 28 | 29 | % calculates cluster statistics 30 | function C=calc(C) 31 | 32 | W=sum(C.w); 33 | % weighted mean 34 | C.q=sum(repmat(C.w,[1,size(C.X,2)]).*C.X,1)/W; 35 | % weighted covariance 36 | t=(C.X-repmat(C.q,[size(C.X,1),1])).*(repmat(sqrt(C.w),[1,size(C.X,2)])); 37 | C.R=(t'*t)/W + 1e-5*eye(3); 38 | 39 | C.wtse = sum(sum((C.X-repmat(C.q,[size(C.X,1),1])).^2)); 40 | 41 | [V,D]=eig(C.R); 42 | C.e=V(:,3); 43 | C.lambda=D(9); 44 | 45 | % splits maximal eigenvalue node in direction of maximal variance 46 | function nodes=split(nodes) 47 | 48 | [x,i]=max([nodes.lambda]); 49 | Ci=nodes(i); 50 | idx=Ci.X*Ci.e<=Ci.q*Ci.e; 51 | Ca.X=Ci.X(idx,:); Ca.w=Ci.w(idx); 52 | Cb.X=Ci.X(~idx,:); Cb.w=Ci.w(~idx); 53 | Ca=calc(Ca); 54 | Cb=calc(Cb); 55 | nodes(i)=[]; % remove the i'th nodes and replace it with its children 56 | nodes=[nodes,Ca,Cb]; 57 | 58 | -------------------------------------------------------------------------------- /BayesianMatting/cluster_OrachardBouman.m: -------------------------------------------------------------------------------- 1 | function [mu,Sigma]=cluster_OrachardBouman(S,w,minVar) 2 | 3 | % Implements color clustering presented by Orchard and Bouman (1991) 4 | % input: 5 | % S - measurements vector 6 | % w - corresponding weights 7 | % returns: 8 | % mu - cluster means 9 | % Sigma - cluster covariances 10 | % 11 | % Author: Michael Rubinstein 12 | % 13 | 14 | % initially, all measurements are one cluster 15 | C1.X=S; 16 | C1.w=w; 17 | C1=calc(C1); 18 | nodes=[C1]; 19 | 20 | while (max([nodes.lambda])>minVar) 21 | nodes=split(nodes); 22 | end 23 | 24 | for i=1:length(nodes) 25 | mu(:,i)=nodes(i).q; 26 | Sigma(:,:,i)=nodes(i).R; 27 | end 28 | 29 | % calculates cluster statistics 30 | function C=calc(C) 31 | 32 | W=sum(C.w); 33 | % weighted mean 34 | C.q=sum(repmat(C.w,[1,size(C.X,2)]).*C.X,1)/W; 35 | % weighted covariance 36 | t=(C.X-repmat(C.q,[size(C.X,1),1])).*(repmat(sqrt(C.w),[1,size(C.X,2)])); 37 | C.R=(t'*t)/W + 1e-5*eye(3); 38 | 39 | C.wtse = sum(sum((C.X-repmat(C.q,[size(C.X,1),1])).^2)); 40 | 41 | [V,D]=eig(C.R); 42 | C.e=V(:,3); 43 | C.lambda=D(9); 44 | 45 | % splits maximal eigenvalue node in direction of maximal variance 46 | function nodes=split(nodes) 47 | 48 | [x,i]=max([nodes.lambda]); 49 | Ci=nodes(i); 50 | idx=Ci.X*Ci.e<=Ci.q*Ci.e; 51 | Ca.X=Ci.X(idx,:); Ca.w=Ci.w(idx); 52 | Cb.X=Ci.X(~idx,:); Cb.w=Ci.w(~idx); 53 | Ca=calc(Ca); 54 | Cb=calc(Cb); 55 | nodes(i)=[]; % remove the i'th nodes and replace it with its children 56 | nodes=[nodes,Ca,Cb]; 57 | 58 | -------------------------------------------------------------------------------- /BayesianMatting/getTrimap.m: -------------------------------------------------------------------------------- 1 | function trimap=getTrimap(simg) 2 | 3 | % GETTRIMAP Enables the user to enter trimap for the given image using 4 | % a simple polygonal interface. Instructions will appear in MATLAB 5 | % command line 6 | % The resulting trimap will have the same size as simg, with values 0,1 7 | % and 0.5 at pixels marked background, foreground and unknown 8 | % respectively. 9 | % 10 | % Author: Michael Rubinstein 11 | % 12 | 13 | simg=im2double(simg); 14 | % defines the source polygon 15 | figure('Name','Enter Trimap','NumberTitle','off'); 16 | imshow(simg); 17 | fprintf('====>Mark foreground region\n'); 18 | fprintf('====>Define polygon with left mouse clicks and terminate with a right click\n'); 19 | [smap,sxi,syi]=roipoly; sxi=floor(sxi); syi=floor(syi); 20 | 21 | trimap=zeros(size(smap)); 22 | trimap(smap)=1; 23 | hold on; 24 | im2=.5*(simg+repmat(trimap,[1,1,3])); % for display 25 | imshow(im2); 26 | 27 | fprintf('====>Mark unknown region\n'); 28 | fprintf('====>Define polygon with left mouse clicks and terminate with a right click\n'); 29 | 30 | kmap=roipoly; 31 | trimap(kmap&~smap)=0.5; 32 | im2=.5*(simg+repmat(trimap,[1,1,3])); % for display 33 | imshow(im2); 34 | 35 | -------------------------------------------------------------------------------- /BayesianMatting/images/bag/plasticbag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/bag/plasticbag.png -------------------------------------------------------------------------------- /BayesianMatting/images/bag/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/bag/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/bear/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/bear/Thumbs.db -------------------------------------------------------------------------------- /BayesianMatting/images/bear/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/bear/background.jpg -------------------------------------------------------------------------------- /BayesianMatting/images/bear/input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/bear/input.jpg -------------------------------------------------------------------------------- /BayesianMatting/images/bear/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/bear/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/dog/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/dog/Thumbs.db -------------------------------------------------------------------------------- /BayesianMatting/images/dog/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/dog/background.png -------------------------------------------------------------------------------- /BayesianMatting/images/dog/input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/dog/input.jpg -------------------------------------------------------------------------------- /BayesianMatting/images/dog/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/dog/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/gandalf/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/gandalf/Thumbs.db -------------------------------------------------------------------------------- /BayesianMatting/images/gandalf/background-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/gandalf/background-small.png -------------------------------------------------------------------------------- /BayesianMatting/images/gandalf/background.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/gandalf/background.jpg -------------------------------------------------------------------------------- /BayesianMatting/images/gandalf/input-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/gandalf/input-small.png -------------------------------------------------------------------------------- /BayesianMatting/images/gandalf/mytrimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/gandalf/mytrimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/gandalf/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/gandalf/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/knockout/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/knockout/background.png -------------------------------------------------------------------------------- /BayesianMatting/images/knockout/input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/knockout/input.png -------------------------------------------------------------------------------- /BayesianMatting/images/knockout/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/knockout/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/lighthouse/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/lighthouse/background.png -------------------------------------------------------------------------------- /BayesianMatting/images/lighthouse/input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/lighthouse/input.png -------------------------------------------------------------------------------- /BayesianMatting/images/lighthouse/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/lighthouse/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/me/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/me/background.png -------------------------------------------------------------------------------- /BayesianMatting/images/me/cheng.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/me/cheng.jpg -------------------------------------------------------------------------------- /BayesianMatting/images/me/input.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/me/input.jpg -------------------------------------------------------------------------------- /BayesianMatting/images/me/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/me/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/net/alpha.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/net/alpha.png -------------------------------------------------------------------------------- /BayesianMatting/images/net/bayesian.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/net/bayesian.mat -------------------------------------------------------------------------------- /BayesianMatting/images/net/net.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/net/net.png -------------------------------------------------------------------------------- /BayesianMatting/images/net/pineapple.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/net/pineapple.png -------------------------------------------------------------------------------- /BayesianMatting/images/net/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/net/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/images/net/troll.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/net/troll.png -------------------------------------------------------------------------------- /BayesianMatting/images/woman/Thumbs.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/woman/Thumbs.db -------------------------------------------------------------------------------- /BayesianMatting/images/woman/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/woman/background.png -------------------------------------------------------------------------------- /BayesianMatting/images/woman/compose.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/woman/compose.jpg -------------------------------------------------------------------------------- /BayesianMatting/images/woman/input.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/woman/input.png -------------------------------------------------------------------------------- /BayesianMatting/images/woman/trimap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/images/woman/trimap.png -------------------------------------------------------------------------------- /BayesianMatting/makeComposite.m: -------------------------------------------------------------------------------- 1 | function C=makeComposite(F,B,alpha) 2 | 3 | % MAKECOMPOSITE Creates new composite given foreground image F, 4 | % background image B and alpha channel. 5 | % Applies the following simple logic: if size(B)=size(F), then the 6 | % foreground is simply composed on the background image. Otherwise, the 7 | % user will be able to choose where to place the foreground object in the 8 | % new composition. Use left mouse clicks to change the location and right 9 | % mouse click to confirm the decision. 10 | % 11 | % If the function is called with B=[], the foreground will be composed on 12 | % a black background. 13 | % 14 | % Author: Michael Rubinstein 15 | % 16 | 17 | if isempty(B) 18 | B=zeros(size(F)); 19 | end 20 | 21 | if ~isa(F,'double') 22 | F=im2double(F); 23 | end 24 | if ~isa(B,'double') 25 | B=im2double(B); 26 | end 27 | 28 | if all(size(F)==size(B)) 29 | C=makeComposite_fixed(alpha,F,B); 30 | else 31 | C=makeComposite_free(alpha,F,B); 32 | end 33 | 34 | 35 | function C=makeComposite_fixed(alpha,F,B) 36 | 37 | alpha=repmat(alpha,[1,1,size(F,3)]); 38 | C=alpha.*F+(1-alpha).*B; 39 | 40 | 41 | function C=makeComposite_free(alpha,F,timg) 42 | 43 | % calculate bounding box for matte 44 | [y,x]=find(alpha~=0); 45 | [h,w]=size(alpha); 46 | xmin=min(x); ymin=min(y); 47 | xmax=max(x); ymax=max(y); 48 | ww=xmax-xmin+1; wh=ymax-ymin+1; 49 | % extract bounding box data 50 | F=F(ymin:ymax,xmin:xmax,:); 51 | alpha=repmat(alpha(ymin:ymax,xmin:xmax),[1,1,size(timg,3)]); 52 | 53 | % create interface 54 | figure('Name','Create Composite','NumberTitle','off'); 55 | imagesc(timg); 56 | C=timg; 57 | while 1 58 | [x,y,btn]=ginput(1); 59 | if btn==3 60 | break; 61 | end 62 | tmp=timg; 63 | twinX=round(x) ; twinY=round(y); 64 | if ( x<1 | y<1 | (twinY+wh)>size(timg,1) | (twinX+ww)>size(timg,2)), 65 | fprintf('====>Out of bounds, or paste area exceeds image area. Try again!\n\n'); 66 | else, 67 | B=tmp(twinY:(twinY+wh-1),twinX:(twinX+ww-1),:); 68 | tmp(twinY:(twinY+wh-1),twinX:(twinX+ww-1),:)=alpha.*F+(1-alpha).*B; 69 | C=tmp; 70 | imagesc(C); 71 | end; 72 | end; 73 | 74 | close; 75 | 76 | -------------------------------------------------------------------------------- /BayesianMatting/makeParameters.m: -------------------------------------------------------------------------------- 1 | function p=makeParameters() 2 | 3 | p=struct(); 4 | 5 | p.N= 25; % pixel neighborhood size 6 | p.sigma= 8; % variance of gaussian for spatial weighting 7 | p.sigma_C= 0.01; % camera variance 8 | p.clustFunc= @cluster_OrachardBouman; % clustering function 9 | p.minN= 10; % minimum required foreground and background neighbors for optimization 10 | p.guiMode= 0; % if 1, will show a nice looking progress bar. if 0, will print progress to command line 11 | 12 | % clustering parameters 13 | p.clust.minVar= 0.05; % minimal cluster variance in order to stop splitting 14 | 15 | % optimization parameters 16 | p.opt.maxIter= 50; % maximal number of iterations 17 | p.opt.minLike= 1e-6; % minimal change in likelihood between consecutive iterations 18 | -------------------------------------------------------------------------------- /BayesianMatting/progressbar.m: -------------------------------------------------------------------------------- 1 | %this m-file modified by Quan Quach on 12/12/07 2 | %email: quan.quach@gmail.com 3 | %Original Author: Steve Hoelzer 4 | function [stopBar] = progressbar(fractiondone, position) 5 | 6 | if(~exist('fractiondone')) 7 | return 8 | end 9 | % Description: 10 | % progressbar(fractiondone,position) provides an indication of the progress of 11 | % some task using graphics and text. Calling progressbar repeatedly will update 12 | % the figure and automatically estimate the amount of time remaining. 13 | % This implementation of progressbar is intended to be extremely simple to use 14 | % while providing a high quality user experience. 15 | % 16 | % Features: 17 | % - Can add progressbar to existing m-files with a single line of code. 18 | % - The figure closes automatically when the task is complete. 19 | % - Only one progressbar can exist so old figures don't clutter the desktop. 20 | % - Remaining time estimate is accurate even if the figure gets closed. 21 | % - Minimal execution time. Won't slow down code. 22 | % - Random color and position options. When a programmer gets bored.... 23 | % 24 | % Usage: 25 | % fractiondone specifies what fraction (0.0 - 1.0) of the task is complete. 26 | % Typically, the figure will be updated according to that value. However, if 27 | % fractiondone == 0.0, a new figure is created (an existing figure would be 28 | % closed first). If fractiondone == 1.0, the progressbar figure will close. 29 | % position determines where the progressbar figure appears on screen. This 30 | % argument only has an effect when a progress bar is first created or is reset 31 | % by calling with fractiondone = 0. The progress bar's position can be specifed 32 | % as follows: 33 | % [x, y] - Position of lower left corner in normalized units (0.0 - 1.0) 34 | % 0 - Centered (Default) 35 | % 1 - Upper right 36 | % 2 - Upper left 37 | % 3 - Lower left 38 | % 4 - Lower right 39 | % 5 - Random [x, y] position 40 | % The color of the progressbar is choosen randomly when it is created or 41 | % reset. Clicking inside the figure will cause a random color change. 42 | % For best results, call progressbar(0) (or just progressbar) before starting 43 | % a task. This sets the proper starting time to calculate time remaining. 44 | % 45 | % Example Function Calls: 46 | % progressbar(fractiondone,position) 47 | % progressbar % Initialize/reset 48 | % progressbar(0) % Initialize/reset 49 | % progressbar(0,4) % Initialize/reset and specify position 50 | % progressbar(0,[0.2 0.7]) % Initialize/reset and specify position 51 | % progressbar(0.5) % Update 52 | % progressbar(1) % Close 53 | % 54 | % Demo: 55 | % n = 1000; 56 | % progressbar % Create figure and set starting time 57 | % for i = 1:n 58 | % pause(0.01) % Do something important 59 | % progressbar(i/n) % Update figure 60 | % end 61 | % 62 | % Author: Steve Hoelzer 63 | % 64 | % Revisions: 65 | % 2002-Feb-27 Created function 66 | % 2002-Mar-19 Updated title text order 67 | % 2002-Apr-11 Use floor instead of round for percentdone 68 | % 2002-Jun-06 Updated for speed using patch (Thanks to waitbar.m) 69 | % 2002-Jun-19 Choose random patch color when a new figure is created 70 | % 2002-Jun-24 Click on bar or axes to choose new random color 71 | % 2002-Jun-27 Calc time left, reset progress bar when fractiondone == 0 72 | % 2002-Jun-28 Remove extraText var, add position var 73 | % 2002-Jul-18 fractiondone input is optional 74 | % 2002-Jul-19 Allow position to specify screen coordinates 75 | % 2002-Jul-22 Clear vars used in color change callback routine 76 | % 2002-Jul-29 Position input is always specified in pixels 77 | % 2002-Sep-09 Change order of title bar text 78 | % 2003-Jun-13 Change 'min' to 'm' because of built in function 'min' 79 | % 2003-Sep-08 Use callback for changing color instead of string 80 | % 2003-Sep-10 Use persistent vars for speed, modify titlebarstr 81 | % 2003-Sep-25 Correct titlebarstr for 0% case 82 | % 2003-Nov-25 Clear all persistent vars when percentdone = 100 83 | % 2004-Jan-22 Cleaner reset process, don't create figure if percentdone = 100 84 | % 2004-Jan-27 Handle incorrect position input 85 | % 2004-Feb-16 Minimum time interval between updates 86 | % 2004-Apr-01 Cleaner process of enforcing minimum time interval 87 | % 2004-Oct-08 Seperate function for timeleftstr, expand to include days 88 | % 2004-Oct-20 Efficient if-else structure for sec2timestr 89 | % 90 | stopBar = 0; 91 | persistent progfig progpatch starttime lastupdate firstIteration 92 | 93 | % Set defaults for variables not passed in 94 | if nargin < 1 95 | fractiondone = 0; 96 | end 97 | if nargin < 2 98 | position = 0; 99 | end 100 | 101 | try 102 | % Access progfig to see if it exists ('try' will fail if it doesn't) 103 | dummy = get(progfig,'UserData'); 104 | % If progress bar needs to be reset, close figure and set handle to empty 105 | if fractiondone == 0 106 | delete(progfig) % Close progress bar 107 | progfig = []; % Set to empty so a new progress bar is created 108 | end 109 | catch 110 | progfig = []; % Set to empty so a new progress bar is created 111 | end 112 | 113 | 114 | percentdone = floor(100*fractiondone); 115 | 116 | % Create new progress bar if needed 117 | 118 | if (isempty(progfig) && (isempty(firstIteration))) 119 | firstIteration = 1; 120 | % Calculate position of progress bar in normalized units 121 | scrsz = [0 0 1 1]; 122 | width = scrsz(3)/4; 123 | height = scrsz(4)/50; 124 | if (length(position) == 1) 125 | hpad = scrsz(3)/64; % Padding from left or right edge of screen 126 | vpad = scrsz(4)/24; % Padding from top or bottom edge of screen 127 | left = scrsz(3)/2 - width/2; % Default 128 | bottom = scrsz(4)/2 - height/2; % Default 129 | switch position 130 | case 0 % Center 131 | % Do nothing (default) 132 | case 1 % Top-right 133 | left = scrsz(3) - width - hpad; 134 | bottom = scrsz(4) - height - vpad; 135 | case 2 % Top-left 136 | left = hpad; 137 | bottom = scrsz(4) - height - vpad; 138 | case 3 % Bottom-left 139 | left = hpad; 140 | bottom = vpad; 141 | case 4 % Bottom-right 142 | left = scrsz(3) - width - hpad; 143 | bottom = vpad; 144 | case 5 % Random 145 | left = rand * (scrsz(3)-width); 146 | bottom = rand * (scrsz(4)-height); 147 | otherwise 148 | warning('position must be (0-5). Reset to 0.') 149 | end 150 | position = [left bottom]; 151 | elseif length(position) == 2 152 | % Error checking on position 153 | if (position(1) < 0) | (scrsz(3)-width < position(1)) 154 | position(1) = max(min(position(1),scrsz(3)-width),0); 155 | warning('Horizontal position adjusted to fit on screen.') 156 | end 157 | if (position(2) < 0) | (scrsz(4)-height < position(2)) 158 | position(2) = max(min(position(2),scrsz(4)-height),0); 159 | warning('Vertical position adjusted to fit on screen.') 160 | end 161 | else 162 | error('position is not formatted correctly') 163 | end 164 | 165 | % Initialize progress bar 166 | progfig = figure(... 167 | 'Units', 'normalized',... 168 | 'Position', [position width height],... 169 | 'NumberTitle', 'off',... 170 | 'Resize', 'off',... 171 | 'MenuBar', 'none',... 172 | 'BackingStore', 'off',... 173 | 'WindowStyle', 'modal'); 174 | progaxes = axes(... 175 | 'Position', [0.02 0.15 0.96 0.70],... 176 | 'XLim', [0 1],... 177 | 'YLim', [0 1],... 178 | 'Box', 'on',... 179 | 'ytick', [],... 180 | 'xtick', [] ); 181 | progpatch = patch(... 182 | 'XData', [0 0 0 0],... 183 | 'YData', [0 0 1 1],... 184 | 'EraseMode', 'none' ); 185 | 186 | % enable this code if you want the bar to change colors when the 187 | % user clicks on the progress bar 188 | % set(progfig, 'ButtonDownFcn',{@changecolor,progpatch}); 189 | % set(progaxes, 'ButtonDownFcn',{@changecolor,progpatch}); 190 | % set(progpatch,'ButtonDownFcn',{@changecolor,progpatch}); 191 | % changecolor(0,0,progpatch) 192 | 193 | set(progpatch,'FaceColor',[.1 1 .1]); 194 | 195 | % Set time of last update to ensure a redraw 196 | lastupdate = clock - 1; 197 | 198 | % Task starting time reference 199 | if isempty(starttime) | (fractiondone == 0) 200 | starttime = clock; 201 | end 202 | 203 | set(progfig,'CloseRequestFcn',@closeBar); 204 | 205 | end 206 | 207 | %if the user closes the progress bar during the data processing 208 | %then this will erase all the variables are return 1 to the output 209 | if (isempty(progfig) && ~(fractiondone==0)) 210 | delete(progfig) % Close progress bar 211 | 212 | % Clear persistent vars 213 | clear progfig progpatch starttime lastupdate firstIteration 214 | stopBar = 1; 215 | return 216 | 217 | end 218 | 219 | 220 | %Enforce a minimum time interval between updates 221 | %but allows for the case when the bar reaches 100% so that the user can see 222 | %it 223 | if (etime(clock,lastupdate) < 0.01 && ~(percentdone == 100)) 224 | return 225 | end 226 | 227 | % Update progress patch 228 | set(progpatch,'XData',[0 fractiondone fractiondone 0]) 229 | 230 | % Update progress figure title bar 231 | if (fractiondone == 0) 232 | titlebarstr = ' 0%'; 233 | else 234 | runtime = etime(clock,starttime); 235 | timeleft = runtime/fractiondone - runtime; 236 | timeleftstr = sec2timestr(timeleft); 237 | titlebarstr = sprintf('%2d%% %s remaining',percentdone,timeleftstr); 238 | end 239 | set(progfig,'Name',titlebarstr) 240 | 241 | % Force redraw to show changes 242 | drawnow 243 | 244 | % If task completed, close figure and clear vars, then exit 245 | 246 | if percentdone == 100 % Task completed 247 | delete(progfig) % Close progress bar 248 | %change the close request function back to normal 249 | % set(progfig,'CloseRequestFcn','closereq'); 250 | % Clear persistent vars 251 | clear progfig progpatch starttime lastupdate firstIteration 252 | return 253 | end 254 | % Record time of this update 255 | lastupdate = clock; 256 | 257 | %% 258 | % ------------------------------------------------------------------------------ 259 | function changecolor(h,e,progpatch) 260 | Change the color of the progress bar patch 261 | 262 | colorlim = 2.8; % Must be <= 3.0 - This keeps the color from being too light 263 | thiscolor = rand(1,3); 264 | while sum(thiscolor) > colorlim 265 | thiscolor = rand(1,3); 266 | end 267 | set(progpatch,'FaceColor',thiscolor); 268 | 269 | 270 | 271 | %% 272 | % ------------------------------------------------------------------------------ 273 | function timestr = sec2timestr(sec) 274 | % Convert a time measurement from seconds into a human readable string. 275 | 276 | % Convert seconds to other units 277 | d = floor(sec/86400); % Days 278 | sec = sec - d*86400; 279 | h = floor(sec/3600); % Hours 280 | sec = sec - h*3600; 281 | m = floor(sec/60); % Minutes 282 | sec = sec - m*60; 283 | s = floor(sec); % Seconds 284 | 285 | % Create time string 286 | if d > 0 287 | if d > 9 288 | timestr = sprintf('%d day',d); 289 | else 290 | timestr = sprintf('%d day, %d hr',d,h); 291 | end 292 | elseif h > 0 293 | if h > 9 294 | timestr = sprintf('%d hr',h); 295 | else 296 | timestr = sprintf('%d hr, %d min',h,m); 297 | end 298 | elseif m > 0 299 | if m > 9 300 | timestr = sprintf('%d min',m); 301 | else 302 | timestr = sprintf('%d min, %d sec',m,s); 303 | end 304 | else 305 | timestr = sprintf('%d sec',s); 306 | end 307 | 308 | %% 309 | function closeBar(src,evnt) 310 | 311 | selection = questdlg('Do you want to stop this process?',... 312 | 'Stop process',... 313 | 'Yes','No','Yes'); 314 | switch selection, 315 | case 'Yes', 316 | delete(gcf) 317 | case 'No' 318 | return 319 | end 320 | -------------------------------------------------------------------------------- /BayesianMatting/script.m: -------------------------------------------------------------------------------- 1 | 2 | % Demonstrates alpha matte calculation and composition with new background 3 | % Assumes the images folder is already extracted under the code 4 | % directory. 5 | % 6 | % Author: Michael Rubinstein 7 | 8 | im=imread('images/woman/input.png'); 9 | % trimap=imread('images/gandalf/trimap.png'); 10 | 11 | trimap=getTrimap(im); 12 | 13 | p=makeParameters; 14 | [F,B,alpha]=bayesmat(im,trimap,p); 15 | 16 | figure; 17 | imshow(im); 18 | title('Input'); 19 | 20 | figure; 21 | imshow(trimap); 22 | title('Trimap'); 23 | 24 | figure; 25 | imshow(alpha); 26 | title('Alpha'); 27 | 28 | Bnew=imread('images/gandalf/background-small.png'); 29 | figure; 30 | imshow(Bnew); 31 | title('New background'); 32 | 33 | C=makeComposite(F,Bnew,alpha); 34 | figure; 35 | imshow(C); 36 | title('Composite'); 37 | 38 | -------------------------------------------------------------------------------- /BayesianMatting/solve.m: -------------------------------------------------------------------------------- 1 | function [F,B,alpha]=solve(mu_F,Sigma_F,mu_B,Sigma_B,C,sigma_C,alpha_init,maxIter,minLike) 2 | 3 | % SOLVE Solves for F,B and alpha that maximize the sum of log 4 | % likelihoods at the given pixel C. 5 | % input: 6 | % mu_F - means of foreground clusters (for RGB, of size 3x#Fclusters) 7 | % Sigma_F - covariances of foreground clusters (for RGB, of size 8 | % 3x3x#Fclusters) 9 | % mu_B,Sigma_B - same for background clusters 10 | % C - observed pixel 11 | % alpha_init - initial value for alpha 12 | % maxIter - maximal number of iterations 13 | % minLike - minimal change in likelihood between consecutive iterations 14 | % 15 | % returns: 16 | % F,B,alpha - estimate of foreground, background and alpha 17 | % channel (for RGB, each of size 3x1) 18 | % 19 | 20 | I=eye(3); 21 | vals=[]; 22 | 23 | for i=1:size(mu_F,2) 24 | mu_Fi=mu_F(:,i); 25 | invSigma_Fi=inv(Sigma_F(:,:,i)); 26 | 27 | for j=1:size(mu_B,2) 28 | mubi=mu_B(:,j); 29 | invSigmabi=inv(Sigma_B(:,:,j)); 30 | 31 | alpha=alpha_init; 32 | iter=1; 33 | lastLike=-realmax; 34 | % z=[]; 35 | while (1) 36 | 37 | % solve for F,B 38 | A=[invSigma_Fi+I*(alpha^2/sigma_C^2) , I*alpha*(1-alpha)/sigma_C^2; 39 | I*((alpha*(1-alpha))/sigma_C^2) , invSigmabi+I*(1-alpha)^2/sigma_C^2]; 40 | 41 | b=[invSigma_Fi*mu_Fi+C*(alpha/sigma_C^2); 42 | invSigmabi*mubi+C*((1-alpha)/sigma_C^2)]; 43 | 44 | X=A\b; 45 | F=max(0,min(1,X(1:3))); 46 | B=max(0,min(1,X(4:6))); 47 | 48 | % solve for alpha 49 | alpha=max(0,min(1,((C-B)'*(F-B))/sum((F-B).^2))); 50 | 51 | % calculate likelihood 52 | L_C=-sum((C-alpha*F-(1-alpha)*B).^2)/sigma_C; 53 | L_F=-((F-mu_Fi)'*invSigma_Fi*(F-mu_Fi))/2; 54 | L_B=-((B-mubi)'*invSigmabi*(B-mubi))/2; 55 | like=L_C+L_F+L_B; 56 | 57 | % fprintf('like=%.2f, iter=%d\n',like,iter); 58 | % z(iter)=like; 59 | 60 | if iter>=maxIter | abs(like-lastLike)<=minLike 61 | break; 62 | end 63 | 64 | lastLike=like; 65 | iter=iter+1; 66 | end 67 | 68 | % we need only keep the maximal value, but for now we keep all 69 | % values anyway as there are not many, and we can investigate them 70 | % later on 71 | val.F=F; 72 | val.B=B; 73 | val.alpha=alpha; 74 | val.like=like; 75 | vals=[vals val]; 76 | end 77 | end 78 | 79 | % return maximum likelihood estimations 80 | [t,ind]=max([vals.like]); 81 | F=vals(ind).F; 82 | B=vals(ind).B; 83 | alpha=vals(ind).alpha; 84 | 85 | -------------------------------------------------------------------------------- /BayesianMatting/woman.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/BayesianMatting/woman.mat -------------------------------------------------------------------------------- /FCM/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FCM/3096.jpg -------------------------------------------------------------------------------- /FCM/distfcm.m: -------------------------------------------------------------------------------- 1 | function out = distfcm(center, data) 2 | %DISTFCM Distance measure in fuzzy c-mean clustering. 3 | % OUT = DISTFCM(CENTER, DATA) calculates the Euclidean distance 4 | % between each row in CENTER and each row in DATA, and returns a 5 | % distance matrix OUT of size M by N, where M and N are row 6 | % dimensions of CENTER and DATA, respectively, and OUT(I, J) is 7 | % the distance between CENTER(I,:) and DATA(J,:). 8 | % 9 | % See also FCMDEMO, INITFCM, IRISFCM, STEPFCM, and FCM. 10 | 11 | % Roger Jang, 11-22-94, 6-27-95. 12 | % Copyright 1994-2002 The MathWorks, Inc. 13 | 14 | out = zeros(size(center, 1), size(data, 1)); 15 | 16 | % fill the output matrix 17 | 18 | if size(center, 2) > 1, 19 | for k = 1:size(center, 1), 20 | out(k, :) = sqrt(sum(((data-ones(size(data, 1), 1)*center(k, :)).^2)')); 21 | end 22 | else % 1-D data 23 | for k = 1:size(center, 1), 24 | out(k, :) = abs(center(k)-data)'; 25 | end 26 | end 27 | -------------------------------------------------------------------------------- /FCM/fcm.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FCM/fcm.m -------------------------------------------------------------------------------- /FCM/fcm_stepfcm.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FCM/fcm_stepfcm.m -------------------------------------------------------------------------------- /FCM/main_fcm.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FCM/main_fcm.m -------------------------------------------------------------------------------- /FRFCM_Leitao/2018TFS_FRFCM.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FRFCM_Leitao/2018TFS_FRFCM.pdf -------------------------------------------------------------------------------- /FRFCM_Leitao/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FRFCM_Leitao/3096.jpg -------------------------------------------------------------------------------- /FRFCM_Leitao/FRFCM.m: -------------------------------------------------------------------------------- 1 | function [center, U, obj_U, iter_n]=FRFCM(data,cluster_n,diameter,w_size) 2 | % Firstly, we use morphological reconstruction to reconstruct original image to suppress noise; 3 | % Secondly, we use histogram to reduce the computational complexity of FCM; 4 | % Thirdly, we use a median filter to smooth the fuzzy membership U; 5 | % Finally, we normalize U; 6 | % Input variants and parameters 7 | % data is a 2D matrix of size row*col, it means that the input is a gray image 8 | % cluster_n denotes the number of cluster centers 9 | % diameter denotes the parameter of structuring element used in 10 | % mrophological recosntruction 11 | % w_size is the scale of the filtering window 12 | 13 | if nargin ~= 4 14 | error('Too many or too few input arguments!'); 15 | end 16 | % Change the following to set default options 17 | options = [2; % exponent for the partition matrix 18 | 100; % max. number of iteration 19 | 1e-5; % min. amount of improvement 20 | 1]; % info display during iteration 21 | expo = options(1); % Exponent for U 22 | max_iter = options(2); % Max. iteration 23 | obj_U = zeros(max_iter, 1); % Array for objective function 24 | %% step 1, morphological reconstruction 25 | data=w_recons_CO(data,strel('square',diameter)); 26 | %% step 2, FCM on histogram 27 | row=size(data, 1);col=size(data,2); 28 | data_n = row*col; % the number of pixels 29 | data=data(:); 30 | data_u=unique(data(:));% computing the histogram 31 | n_r=size(data_u,1); % n_r denotes the number of pixels with different gray value 32 | U=initfcm(cluster_n,n_r); % Initial fuzzy partition 33 | sum_U{1}=double(U>0.5);sum_U{2}=sum_U{1}; 34 | % computing histogram 35 | N_p=zeros(length(data_u),1); 36 | for i=1:length(data_u) 37 | N_p(i)=sum(data==data_u(i)); 38 | end 39 | Num=ones(cluster_n,1)*N_p'; 40 | %% main loop 41 | dist=zeros(cluster_n,n_r);dist2=zeros(cluster_n,data_n); 42 | for w= 1:max_iter 43 | mf = Num.*(U.^expo); 44 | center = mf*data_u./((ones(size(data, 2), 1)*sum(mf'))'); 45 | for k=1: size(center, 1) 46 | dist(k, :)=abs(center(k)-data_u)'; 47 | end 48 | tmp=dist.^2; 49 | h1=(tmp+eps).^(-1/(expo-1)); 50 | U=(h1)./(ones(cluster_n,1)*(sum(h1))+eps); 51 | if w>2 52 | sum_U{w}=double(U>0.5); 53 | obj_U(w)=sum(sum(abs(sum_U{w}-sum_U{w-1}))); 54 | if obj_U(w)==0,break; 55 | end 56 | end 57 | end 58 | iter_n = w; % Actual number of iterations 59 | %% compute membership matrix U according to cluster centers 60 | for k2=1: size(center, 1) 61 | dist2(k2, :)=abs(center(k2)-data)'; 62 | end 63 | tmp =dist2+eps; 64 | h1=(tmp).^(-1/(expo-1)); 65 | U=(h1)./(ones(cluster_n,1)*(sum(h1))+eps); 66 | %% median filtering 67 | for k3=1: size(center, 1) 68 | U1= U (k3,:); 69 | U1=reshape(U1,[row,col]); %reshape the vector U to a matrix of size row*col 70 | UU=medfilt2(U1,[w_size,w_size]); % Notice that we cann't use U1.^expo due to the high computational complexity 71 | GG(k3,:)=UU(:); 72 | end 73 | U=GG./(ones(cluster_n,1)*(sum(GG))+eps); % the normalization 74 | -------------------------------------------------------------------------------- /FRFCM_Leitao/FRFCM_c.m: -------------------------------------------------------------------------------- 1 | function [center, U, obj_fcn,iter_n]=FRFCM_c(data,cluster_n,radius,w_size,options) 2 | % Firstly, we use multivariate morphological reconstruction to reconstruct original image to suppress noise; 3 | % Secondly, we implement FCM; 4 | % Thirdly, we use a median filter to smooth the fuzzy membership U; 5 | % Finally, we normalize U; 6 | % Input variants and parameters 7 | % data is a 3D data, it means that the input is a color image 8 | % cluster_n denotes the number of cluster centers 9 | % radius denotes the parameter of structuring element used in 10 | % mrophological recosntruction 11 | % w_size is the scale of the filtering window 12 | 13 | if nargin ~= 4 & nargin ~= 5 14 | error('Too many or too few input arguments!'); 15 | end 16 | % Change the following to set default options 17 | default_options = [2; % exponent for the partition matrix U 18 | 100; % max. number of iteration 19 | 1e-5; % min. amount of improvement 20 | 0]; % info display during iteration 21 | 22 | if nargin == 4, 23 | options = default_options; 24 | else 25 | % If "options" is not fully specified, pad it with default values. 26 | if length(options) < 4, 27 | tmp = default_options; 28 | tmp(1:length(options)) = options; 29 | options = tmp; 30 | end 31 | % If some entries of "options" are nan's, replace them with defaults. 32 | nan_index = find(isnan(options)==1); 33 | options(nan_index) = default_options(nan_index); 34 | if options(1) <= 1, 35 | error('The exponent should be greater than 1!'); 36 | end 37 | end 38 | expo = options(1); % Exponent for U 39 | max_iter = options(2); % Max. iteration 40 | min_impro = options(3); % Min. improvement 41 | display = options(4); % Display info or not 42 | obj_fcn = zeros(max_iter, 1); % Array for objective function 43 | %% step 1, morphological reconstruction 44 | data_rgb=w_ColorRecons_CO(data,radius); %radius means maximal radius 45 | data_lab=colorspace('Lab<-RGB',data_rgb); 46 | %% step 2, FCM on histogram 47 | data_l=data_lab(:,:,1);data_a=data_lab(:,:,2);data_b=data_lab(:,:,3); 48 | data=[data_l(:)';data_a(:)';data_b(:)']'; 49 | %iter_n=0; % actual number of iteration 50 | row=size(data_a,1);col=size(data_a,2); 51 | U = initfcm(cluster_n, row*col); % Initial fuzzy partition 52 | % Main loop 53 | for i = 1:max_iter 54 | %% stepfcm [U, center, obj_fcn(i)] = stepfcm(data, U, cluster_n, expo); 55 | mf = U.^expo; % MF matrix after exponential modification 56 | center = mf*data./((ones(size(data, 2), 1)*sum(mf'))'); % new center 57 | %% dist = distfcm(center, data); % fill the distance matrix 58 | out = zeros(size(center, 1), size(data, 1)); 59 | % fill the output matrix 60 | if size(center, 2) > 1, 61 | for k = 1:size(center, 1), 62 | out(k, :) = sqrt(sum(((data-ones(size(data, 1), 1)*center(k, :)).^2)')); 63 | end 64 | else % 1-D data 65 | for k = 1:size(center, 1), 66 | out(k, :) = abs(center(k)-data)'; 67 | end 68 | end 69 | dist=out+eps; 70 | %% distfcm end 71 | obj_fcn(i) = sum(sum((dist.^2).*mf)); % objective function 72 | tmp = dist.^(-2/(expo-1)); % calculate new U, suppose expo != 1 73 | U = tmp./(ones(cluster_n, 1)*sum(tmp)+eps); 74 | Uc{i}=U; 75 | if i > 1, 76 | %if abs(obj_fcn(i) - obj_fcn(i-1))/obj_fcn(i) < min_impro, break; end, 77 | if max(max(abs(Uc{i}-Uc{i-1})))< min_impro,break; end, 78 | end 79 | end 80 | iter_n = i; % Actual number of iterations 81 | obj_fcn(iter_n+1:max_iter) = []; 82 | %% median filtering 83 | for k3=1: size(center, 1) 84 | U1= U (k3,:); 85 | U1=reshape(U1,[row,col]); %reshape the vector U to a matrix of size row*col 86 | UU=medfilt2(U1,[w_size,w_size]); % Notice, we cann't use U1.^expo due to the problem of high computational complexity 87 | GG(k3,:)=UU(:); 88 | end 89 | U=GG./(ones(cluster_n,1)*(sum(GG))+eps); % the normalization of 90 | center_l=center(:,1);center_a=center(:,2);center_b=center(:,3);center_lab=cat(3,center_l,center_a,center_b); 91 | center=255*colorspace('RGB<-Lab',center_lab); 92 | -------------------------------------------------------------------------------- /FRFCM_Leitao/Label_image.m: -------------------------------------------------------------------------------- 1 | function [fs,center_p,Num_p,center_lab]=Label_image(f,L) 2 | %fs is the result of segmentation, center_p is the center pixel of each 3 | %areas 4 | % f is the original image 5 | % L is the segmented image using waterhsed transformation 6 | f=double(f); 7 | num_area=max(max(L)); %The number of segmented areas 8 | Num_p=zeros(num_area,1); 9 | if size(f,3)<2 10 | [M,N]=size(f); 11 | s3=L; 12 | fs=zeros(M,N); 13 | center_p=zeros(num_area,1); 14 | for i=1:num_area 15 | f2=f(s3==i);f_med=median(f2);fx=double((s3==i))*double(f_med); 16 | fs=fs+fx; 17 | center_p(i,:)=uint8(f_med); 18 | Num_p=zeros(num_area,1); 19 | end 20 | fs=uint8(fs); 21 | %% Color image 22 | else 23 | [M,N]=size(f(:,:,1)); 24 | s3=L; 25 | fs=zeros(M,N,3); 26 | fr=f(:,:,1);fg=f(:,:,2);fb=f(:,:,3); 27 | center_p=zeros(num_area,3); 28 | for i=1:num_area 29 | fr2=fr(s3==i);r_med=median(fr2);r=(s3==i)*r_med; 30 | fg2=fg(s3==i);g_med=median(fg2);g=(s3==i)*g_med; 31 | fb2=fb(s3==i);b_med=median(fb2);b=(s3==i)*b_med; 32 | fs=fs+cat(3,r,g,b); 33 | center_p(i,:)=uint8([r_med g_med b_med]); 34 | Num_p(i)=sum(sum(s3==i)); 35 | end 36 | fs=uint8(fs); 37 | end 38 | TT=cat(3,center_p(:,1),center_p(:,2),center_p(:,3)); 39 | TT2=colorspace('Lab<-RGB',TT); 40 | TT2r=TT2(:,:,1);TT2g=TT2(:,:,2);TT2b=TT2(:,:,3); 41 | center_lab(:,1)=TT2r(:);center_lab(:,2)=TT2g(:);center_lab(:,3)=TT2b(:); -------------------------------------------------------------------------------- /FRFCM_Leitao/PCA_color.m: -------------------------------------------------------------------------------- 1 | function g=PCA_color(f) 2 | f1=f(:,:,1);f2=f(:,:,2);f3=f(:,:,3); 3 | data=double([f1(:)';f2(:)';f3(:)']); 4 | [~,c]=size(data); 5 | m=mean(data')'; 6 | d=data-repmat(m,1,c); 7 | % Compute the covariance matrix (co) 8 | co=d*d'; 9 | % Compute the eigen values and eigen vectors of the covariance matrix 10 | [eigvector,eigvl]=eig(co); 11 | % Sort the eigen vectors according to the eigen values 12 | eigvalue = diag(eigvl); 13 | [~, index] = sort(-eigvalue); 14 | eigvalue = eigvalue(index); 15 | eigvector = eigvector(:, index); 16 | % Compute the number of eigen values that greater than zero (you can select any threshold) 17 | count1=0; 18 | for i=1:size(eigvalue,1) 19 | if(eigvalue(i)>0) 20 | count1=count1+1; 21 | end 22 | end 23 | % We can use all the eigen vectors but this method will increase the 24 | % computation time and complixity 25 | %vec=eigvector(:,:); 26 | 27 | % And also we can use the eigen vectors that the corresponding eigen values is greater than zero(Threshold) and this method will decrease the 28 | % computation time and complixity 29 | vec=eigvector(:,1:count1); 30 | % Compute the feature matrix (the space that will use it to project the testing image on it) 31 | x=vec'*d; 32 | x2=x+repmat(m,1,c); 33 | x2=uint8(x2); 34 | x2_1=x2(1,:);x2_2=x2(2,:);x2_3=x2(3,:); 35 | s1=size(f1,1);s2=size(f1,2); 36 | f_1=zeros(s1, s2);f_2=f_1;f_3=f_1; 37 | for j=1:s2 38 | f_1(:,j)=x2_1((j-1)*s1+1:j*s1); 39 | f_2(:,j)=x2_2((j-1)*s1+1:j*s1); 40 | f_3(:,j)=x2_3((j-1)*s1+1:j*s1); 41 | end 42 | g=cat(3,uint8(f_1),uint8(f_2),uint8(f_3)); 43 | -------------------------------------------------------------------------------- /FRFCM_Leitao/Readme.txt: -------------------------------------------------------------------------------- 1 | 2 | Please cite the paper 3 | 4 | T. Lei, X. Jia, Y. Zhang, L. He, H. Meng and A. K. Nandi, "Significantly Fast and Robust Fuzzy C-Means Clustering Algorithm Based on Morphological Reconstruction and Membership Filtering," in IEEE Transactions on Fuzzy Systems, vol. PP, no. 99, pp. 1-1.doi: 10.1109/TFUZZ.2018.2796074 5 | 6 | Full paper link: http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8265186 7 | 8 | 1. If you want to segment a gray image, please run main_gray. 9 | 2. If you want to segment a color image, please run main_color. -------------------------------------------------------------------------------- /FRFCM_Leitao/VOI_h.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FRFCM_Leitao/VOI_h.m -------------------------------------------------------------------------------- /FRFCM_Leitao/V_pcpe.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FRFCM_Leitao/V_pcpe.m -------------------------------------------------------------------------------- /FRFCM_Leitao/centerMVP.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FRFCM_Leitao/centerMVP.m -------------------------------------------------------------------------------- /FRFCM_Leitao/fcm_image.m: -------------------------------------------------------------------------------- 1 | % This function is only suitabe for gray image 2 | function imput_ff=fcm_image(f,U,center) 3 | [m,n]=size(f); 4 | [~,idx_f]=max(U); 5 | imput_f=reshape(idx_f,[m n]); 6 | imput_ff=zeros(m,n); %input_ff denotes the classification result based on the cluster center 7 | for k=1:length(center(:,1)) 8 | t=(imput_f==k).*center(k); 9 | imput_ff=imput_ff+t; 10 | end 11 | 12 | -------------------------------------------------------------------------------- /FRFCM_Leitao/fcm_image_color.m: -------------------------------------------------------------------------------- 1 | % This function is only suitabe for color image 2 | function gx=fcm_image_color(f,U) 3 | m=size(f,1);n=size(f,2); 4 | U=U'; 5 | idx_f=zeros(m*n,1); 6 | for i=1:m*n 7 | x=U(i,:); 8 | idx=find(x==max(x)); % Computing the classification index of matrix weighted 9 | idx=idx(1); 10 | idx_f(i)=idx; %idx_f denotes the classification image based on index 11 | end 12 | imput_f=reshape(idx_f,[m n]); 13 | gx=Label_image(f,imput_f); 14 | 15 | 16 | -------------------------------------------------------------------------------- /FRFCM_Leitao/main_color.m: -------------------------------------------------------------------------------- 1 | % Please cite the paper "Tao Lei, Xiaohong Jia, Yanning Zhang, Lifeng He, Hongying Meng and Asoke K. Nandi, Significantly Fast and Robust 2 | % Fuzzy C-Means Clustering Algorithm Based on Morphological Reconstruction and Membership Filtering, IEEE Transactions on Fuzzy Systems, 3 | % DOI: 10.1109/TFUZZ.2018.2796074, 2018.2018" 4 | %and 5 | %Tao. Lei, Yanning Zhang, Yi Wang, Shigang Liu, and Zhe Guo, "A Conditionally Invariant Mathematical Morphological Framework for Color Images," 6 | %Information Sciences, Vol. 387, no. 5, pp. 34-52, May. 2017. 7 | 8 | % The first paper is OpenAccess and you can download the paper freely from "http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8265186." 9 | % The code was written by Tao Lei in 2017. 10 | % If you have any problems, please contact me. 11 | % Email address: leitao@sust.edu.cn 12 | 13 | clc 14 | close all 15 | clear all 16 | %% parameters 17 | cluster=3; % the number of clustering centers 18 | se=3; % the parameter of structuing element used for morphological reconstruction 19 | w_size=3; % the size of fitlering window 20 | %% test a color image 21 | fileID='12003'; 22 | f_ori=imread('12003.jpg'); 23 | GT=load('12003.mat'); % Ground Truth, download from 'https://www2.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/resources.html' 24 | f_ori=double(f_ori); 25 | %% implement the proposed algorithm 26 | tic 27 | [~,U1,~,~]=FRFCM_c(double(f_ori),cluster,se,w_size); 28 | Time1=toc; 29 | disp(strcat('running time is: ',num2str(Time1))) 30 | f_ori; 31 | f_seg=fcm_image_color(f_ori,U1); 32 | imshow(f_seg); 33 | -------------------------------------------------------------------------------- /FRFCM_Leitao/main_gray.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FRFCM_Leitao/main_gray.m -------------------------------------------------------------------------------- /FRFCM_Leitao/renumber.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/FRFCM_Leitao/renumber.m -------------------------------------------------------------------------------- /FRFCM_Leitao/w_ColorRecons_CO.m: -------------------------------------------------------------------------------- 1 | function output_f=w_ColorRecons_CO(f,radius) 2 | se=strel('disk',radius); 3 | if length(size(f))<3 4 | disp('Please input a color image!'); 5 | else 6 | %% 7 | f=double(f);f_r=f(:,:,1);f_g=f(:,:,2);f_b=f(:,:,3); 8 | f_pca=double(PCA_color(f));f1=f_pca(:,:,1);f2=f_pca(:,:,2); 9 | %% step2 data transformation 10 | data1=f1*10^3+f2+f_r*10^-3+f_g*10^-6+f_b*10^-9;Max1=max(max(data1)); 11 | data2=f1*10^3+f2+f_g*10^-3+f_r*10^-6+f_b*10^-9;Max2=max(max(data2)); 12 | data3=f1*10^3+f2+f_b*10^-3+f_r*10^-6+f_g*10^-9;Max3=max(max(data3)); 13 | %% step 3 data processing 14 | imput_data1=imerode(data1,se); 15 | imput_data2=imerode(data2,se); 16 | imput_data3=imerode(data3,se); 17 | f_rec1=imreconstruct(imput_data1,data1); 18 | f_rec2=imreconstruct(imput_data2,data2); 19 | f_rec3=imreconstruct(imput_data3,data3); 20 | imput2_data1=imerode(Max1-f_rec1,se); 21 | imput2_data2=imerode(Max2-f_rec2,se); 22 | imput2_data3=imerode(Max3-f_rec3,se); 23 | f_g1=Max1-imreconstruct(imput2_data1,Max1-f_rec1); 24 | f_g2=Max2-imreconstruct(imput2_data2,Max2-f_rec2); 25 | f_g3=Max3-imreconstruct(imput2_data3,Max3-f_rec3); 26 | end 27 | %% return to RGB format 28 | tt1=f_g1-floor(f_g1); 29 | tt2=f_g2-floor(f_g2); 30 | tt3=f_g3-floor(f_g3); 31 | g1_r=floor(tt1*10^3); 32 | g1_g=floor(tt2*10^3); 33 | g1_b=floor(tt3*10^3); 34 | output_f=cat(3,uint8(g1_r),uint8(g1_g),uint8(g1_b)); 35 | -------------------------------------------------------------------------------- /FRFCM_Leitao/w_recons_CO.m: -------------------------------------------------------------------------------- 1 | % morphological closing reconstruction 2 | function fobrcbr=w_recons_CO(f,se) 3 | fe=imerode(f,se); 4 | fobr=imreconstruct(fe,f); 5 | fobrc=imcomplement(fobr); 6 | fobrce=imerode(fobrc,se); 7 | fobrcbr=imcomplement(imreconstruct(fobrce,fobrc)); 8 | 9 | -------------------------------------------------------------------------------- /IFCM/1.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/1.tiff -------------------------------------------------------------------------------- /IFCM/124084.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/124084.jpg -------------------------------------------------------------------------------- /IFCM/2..tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/2..tiff -------------------------------------------------------------------------------- /IFCM/3.1..tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/3.1..tiff -------------------------------------------------------------------------------- /IFCM/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/3096.jpg -------------------------------------------------------------------------------- /IFCM/distifcmMVP.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/distifcmMVP.m -------------------------------------------------------------------------------- /IFCM/ifcm.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/ifcm.m -------------------------------------------------------------------------------- /IFCM/ifcm_step.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/ifcm_step.m -------------------------------------------------------------------------------- /IFCM/initifcmmvp.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/initifcmmvp.m -------------------------------------------------------------------------------- /IFCM/initifcmv.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/initifcmv.m -------------------------------------------------------------------------------- /IFCM/main_IFCM.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFCM/main_IFCM.m -------------------------------------------------------------------------------- /IFFCM/1.1.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/1.1.tiff -------------------------------------------------------------------------------- /IFFCM/1.2.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/1.2.tiff -------------------------------------------------------------------------------- /IFFCM/3.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/3.tiff -------------------------------------------------------------------------------- /IFFCM/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/3096.jpg -------------------------------------------------------------------------------- /IFFCM/compute_mean_median.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/compute_mean_median.m -------------------------------------------------------------------------------- /IFFCM/datahistprocess.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/datahistprocess.m -------------------------------------------------------------------------------- /IFFCM/distffcm.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/distffcm.m -------------------------------------------------------------------------------- /IFFCM/iffcm.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/iffcm.m -------------------------------------------------------------------------------- /IFFCM/iffcm_step.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/iffcm_step.m -------------------------------------------------------------------------------- /IFFCM/initifcmv.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/initifcmv.m -------------------------------------------------------------------------------- /IFFCM/main_FFCM.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/main_FFCM.m -------------------------------------------------------------------------------- /IFFCM/u_return.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/IFFCM/u_return.m -------------------------------------------------------------------------------- /JSEG/124084.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/JSEG/124084.jpg -------------------------------------------------------------------------------- /JSEG/Borsotti.m: -------------------------------------------------------------------------------- 1 | % this function is used to evaluate the image segmentation results. 2 | 3 | % input: Im -- original image 4 | % CMap -- class map 5 | % output: value indicate the evaluation 6 | % by Qinpei zhao 7 | 8 | function Score = Borsotti(Im, CMap) 9 | % image property 10 | [Ih, Iw, d] = size(Im); 11 | SI = Ih*Iw; 12 | % segmentation no. 13 | Rn = max(CMap(:)); 14 | 15 | % within cluster 16 | Rmean = zeros(Rn, d); 17 | color_err = zeros(1, Rn); 18 | Area = zeros(1, Rn); 19 | for j = 1:Rn, 20 | Area(j) = length(find(CMap == j)); 21 | end 22 | % N(x) -- the number of regions have area x (stupid way to calculate) 23 | for x = 1:Rn, 24 | Nx(x) = length(find(Area == Area(x))); 25 | end 26 | 27 | % for each region 28 | for i = 1:Rn, 29 | sqerr = 0; 30 | sq = find(CMap == i); 31 | Si = Area(i); 32 | 33 | for dim = 1:d, 34 | Ri = zeros(Ih, Iw); 35 | Aver_id = zeros(Ih, Iw); 36 | temp1 = Im(:,:,dim); 37 | Ri(sq) = temp1(sq); 38 | % Aver_id -- average value 39 | Aver_id(sq) = sum(Ri(:))/Si; 40 | Rmean(i,dim) = sum(Ri(:))/Si; 41 | % squared color error 42 | sqerr = sqerr + sum(sum((Ri - Aver_id).^2)); 43 | end 44 | color_err(i) = sqerr / (1+log(Si)) + (Nx(i)/Si)^2; 45 | end 46 | within_err = 1/(1000*SI)*sqrt(Rn)*sum(color_err); 47 | 48 | Score = within_err; 49 | 50 | -------------------------------------------------------------------------------- /JSEG/DrawLine.m: -------------------------------------------------------------------------------- 1 | function DrawLine(SegI) 2 | % input: SegI --- Segments with segment labels 3 | % output: ImgS --- Segments with line boundaries 4 | 5 | [m, n] = size(SegI); 6 | ImgS = zeros(m, n); 7 | % RGB = label2rgb(SegI); 8 | % figure; imshow(RGB); 9 | % hold on; 10 | BRegion = imdilate(SegI, [0 1 0; 1 1 1; 0 1 0]); 11 | Boundary = BRegion & ~SegI; 12 | 13 | 14 | for i = 1:max(SegI(:)), 15 | S = zeros(m, n); 16 | [x, y] = find(SegI == i); 17 | for j = 1:length(x), 18 | S(x(j), y(j)) = 1; 19 | end 20 | [B,L] = bwboundaries(S,'noholes'); 21 | for k = 1:length(B) 22 | boundary = B{k}; 23 | plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 1); 24 | end 25 | ImgS = ImgS + S; 26 | end 27 | 28 | -------------------------------------------------------------------------------- /JSEG/EVisible.m: -------------------------------------------------------------------------------- 1 | % this function is used to evaluate the image segmentation results. 2 | % H.C. Chen, S.J. Wang. The use of visible color difference in the 3 | % quantitative evaluation of color image segmentation, in: Proceedings of 4 | % ICASSP, 2004 5 | % input: Im -- original image 6 | % CMap -- class map 7 | % output: value indicate the evaluation 8 | % inter-intra region visual error 9 | % NB: design for CIE l*a*b color space 10 | % by Qinpei zhao 11 | 12 | function [Eintra, Einter] = EVisible(Im, CMap, th) 13 | 14 | % image property 15 | [Ih, Iw, d] = size(Im); 16 | % segmentation no. 17 | Rn = max(CMap(:)); 18 | 19 | % segmented image with average color of that region 20 | Seg = zeros(Ih, Iw, d); 21 | Rmean = zeros(Rn, d); 22 | % for each region 23 | for i = 1:Rn, 24 | sq = find(CMap == i); 25 | Si = length(sq); 26 | for dim = 1:d, 27 | Aver_id = zeros(Ih, Iw); 28 | Ri = zeros(Ih, Iw); 29 | temp1 = Im(:,:,dim); 30 | Ri(sq) = temp1(sq); 31 | Aver_id(sq) = sum(Ri(:))/Si; 32 | Rmean(i,dim) = sum(Ri(:))/Si; 33 | Ri(sq) = Aver_id(sq); 34 | Seg(:,:,dim) = Seg(:,:,dim) + Ri; 35 | end 36 | end 37 | 38 | % intra-region error 39 | Diff = zeros(Ih, Iw, d); 40 | Diff = double(Im) - Seg; 41 | Diff = sqrt(Diff(:,:,1).^2 + Diff(:,:,2).^2 + Diff(:,:,3).^2); 42 | th1 = repmat(th, Ih, Iw); 43 | Eintra = length(find((Diff-th1)>0))/(Ih*Iw); 44 | 45 | % inter-region error 46 | E_diff = zeros(1, Rn*(Rn-1)/2); 47 | E_diff(th-sqrt(pdist(Rmean))>0) = 1; 48 | wts = []; 49 | for t = 1:Rn, 50 | for s = t+1:Rn, 51 | R1 = zeros(Ih, Iw); 52 | sq1 = find(CMap == t); 53 | R1(sq1) = t; 54 | BRegion1 = imdilate(R1, [0 1 0; 1 1 1; 0 1 0]); 55 | Boundary1 = BRegion1 & ~R1; 56 | R2 = zeros(Ih, Iw); 57 | sq2 = find(CMap == s); 58 | R2(sq2) = s; 59 | BRegion2 = imdilate(R2, [0 1 0; 1 1 1; 0 1 0]); 60 | Boundary2 = BRegion2 & ~R2; 61 | R = R1 + R2; 62 | BRegion = imdilate(R, [0 1 0; 1 1 1; 0 1 0]); 63 | Boundary = BRegion & ~R; 64 | Bw = Boundary1+Boundary2-Boundary; 65 | Bw = bwmorph(Bw, 'thin'); 66 | wts = [wts length(find(Bw))]; 67 | end 68 | end 69 | 70 | C = 1/6; 71 | Einter = sum(wts.*E_diff)/(C*Ih*Iw); 72 | 73 | 74 | -------------------------------------------------------------------------------- /JSEG/Evaluation.m: -------------------------------------------------------------------------------- 1 | % clear all 2 | clc 3 | 4 | filename = ['124084']; 5 | image_org = imread(filename); 6 | [m,n,d] = size(image_org); 7 | % figure; imshow(image_org); 8 | 9 | % class_map from clustering algorithms 10 | pa_filename = ['woman6.pa']; 11 | PA = load(pa_filename); 12 | if length(PA) == m*n %&& length(find(PA==0))~=0, 13 | map = reshape(PA, m, n); 14 | map = map+1; 15 | else 16 | fprintf('something wrong!!\n'); 17 | end 18 | 19 | % % generate J images 20 | % for w = 1:4, 21 | % W = GenerateWindow(w); 22 | % JI = JImage(map, W); 23 | % save([num2str(w) '.mat'], 'JI'); 24 | % % imwrite(JI, ['JImage' num2str(w) '.jpg']); 25 | % end 26 | 27 | 28 | load('4.mat'); 29 | JI4 = JI; 30 | load('3.mat'); 31 | JI3 = JI; 32 | load('2.mat'); 33 | JI2 = JI; 34 | load('1.mat'); 35 | JI1 = JI; 36 | 37 | % quantized image 38 | ImgQ = class2Img(map, image_org); 39 | 40 | Region = zeros(m, n); 41 | % --------------------scale 4-------------------- 42 | % scale 4 43 | u = mean(JI4(:)); 44 | s = std(JI4(:)); 45 | Region = ValleyD(JI4, 4, u, s); % 4.1 Valley Determination 46 | Region = ValleyG1(JI4, Region); % 4.2.2 Growing 47 | Region = ValleyG1(JI3, Region); % 4.2.3 Growing at next smaller scale 48 | Region = ValleyG2(JI1, Region); % 4.2.4 remaining pixels at the smallest scale 49 | Region4 = Region; 50 | fprintf('scale4: %d\n', max(Region(:))); 51 | % draw segments 52 | figure; imshow(uint8(ImgQ)); 53 | hold on; 54 | DrawLine(Region); 55 | hold off; 56 | % --------------------scale 3-------------------- 57 | w = 3; 58 | Region = SpatialSeg(JI3, Region, w); 59 | % Valley Growing at the next smaller scale level 60 | Region = ValleyG1(JI2, Region); 61 | % Valley Growing at the smallest scale level 62 | Region = ValleyG2(JI1, Region); 63 | Region3 = Region; 64 | fprintf('scale3: %d\n', max(Region(:))); 65 | figure; imshow(uint8(ImgQ)); 66 | hold on; 67 | DrawLine(Region); 68 | hold off; 69 | % --------------------scale 2-------------------- 70 | % SpatialSeg includes one ValleyD and ValleyG1 at current scale level 71 | w = 2; 72 | Region = SpatialSeg(JI2, Region, w); 73 | % Valley Growing at the next smaller scale level 74 | Region = ValleyG1(JI1, Region); 75 | % Valley Growing at the smallest scale level 76 | Region = ValleyG2(JI1, Region); 77 | Region2 = Region; 78 | fprintf('scale2: %d\n', max(Region(:))); 79 | figure; imshow(uint8(ImgQ)); 80 | hold on; 81 | DrawLine(Region); 82 | hold off; 83 | 84 | % % % % % % --------------------scale 1-------------------- 85 | w = 1; 86 | Region = SpatialSeg(JI1, Region, w); 87 | Region = ValleyG2(JI1, Region); 88 | Region1 = Region; 89 | fprintf('scale1: %d\n', max(Region(:))); 90 | figure; imshow(uint8(ImgQ)); 91 | hold on; 92 | DrawLine(Region); 93 | hold off; 94 | 95 | % determining the number of segments 96 | index = []; 97 | for t = 2:10, 98 | Region0 = RegionMerge_RGB(image_org, map, Region, t); 99 | [Einter, Eintra, Score] = Fratio(image_org, Region0); 100 | index = [index; Score]; 101 | end 102 | 103 | % plot the "optimal" segmentation 104 | [seg_no index_value] = min[index]; 105 | seg_no = seg_no + 1; 106 | Region0 = RegionMerge_RGB(image_org, map, Region, seg_no); 107 | figure; imshow(uint8(ImgQ)); 108 | hold on; 109 | DrawLine(Region0); 110 | hold off; 111 | 112 | -------------------------------------------------------------------------------- /JSEG/Fratio.m: -------------------------------------------------------------------------------- 1 | % this function is used to evaluate the image segmentation results. 2 | % F-ratio: between and within segments 3 | % input: Im -- original image 4 | % CMap -- class map 5 | % output: value indicate the evaluation 6 | % by Qinpei zhao 7 | 8 | function [Einter, Eintra, Score] = Fratio(Im, CMap) 9 | 10 | % image property 11 | [Ih, Iw, d] = size(Im); 12 | % segmentation no. 13 | Rn = max(CMap(:)); 14 | % image average 15 | for dd = 1:d, 16 | Channel = Im(:,:,dd); 17 | Imean(1,dd) = mean(Channel(:)); 18 | end 19 | 20 | % segmented image with average color of that region 21 | Seg = zeros(Ih, Iw, d); 22 | Einter = 0; 23 | % for each region 24 | for i = 1:Rn, 25 | sq = find(CMap == i); 26 | Si = length(sq); 27 | for dim = 1:d, 28 | Aver_id = zeros(Ih, Iw); 29 | Ri = zeros(Ih, Iw); 30 | temp1 = Im(:,:,dim); 31 | Ri(sq) = temp1(sq); 32 | Aver_id(sq) = sum(Ri(:))/Si; 33 | Rmean(1,dim) = sum(Ri(:))/Si; 34 | Ri(sq) = Aver_id(sq); 35 | Seg(:,:,dim) = Seg(:,:,dim) + Ri; 36 | end 37 | dist = sum((Rmean-Imean).^2) *Si; 38 | Einter = Einter + dist; 39 | end 40 | Einter = Einter/(Ih*Iw); 41 | 42 | % intra-region error 43 | Diff = zeros(Ih, Iw, d); 44 | Diff = double(Im) - Seg; 45 | Diff = Diff(:,:,1).^2 + Diff(:,:,2).^2 + Diff(:,:,3).^2; 46 | 47 | Eintra = sum(Diff(:))/(Ih*Iw); 48 | 49 | Score = Rn*Eintra/Einter; 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /JSEG/GenerateWindow.m: -------------------------------------------------------------------------------- 1 | function W = GenerateWindow(scale); 2 | % function for generate circular window for J images 3 | % scale: the size of the window 4 | % scale - 1: 9*9 window 5 | % 2: 17*17 6 | % 3: 33*33 7 | % 4; 65*65 8 | 9 | window = ones(65, 65); 10 | % left up block of the window 11 | lu = ones(32,32); 12 | % left bottom 13 | lb = ones(32,32); 14 | % right up 15 | ru = ones(32,32); 16 | % right bottom 17 | rb = ones(32,32); 18 | 19 | % left up 20 | j = 1; 21 | for i = 24:-2:10, 22 | lu(j,1:i) = 0; 23 | lu(1:i,j) = 0; 24 | j = j + 1; 25 | end 26 | 27 | % 90 degree counterclockwise rotation of matrix 28 | lb = rot90(lu); 29 | rb = rot90(lb); 30 | ru = rot90(rb); 31 | window(1:32, 1:32) = lu; 32 | window(1:32, 34:65) = ru; 33 | window(34:65, 1:32) = lb; 34 | window(34:65, 34:65) = rb; 35 | 36 | w4 = window; 37 | w3 = w4(1:2:end, 1:2:end); 38 | w2 = w3(1:2:end, 1:2:end); 39 | w1 = w2(1:2:end, 1:2:end); 40 | 41 | if scale == 4, 42 | W = w4; 43 | elseif scale == 3, 44 | W = w3; 45 | elseif scale == 2, 46 | W = w2; 47 | else scale == 1, 48 | W = w1; 49 | end 50 | -------------------------------------------------------------------------------- /JSEG/JAverage.m: -------------------------------------------------------------------------------- 1 | function JA = JAverage(class_map, Region); 2 | % Calculate a J over each segmented region 3 | % Qinpei 4 | % input: Region: segmented result, contains different segments 5 | % class_map: the original class map 6 | % output: J average value -- higher value indicates classess separated 7 | % -- lower value indicates compactness 8 | 9 | % NOTE: make sure the class_map starts from 1. 10 | 11 | 12 | [m, n] = size(Region); 13 | N = m*n; 14 | JA = 0; 15 | for l = 1: max(Region(:)), 16 | % calculate J value for each region 17 | TRegion = zeros(m, n); 18 | [x,y] = find(Region == l); 19 | xxx = find(Region == l); 20 | if isempty(x) 21 | continue; 22 | end 23 | TRegion(xxx) = class_map(xxx); 24 | St = 0; 25 | % mean vector of the vectors with class label l 26 | z = [x y]; 27 | M = mean(z); 28 | for i = 1:length(z), 29 | m2 = repmat(M, length(z), 1); 30 | St = sum(diag(sqdist(z', m2'))); 31 | end 32 | J = JCalculation(TRegion, M, St); 33 | JA = JA + J*length(z); 34 | end 35 | JA = JA/max(Region(:)); 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /JSEG/JCalculation.m: -------------------------------------------------------------------------------- 1 | function J = JCalculation(class_map, M, St); 2 | % JSEG for color image segmentation implementation 3 | % Calculate a J value for a class map from clustering results (whole image) 4 | % Qinpei 5 | % input: class labels from clustering algorithms 6 | % M: centroid of the whole class map. for a certain window, it will 7 | % not change each time 8 | % output: J value -- higher value indicates classess separated 9 | % -- lower value indicates compactness 10 | 11 | % NOTE: make sure the class_map starts from 1. 12 | 13 | 14 | [m, n] = size(class_map); 15 | N = m*n; 16 | Sw = 0; 17 | 18 | for l = 1: max(class_map(:)), 19 | [x,y] = find(class_map == l); 20 | % mean vector of the vectors with class label l 21 | if isempty(x) 22 | continue; 23 | end 24 | m_l = [mean(x), mean(y)]; 25 | % m_l = [median(x), median(y)]; 26 | m1 = repmat(m_l, length(x), 1); 27 | xy = [x, y]; 28 | Dist1 = sum(diag(sqdist(xy', m1'))); 29 | Sw = Sw + Dist1; 30 | end 31 | 32 | J = (St-Sw)/Sw; 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /JSEG/JImage.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/JSEG/JImage.m -------------------------------------------------------------------------------- /JSEG/LiuYang.m: -------------------------------------------------------------------------------- 1 | % this function is used to evaluate the image segmentation results. 2 | % J.Liu and Y.H. Yang, "Multi-resolution color image segmentation," IEEE 3 | % PAMI 16, pp.689-700,1994 4 | % another version: 5 | % M. Borsotti, P. Campadelli, and R. Schettini, "Quantitiative evaluation 6 | % of color image segmentation results," Pattern Recognitiion Letters 19, 7 | % pp.741-747, 1998 8 | % input: Im -- original image 9 | % CMap -- class map 10 | % output: value indicate the evaluation 11 | % by Qinpei zhao 12 | 13 | function Score = LiuYang(Im, CMap) 14 | 15 | % image property 16 | [Ih, Iw, d] = size(Im); 17 | % segmentation no. 18 | Rn = max(CMap(:)); 19 | 20 | % within cluster 21 | Rmean = zeros(Rn, d); 22 | color_err = zeros(1, Rn); 23 | % for each region 24 | for i = 1:Rn, 25 | sqerr = 0; 26 | sq = find(CMap == i); 27 | Si = length(sq); 28 | for dim = 1:d, 29 | Ri = zeros(Ih, Iw); 30 | Aver_id = zeros(Ih, Iw); 31 | temp1 = Im(:,:,dim); 32 | Ri(sq) = temp1(sq); 33 | % Aver_id -- average value 34 | Aver_id(sq) = sum(Ri(:))/Si; 35 | Rmean(i,dim) = sum(Ri(:))/Si; 36 | % squared color error 37 | sqerr = sqerr + sum(sum((Ri - Aver_id).^2)); 38 | end 39 | color_err(i) = sqerr / sqrt(Si); 40 | end 41 | within_err = sum(color_err)/(sqrt(Rn)); 42 | 43 | % % between cluster 44 | % between_err = sum(pdist(Rmean, 'euclidean')); 45 | 46 | Score = within_err; 47 | 48 | -------------------------------------------------------------------------------- /JSEG/PNN_fast.m: -------------------------------------------------------------------------------- 1 | function T = PNN_fast(Iseg,nhist,nseg) 2 | %Iseg-segment image 3 | %nhist- histogram, 4 | %nseg - outseg 5 | 6 | %connect matrix 7 | n = size(nhist,2); 8 | conn = diag(ones(1,n)); 9 | 10 | %get boundary conn 11 | [row,col] = size(Iseg); 12 | diffx = diff(Iseg,1,2); 13 | diffy = diff(Iseg,1,1); 14 | sq1 = find(diffx); 15 | sq2 = find(diffy); 16 | for t = 1:length(sq1) 17 | v1 = Iseg(sq1(t)); 18 | v2 = Iseg(sq1(t)+ row); 19 | conn(v1,v2) = 1; 20 | conn(v2,v1) = 1; 21 | end 22 | for t = 1:length(sq2) 23 | v1 = Iseg(sq2(t)); 24 | v2 = Iseg(sq2(t)+ 1); 25 | conn(v1,v2) = 1; 26 | conn(v2,v1) = 1; 27 | end 28 | 29 | 30 | histnum = sum(nhist,1); 31 | qlv = size(nhist,1); 32 | tmp = repmat(histnum,qlv,1); 33 | phist = nhist./tmp; 34 | %dist between phist 35 | distv = pdist(phist','euclidean');%probably KL distance is a better choice, use method in the paper here. 36 | %also, original image's mean RGB value can be considered. 37 | distv = distv.^2; 38 | distv = squareform(distv); 39 | Y = distv; 40 | Y(conn==0)= inf; 41 | 42 | minY_col = zeros(1,n); 43 | minY_colsq = zeros(1,n); 44 | for i = 1:n 45 | j1 = 1:(i-1); 46 | j2 = (i+1):n; 47 | jtmp = [j1 j2]; 48 | ytmp = Y(i,jtmp); 49 | [tmp1,tmp2] = min(ytmp); 50 | minY_col(i) = tmp1; 51 | minY_colsq(i) = jtmp(tmp2); 52 | end 53 | 54 | R = 1:n;%n: number of vector 55 | Z = zeros(n-1,3); % allocate the output matrix. 56 | % during updating clusters, cluster index is constantly changing, R is 57 | % a index vector mapping the original index to the current (row, column) 58 | % index in Y. N denotes how many points are contained in each cluster. 59 | N = zeros(1,2*n-1); 60 | N(1:n) = histnum; 61 | centers = zeros(2*n-1,qlv); 62 | centers(1:n,:) = phist'; 63 | 64 | for s = 1:(n-1) 65 | % [v, k] = min(Y); 66 | ncur = length(minY_col); 67 | [v, k] = min(minY_col); 68 | ctmp = k; 69 | rtmp = minY_colsq(k); 70 | 71 | Z(s,:) = [R(rtmp) R(ctmp) v]; % update one more row to the output matrix A 72 | if s 0 && current_xx < m ... 42 | && current_yy > 0 && current_yy < n ) 43 | if(BI(current_xx, current_yy) == 1 && J(current_xx, current_yy) ==1) 44 | J(current_xx, current_yy) = 0; 45 | nEnd = nEnd + 1; 46 | seedx(nEnd) = current_xx; 47 | seedy(nEnd) = current_yy; 48 | end 49 | end 50 | end 51 | nStart = nStart + 1; 52 | end 53 | end 54 | 55 | % % draw the segments dynamically 56 | % temp = zeros(m,n); 57 | % for i = 1:length(seedx), 58 | % if(seedx(i)~=0 && seedy(i) ~=0) 59 | % temp(seedx(i), seedy(i)) = 255; 60 | % end 61 | % end 62 | % imshow(temp); 63 | % hold on; 64 | % pause(2) 65 | 66 | if nEnd > minsize, 67 | NumV = NumV + 1; 68 | for i = 1:length(seedx), 69 | if(seedx(i)~=0 && seedy(i) ~=0) 70 | Seg(seedx(i), seedy(i)) = NumV; 71 | end 72 | end 73 | end 74 | end 75 | 76 | 77 | 78 | -------------------------------------------------------------------------------- /JSEG/SegEval.m: -------------------------------------------------------------------------------- 1 | function ScorePlot(feature_file, partition_file, loglk_file) 2 | clc 3 | % close all 4 | % PlotStyles = {'*-r','o-g','x-m','+-k'}; 5 | % for no = 1:4, 6 | feature_file = 'tree.txt'; 7 | 8 | % for BIC 9 | d = 3; 10 | loglk_file = 'loglk.txt'; 11 | loglikelihood = load(loglk_file); 12 | BIC_VALUE = []; 13 | for j = 2:60, 14 | partition_file = ['tree_' num2str(j) '.txt']; 15 | BICvalue = SegBIC(partition_file, loglikelihood(j-1), d); 16 | BIC_VALUE = [BIC_VALUE, BICvalue]; 17 | end 18 | % plot(2:60, BIC_VALUE, '*-g'); 19 | % grid on; 20 | % end BIC 21 | BIC_min = min(BIC_VALUE); 22 | BIC_max = max(BIC_VALUE); 23 | Norm_BIC = (BIC_VALUE-BIC_min)/(BIC_max-BIC_min); 24 | plot(2:60, Norm_BIC, '*-g'); 25 | hold on; grid on; 26 | % wb-index 27 | Score_Matrix = []; 28 | for i = 2: 60, 29 | partition_file = ['tree_' num2str(i) '.txt']; 30 | Score = SegEvaluate(feature_file, partition_file); 31 | Score_Matrix = [Score_Matrix, Score]; 32 | end 33 | [value,num] = min(Score_Matrix); 34 | % disp(num); 35 | % figure; 36 | % plot(2:60, Score_Matrix, '*-b'); 37 | % grid on; 38 | 39 | % end wb-index 40 | wb_min = min(Score_Matrix); 41 | wb_max= max(Score_Matrix); 42 | norm_wb = (Score_Matrix-wb_min)/(wb_max-wb_min); 43 | plot(2:60, norm_wb, 'o-r'); 44 | plot(2:60, Norm_BIC+ norm_wb, '*-r'); 45 | [a,b] = min(Norm_BIC+ norm_wb); 46 | disp(b); 47 | hold on; 48 | 49 | % end 50 | % this function is used to evaluate the image segmentation results. 51 | % input: feature file; 52 | % label file with partitions 53 | % output: value indicate the evaluation 54 | % by Qinpei zhao 10.Mar.2009 55 | % N - the number of data points (pixel number) 56 | % d - dimension of feature space 57 | % M - number of components 58 | % Nj- number of pixels in each component 59 | % NB: not applicable for M = 1; 1 component doesn't need to evaluate!!!! 60 | function Score = SegEvaluate(feature_file, partition_file) 61 | Score = 0; 62 | Label = load(partition_file); 63 | M = max(Label) + 1; 64 | Feature = load(feature_file); 65 | [N,d] = size(Feature); 66 | % assume each dimension of features is independent 67 | for dim = 1:d, 68 | ssw = 0; 69 | ssb = 0; 70 | % mean of the whole image on each feature 71 | Xmean = sum(Feature(:, dim)); 72 | for m = 0: M-1, 73 | Index = find(Label == m); 74 | Nm = length(Index); 75 | Cmean = sum(Feature(Index, dim)); 76 | temp = Feature(Index, dim)-Cmean; 77 | ssw = ssw + sum(sqrt(temp.*temp)); 78 | ssb = ssb + Nm* sqrt((Cmean - Xmean)*(Cmean - Xmean)); 79 | end 80 | Score = Score + ssw / ssb; 81 | 82 | end 83 | Score = M*Score; 84 | 85 | 86 | % evaluate by BIC = -loglikelihood + 0.5*k*sum(log(Ni)) 87 | % input: partition_file 88 | % loglikelihood 89 | % output: BIC value 90 | 91 | function BICvalue = SegBIC(partition_file, loglikelihood, dim) 92 | Label = load(partition_file); 93 | N = length(Label); 94 | M = max(Label) + 1; 95 | temp = 0; 96 | for m = 0:M-1, 97 | Index = find(Label == m); 98 | % number of points for each component 99 | Nm = length(Index); 100 | temp = temp + log(Nm); 101 | end 102 | 103 | BICvalue = -N*loglikelihood + 0.5*M*(dim+1)*temp; 104 | 105 | 106 | 107 | 108 | -------------------------------------------------------------------------------- /JSEG/SpatialSeg.m: -------------------------------------------------------------------------------- 1 | function ImgSeg = SpatialSeg(JI, RS, wi) 2 | 3 | [m, n] = size(JI); 4 | ImgSeg = zeros(m,n); 5 | Sno = 0; 6 | % figure; 7 | for r = 1:max(RS(:)), 8 | % one region to multiple 9 | Region = zeros(m,n); 10 | Region(:, :) = NaN; 11 | temp = []; 12 | xy = find(RS == r); 13 | Region(xy) = JI(xy); 14 | temp = [temp JI(xy)]; 15 | u = sum(temp)/length(xy); 16 | s = std(temp); 17 | 18 | Region = ValleyD(Region, wi, u, s); 19 | sq = find(Region ~=0); 20 | Region(sq) = Region(sq) + Sno; 21 | ImgSeg = ImgSeg + Region; 22 | Sno = max(ImgSeg(:)); 23 | % % fprintf('%d\n', Sno); 24 | % % imshow(ImgSeg); 25 | % % hold on; 26 | % % pause(2) 27 | end 28 | 29 | ImgSeg = ValleyG1(JI, ImgSeg); 30 | 31 | 32 | -------------------------------------------------------------------------------- /JSEG/ValleyD.m: -------------------------------------------------------------------------------- 1 | function ValleyI = ValleyD(JI, scale, uj, sj) 2 | % valley determination 3 | % input: J-images 4 | % scale 5 | % uj, sj: mean and std 6 | % output: valleys which indicates the connected regions with lower J values 7 | % in the J images. Numbers as lable for segments 8 | %% rewrite by Minjie 9 | [m, n] = size(JI); 10 | a = [-0.6, -0.4, -0.2, 0, 0.2, 0,4]; 11 | % valley size has to be larger than minsize under scale 1-4. 12 | minsize = [32, 128, 512, 2048]; 13 | % try a value one by one to find the value gives the most number of valleys 14 | scale = minsize(scale); 15 | MaxVSize = 0; 16 | ValleyI = zeros(m,n); 17 | for i = 1:length(a), 18 | TJ = uj + a(i)*sj; 19 | % candidate valley point (< TJ) == 1; 20 | VP = false(m,n); 21 | VP(JI <= TJ) = 1; 22 | % 4-connectivity => candidate valley (large size segments with low J 23 | % value 24 | VP_lab = bwlabel(VP,4); 25 | VPlab_hist = histc(VP_lab(:),1:max(VP_lab(:))); 26 | sq = find(VPlab_hist>=scale); 27 | VSize = length(sq); 28 | if length(sq)>MaxVSize 29 | ValleyI = zeros(m, n); 30 | for k = 1:length(sq) 31 | ValleyI(VP_lab==sq(k))=k; 32 | end 33 | MaxVSize = VSize; 34 | end 35 | end 36 | 37 | 38 | % 39 | % 40 | % 41 | % [m, n] = size(JI); 42 | % % valley size has to be larger than minsize under scale 1-4. 43 | % minsize = [32, 128, 512, 2048]; 44 | % % threshold UJ+a*SJ; 45 | % % try a value one by one to find the value gives the most number of valleys 46 | % VP = zeros(m, n); 47 | % scale = minsize(scale); 48 | % % maximum valley size with different a value 49 | % MaxVSize = 0; 50 | % ValleyI = zeros(m,n); 51 | % for i = 1:length(a), 52 | % SI = zeros(m, n); 53 | % TJ = uj + a(i)*sj; 54 | % % candidate valley point (< TJ) == 1; 55 | % [x, y] = find(JI <= TJ); 56 | % for j = 1:length(x), 57 | % VP(x(j), y(j)) = 1; 58 | % end 59 | % % 4-connectivity => candidate valley (large size segments with low J 60 | % % value 61 | % SI = SeedGrowing(VP,x,y, scale); 62 | % VSize = max(SI(:)); 63 | % if VSize > MaxVSize, 64 | % ValleyI = SI; 65 | % MaxVSize = VSize; 66 | % end 67 | % end 68 | 69 | 70 | 71 | 72 | 73 | -------------------------------------------------------------------------------- /JSEG/ValleyG1.m: -------------------------------------------------------------------------------- 1 | % input: 2 | % JI -- J image 3 | % ValleyI -- vallley image 4 | % scale -- current scale level 5 | % output: 6 | % SegI -- the segmented image 7 | 8 | 9 | function SegI = ValleyG1(JI, ValleyI) 10 | % valley growing: new regions grow from the valleys 11 | % RemainI: 0 means processed; non-0 means remaining 12 | %% revise by Minjie 13 | [m, n] = size(ValleyI); 14 | 15 | % step1. remove the holes 16 | 17 | ValleyI = imfill(ValleyI, 'holes'); 18 | SegI = ValleyI; 19 | 20 | % step2. for the remaining unsegmented part 21 | sq_remain = find(ValleyI == 0); 22 | JIhigh = JI(sq_remain); 23 | u = mean(JIhigh); 24 | sq_medth = sq_remain(JIhigh0); 42 | SegI(sq) = tmp; 43 | end 44 | end 45 | 46 | %% 47 | % [m, n] = size(ValleyI); 48 | % 49 | % % step1. remove the holes by morphological filtering 50 | % se = strel('square',3); 51 | % ValleyI = imclose(ValleyI, se); 52 | % 53 | % SegI = ValleyI; 54 | % 55 | % % step2. for the remaining unsegmented part 56 | % sq_remain = find(ValleyI == 0); 57 | % JIhigh = JI(sq_remain); 58 | % u = mean(JIhigh); 59 | % sq_medth = sq_remain(JIhigh minsize, 91 | % % for s = 1:length(gx), 92 | % % RemainI(gx(s), gy(s)) = RemainI(gx(s), gy(s)) + max(SegI(:)); 93 | % % end 94 | % % SegI = SegI + RemainI; 95 | % % end 96 | % % end 97 | % end 98 | % 99 | % 100 | % % RemainI = zeros(m,n); 101 | % % [x, y] = find(ValleyI == 0); 102 | % % for i = 1:length(x), 103 | % % RemainI(x(i), y(i)) = JI(x(i), y(i)); 104 | % % end 105 | % 106 | % % u = sum(RemainI(:))/length(x); 107 | % 108 | % % get the image part under u in the remaining part, region grow 109 | % 110 | % 111 | % % region grow 112 | % % GArea = SeedGrowing(GArea, gx, gy, 1); 113 | % % bw_GArea = bwlabel(logical(GArea),4); 114 | % % % dilation on the ValleyI 115 | % % se1 = strel('diamond',1); 116 | % % bw_GAread = imdilate(bw_GArea, se1); 117 | % 118 | % 119 | % 120 | % 121 | % 122 | % 123 | % 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /JSEG/ValleyG2.m: -------------------------------------------------------------------------------- 1 | % input: 2 | % JI -- J image 3 | % Region -- segments 4 | % 5 | % output: 6 | % SegI -- the segmented image 7 | % JSEG: 4.2 step4 8 | % Unclassified pixels at the region boundaries are stored in a buffer(heap) 9 | % in our cse. Each time, the pixel with the minimum local J value is 10 | % assigned to the adjacent region. And the buffer is updated until all the 11 | % pixels are classified. 12 | 13 | function SegI = ValleyG2(JI, Region) 14 | 15 | 16 | [m, n] = size(JI); 17 | SegI = zeros(m,n); 18 | 19 | % Initial Heap list, find the initial boudnaries 20 | BRegion = imdilate(Region, [0 1 0; 1 1 1; 0 1 0]); 21 | 22 | 23 | Boundary = BRegion & ~Region; 24 | % locations of the boundaries: sq = m*(j-1)+i, jth column, ith row 25 | sq = find(Boundary); 26 | % J value of the boundary pixels 27 | Jvalue = JI(sq); 28 | % build heap 29 | [hp, hpid] = build_heap(Jvalue,sq); 30 | 31 | x_direction = [-1, 0, 1, 0]; 32 | y_direction = [ 0, 1, 0, -1]; 33 | 34 | while (~isempty(hp)), 35 | % take the first out from heap: with the minimum J value 36 | [hp,hpid,minval,pos] = heap_pop(hp,hpid); 37 | 38 | posy = fix((pos-1)/m)+1; 39 | posx = pos - m*(posy-1); 40 | if ~Region(posx,posy) 41 | curval = BRegion(posx,posy); 42 | Region(posx,posy) =curval; 43 | 44 | % 4-neighbours 45 | for k = 1:4, 46 | x = posx + x_direction(k); 47 | y = posy + y_direction(k); 48 | if x> 0 && x<=m && y > 0 && y <=n, 49 | 50 | if BRegion(x, y) == 0, 51 | P = x + m*(y-1); 52 | J = JI(x,y); 53 | [hp,hpid] = heap_add(hp,hpid,J,P); 54 | BRegion(x,y) = curval; 55 | % else 56 | % Region(pos) = Region(P); 57 | end 58 | end 59 | end 60 | end 61 | 62 | 63 | 64 | 65 | % % [B,L] = bwboundaries(imdilate(Region, [0 1 0; 1 1 1; 0 1 0]), 'noholes'); 66 | % % 67 | % % for k = 1:length(B), 68 | % % boundary = B{k}; 69 | % % % J value on outer boundaries 70 | % % Jb = []; 71 | % % for b = 1:size(boundary,1), 72 | % % Jb = [Jb JI(boundary(b,1), boundary(b,2))]; 73 | % % end 74 | % % [v, id] = min(Jb); 75 | % % %the pixel with minimum J value 76 | % % Jbmin = boundary(id, :); 77 | % % % assgign to the adjacent segment, values from 4-connectivity neighbour 78 | % % temp = []; 79 | % % x_direction = [-1, 0, 1, 0]; 80 | % % y_direction = [ 0, 1, 0, -1]; 81 | % % for k = 1:4, 82 | % % x = Jbmin(1) + x_direction(k); 83 | % % y = Jbmin(2) + y_direction(k); 84 | % % temp = [temp Region(x, y)]; 85 | % % end 86 | % % if length(unique(temp(find(temp ~= 0)))) == 1, 87 | % % Region(Jbmin(1), Jbmin(2)) = unique(temp(find(temp ~=0))); 88 | % % else 89 | % % break; 90 | % % end 91 | % % end 92 | end 93 | 94 | SegI = Region; 95 | 96 | % ShowSegs(SegI); 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /JSEG/build_heap.m: -------------------------------------------------------------------------------- 1 | function [hp, hpind] = build_heap(x,sq) 2 | l = length(x); 3 | hp = x; 4 | hpind = sq; 5 | 6 | 7 | for i = 2:l 8 | curnode = i; 9 | while (curnode>1) 10 | parnode = fix(curnode/2); 11 | if hp(parnode)>hp(curnode)%FOR MIN-hp 12 | %swap value 13 | tmp = hp(parnode); 14 | hp(parnode) = hp(curnode); 15 | hp(curnode) = tmp; 16 | %swap hpind 17 | tmp = hpind(parnode); 18 | hpind(parnode) = hpind(curnode); 19 | hpind(curnode) = tmp; 20 | curnode = parnode; 21 | else 22 | break; 23 | end 24 | end 25 | end 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /JSEG/class2Img.m: -------------------------------------------------------------------------------- 1 | function Img = class2Img(class_map, OrI) 2 | % input: class_map -- the segment label for each pixel 3 | % OrI -- original image 4 | % output: Img -- segmented image (quantized/average) 5 | 6 | [m, n, d] = size(OrI); 7 | 8 | Img = zeros(m,n,d); 9 | for i = 1:max(class_map(:)), 10 | sq = find(class_map == i); 11 | Channel = zeros(m,n); 12 | for j = 1:d, 13 | Channel = OrI(:,:, j); 14 | u = mean(Channel(sq)); 15 | Channel = zeros(m,n); 16 | Channel(sq) = u; 17 | Img(:,:, j) = Img(:,:,j) + Channel; 18 | end 19 | end 20 | 21 | -------------------------------------------------------------------------------- /JSEG/heap_add.m: -------------------------------------------------------------------------------- 1 | function [hp,hpind] = heap_add(hp,hpind,addval,addind) 2 | %invind is current pos of 1:l point in hps 3 | l = length(hp)+1; 4 | hp(l) = addval; 5 | hpind(l) = addind; 6 | curnode = l; 7 | while (curnode>1) 8 | parnode = fix(curnode/2); 9 | if hp(parnode)>hp(curnode)%FOR MIN-heaps 10 | %swap value 11 | tmp = hp(parnode); 12 | hp(parnode) = hp(curnode); 13 | hp(curnode) = tmp; 14 | %swap heapind 15 | tmp = hpind(parnode); 16 | hpind(parnode) = hpind(curnode); 17 | hpind(curnode) = tmp; 18 | curnode = parnode; 19 | else 20 | break; 21 | end 22 | end -------------------------------------------------------------------------------- /JSEG/heap_pop.m: -------------------------------------------------------------------------------- 1 | function [hp,hpind,minval,minind] = heap_pop(hp,hpind) 2 | %pop min value in heap 3 | if length(hp)==0 4 | disp('empty heap, no pop operation') 5 | return; 6 | end 7 | l = length(hp); 8 | minval = hp(1); 9 | minind = hpind(1); 10 | hp(1) = hp(l); 11 | hpind(1) = hpind(l); 12 | l = l-1; 13 | hp = hp(1:l); 14 | hpind = hpind(1:l); 15 | 16 | 17 | curnode = 1; 18 | halfl = fix(l/2); 19 | while (curnode<=halfl) 20 | sonnode1 = curnode*2; 21 | sonnode2 = sonnode1 +1; 22 | val1 = hp(curnode); 23 | val2 = hp(sonnode1); 24 | if l>=sonnode2 25 | val3 = hp(sonnode2); 26 | else 27 | val3 = inf; 28 | end 29 | if val1>val2 30 | if val2>val3 31 | %1>2>3,move3 32 | stat=3; 33 | else 34 | %1>2,3>2, move 2 35 | stat =2; 36 | end 37 | else 38 | if val1>val3 39 | %2>1>3 move 3 40 | stat = 3; 41 | else 42 | %2>1,3>1, stop 43 | stat = 0; 44 | end 45 | end 46 | if (stat==0) 47 | break; 48 | elseif (stat==3) 49 | %swap value,1<->3 50 | hp(sonnode2) = val1; 51 | hp(curnode) = val3; 52 | %swap heapind 53 | tmp = hpind(curnode); 54 | hpind(curnode) = hpind(sonnode2); 55 | hpind(sonnode2) = tmp; 56 | curnode = sonnode2; 57 | else % stat==2 58 | %swap value,1<->2 59 | hp(sonnode1) = val1; 60 | hp(curnode) = val2; 61 | %swap heapind 62 | tmp = hpind(curnode); 63 | hpind(curnode) = hpind(sonnode1); 64 | hpind(sonnode1) = tmp; 65 | curnode = sonnode1; 66 | end 67 | end 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /JSEG/jseg.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/JSEG/jseg.fig -------------------------------------------------------------------------------- /JSEG/jseg.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/JSEG/jseg.m -------------------------------------------------------------------------------- /JSEG/kmeansO.m: -------------------------------------------------------------------------------- 1 | function [Er,M, nb, P] = kmeansO(X,T,kmax,dyn,bs, killing, pl) 2 | % kmeans - clustering with k-means (or Generalized Lloyd or LBG) algorithm 3 | % 4 | % [Er,M,nb] = kmeans(X,T,kmax,dyn,dnb,killing,p) 5 | % 6 | % X - (n x d) d-dimensional input data 7 | % T - (? x d) d-dimensional test data 8 | % kmax - (maximal) number of means 9 | % dyn - 0: standard k-means, unif. random subset of data init. 10 | % 1: fast global k-means 11 | % 2: non-greedy, just use kdtree to initiallize the means 12 | % 3: fast global k-means, use kdtree for potential insertion locations 13 | % 4: global k-means algorithm 14 | % dnb - desired number of buckets on the kd-tree 15 | % pl - plot the fitting process 16 | % 17 | % returns 18 | % Er - sum of squared distances to nearest mean (second column for test data) 19 | % M - (k x d) matrix of cluster centers; k is computed dynamically 20 | % nb - number of nodes on the kd-tree (option dyn=[2,3]) 21 | % P - Partition labels 22 | % 23 | % Nikos Vlassis & Sjaak Verbeek, 2001, http://www.science.uva.nl/~jverbeek 24 | % modify by Qinpei, 2009 25 | 26 | Er=[]; TEr=[]; % error monitorring 27 | 28 | [n,d] = size(X); 29 | P = zeros(n,1); 30 | 31 | THRESHOLD = 1e-4; % relative change in error that is regarded as convergence 32 | nb = 0; 33 | 34 | % initialize 35 | if dyn==1 % greedy insertion, possible at all points 36 | k = 1; 37 | M = mean(X); 38 | K = sqdist(X',X'); 39 | L = X; 40 | elseif dyn==2 % use kd-tree results as means 41 | k = kmax; 42 | M = kdtree(X,[1:n]',[],1.5*n/k); 43 | nb = size(M,1); 44 | dyn = 0; 45 | elseif dyn==3 46 | L = kdtree(X,[1:n]',[],1.5*n/bs); 47 | nb = size(L,1); 48 | k = 1; 49 | M = mean(X); 50 | K = sqdist(X',L'); 51 | elseif dyn==4 52 | k = 1; 53 | M = mean(X); 54 | K = sqdist(X',X'); 55 | L = X; 56 | else % use random subset of data as means 57 | k = kmax; 58 | tmp = randperm(n); 59 | M = X(tmp(1:k),:); 60 | end 61 | 62 | Wold = realmax; 63 | 64 | while k <= kmax 65 | kill = []; 66 | 67 | % squared Euclidean distances to means; Dist (k x n) 68 | Dist = sqdist(M',X'); 69 | 70 | % Voronoi partitioning 71 | [Dwin,Iwin] = min(Dist',[],2); 72 | P = Iwin; 73 | 74 | % error measures and mean updates 75 | Wnew = sum(Dwin); 76 | 77 | % update VQ's 78 | for i=1:size(M,1) 79 | I = find(Iwin==i); 80 | if size(I,1)>d 81 | M(i,:) = mean(X(I,:)); 82 | elseif killing==1 83 | kill = [kill; i]; 84 | end 85 | end 86 | 87 | if 1-Wnew/Wold < THRESHOLD*(10-9*(k==kmax)) 88 | if dyn & k < kmax 89 | 90 | if dyn == 4 91 | best_Er = Wnew; 92 | 93 | for i=1:n; 94 | Wold = Inf; 95 | Wtmp = Wnew; 96 | Mtmp = [M; X(i,:)]; 97 | while (1-Wtmp/Wold) > THRESHOLD*10; 98 | Wold = Wtmp; 99 | Dist = sqdist(Mtmp',X'); 100 | [Dwin,Iwin] = min(Dist',[],2); 101 | Wtmp = sum(Dwin); 102 | for i = 1 : size(Mtmp,1) 103 | I = find(Iwin==i); 104 | if size(I,1)>d; Mtmp(i,:) = mean(X(I,:)); end 105 | end 106 | end 107 | if Wtmp < best_Er; best_M = Mtmp; best_Er = Wtmp; end 108 | end 109 | 110 | M = best_M; 111 | Wnew = best_Er; 112 | if ~isempty(T); tmp=sqdist(T',M'); TEr=[TEr; sum(min(tmp,[],2))];end; 113 | Er=[Er; Wnew]; 114 | k = k+1; 115 | 116 | else 117 | % try to add a new cluster on some point x_i 118 | [tmp,new] = max(sum(max(repmat(Dwin,1,size(K,2))-K,0))); 119 | k = k+1; 120 | M = [M; L(new,:)+eps]; 121 | if pl; fprintf( 'new cluster, k=%d\n', k); end 122 | [Dwin,Iwin] = min(Dist',[],2); 123 | Wnew = sum(Dwin);Er=[Er; Wnew]; 124 | if ~isempty(T); tmp=sqdist(T',M'); TEr=[TEr; sum(min(tmp,[],2))];end; 125 | end 126 | else 127 | k = kmax+1; 128 | end 129 | end 130 | Wold = Wnew; 131 | if pl 132 | figure(1); plot(X(:,1),X(:,2),'g.',M(:,1),M(:,2),'k.',M(:,1),M(:,2),'k+'); 133 | drawnow; 134 | end 135 | end 136 | 137 | Er=[Er; Wnew]; 138 | if ~isempty(T); tmp=sqdist(T',M'); TEr=[TEr; sum(min(tmp,[],2))]; Er=[Er TEr];end; 139 | M(kill,:)=[]; 140 | 141 | -------------------------------------------------------------------------------- /JSEG/script.m: -------------------------------------------------------------------------------- 1 | % clear all 2 | clc 3 | clear; 4 | close all; 5 | %====== load image =======% 6 | filename = ['124084.jpg']; 7 | image_org = imread(filename); 8 | [m,n,d] = size(image_org); 9 | % figure; imshow(image_org); 10 | 11 | %====== partition ========% 12 | % class_map from clustering algorithms 13 | X = reshape(double(image_org), m*n,d); 14 | [tmp,M,tmp2,P] = kmeansO(X,[],16,0,0,0,0); 15 | map = reshape(P, m, n); 16 | 17 | 18 | % generate J images 19 | for w = 1:4, 20 | W = GenerateWindow(w); 21 | JI = JImage(map, W,w); 22 | save([num2str(w) '.mat'], 'JI'); 23 | imwrite(JI, ['JImage' num2str(w) '.jpg']); 24 | end 25 | 26 | %===== load existing J-images ===% 27 | load('4.mat'); 28 | JI4 = JI; 29 | load('3.mat'); 30 | JI3 = JI; 31 | load('2.mat'); 32 | JI2 = JI; 33 | load('1.mat'); 34 | JI1 = JI; 35 | figure; 36 | imshow(JI4); 37 | figure; 38 | imshow(JI3); 39 | figure; 40 | imshow(JI2); 41 | figure; 42 | imshow(JI1); 43 | 44 | % quantized image 45 | ImgQ = class2Img(map, image_org); 46 | 47 | Region = zeros(m, n); 48 | % --------------------scale 4-------------------- 49 | % scale 4 50 | u = mean(JI4(:)); 51 | s = std(JI4(:)); 52 | Region = ValleyD(JI4, 4, u, s); % 4.1 Valley Determination 53 | Region = ValleyG1(JI4, Region); % 4.2.2 Growing 54 | Region = ValleyG1(JI3, Region); % 4.2.3 Growing at next smaller scale 55 | Region = ValleyG2(JI1, Region); % 4.2.4 remaining pixels at the smallest scale 56 | Region4 = Region; 57 | fprintf('scale4: %d\n', max(Region(:))); 58 | % draw segments 59 | figure; imshow(uint8(ImgQ)); 60 | hold on; 61 | DrawLine(Region); 62 | hold off; 63 | % --------------------scale 3-------------------- 64 | w = 3; 65 | Region = SpatialSeg(JI3, Region, w); 66 | % Valley Growing at the next smaller scale level 67 | Region = ValleyG1(JI2, Region); 68 | % Valley Growing at the smallest scale level 69 | Region = ValleyG2(JI1, Region); 70 | Region3 = Region; 71 | fprintf('scale3: %d\n', max(Region(:))); 72 | figure; imshow(uint8(ImgQ)); 73 | hold on; 74 | DrawLine(Region); 75 | hold off; 76 | % --------------------scale 2-------------------- 77 | % SpatialSeg includes one ValleyD and ValleyG1 at current scale level 78 | w = 2; 79 | Region = SpatialSeg(JI2, Region, w); 80 | % Valley Growing at the next smaller scale level 81 | Region = ValleyG1(JI1, Region); 82 | % Valley Growing at the smallest scale level 83 | Region = ValleyG2(JI1, Region); 84 | Region2 = Region; 85 | fprintf('scale2: %d\n', max(Region(:))); 86 | figure; imshow(uint8(ImgQ)); 87 | hold on; 88 | DrawLine(Region); 89 | hold off; 90 | 91 | % % % % % % --------------------scale 1-------------------- 92 | w = 1; 93 | Region = SpatialSeg(JI1, Region, w); 94 | Region = ValleyG2(JI1, Region); 95 | Region1 = Region; 96 | fprintf('scale1: %d\n', max(Region(:))); 97 | figure; imshow(uint8(ImgQ)); 98 | hold on; 99 | DrawLine(Region); 100 | hold off; 101 | 102 | 103 | %Region0 = RegionMerge(image_org,map, Region, 20); 104 | Region0 = RegionMerge_RGB(image_org,map, Region, 9); 105 | figure; imshow(uint8(ImgQ)); 106 | hold on; 107 | DrawLine(Region0); 108 | hold off; 109 | 110 | 111 | -------------------------------------------------------------------------------- /JSEG/sqdist.m: -------------------------------------------------------------------------------- 1 | function d = sqdist(a,b) 2 | % sqdist - computes pairwise squared Euclidean distances between points 3 | 4 | % original version by Roland Bunschoten, 1999 5 | 6 | if size(a,1)==1 7 | d = repmat(a',1,length(b)) - repmat(b,length(a),1); 8 | d = d.^2; 9 | else 10 | aa = sum(a.*a); bb = sum(b.*b); ab = a'*b; 11 | d = abs(repmat(aa',[1 size(bb,2)]) + repmat(bb,[size(aa,2) 1]) - 2*ab); 12 | end 13 | -------------------------------------------------------------------------------- /JSEG/ssim_index.m: -------------------------------------------------------------------------------- 1 | function [mssim, ssim_map] = ssim_index(img1, img2, K, window, L) 2 | 3 | %======================================================================== 4 | %SSIM Index, Version 1.0 5 | %Copyright(c) 2003 Zhou Wang 6 | %All Rights Reserved. 7 | % 8 | %The author is with Howard Hughes Medical Institute, and Laboratory 9 | %for Computational Vision at Center for Neural Science and Courant 10 | %Institute of Mathematical Sciences, New York University. 11 | % 12 | %---------------------------------------------------------------------- 13 | %Permission to use, copy, or modify this software and its documentation 14 | %for educational and research purposes only and without fee is hereby 15 | %granted, provided that this copyright notice and the original authors' 16 | %names appear on all copies and supporting documentation. This program 17 | %shall not be used, rewritten, or adapted as the basis of a commercial 18 | %software or hardware product without first obtaining permission of the 19 | %authors. The authors make no representations about the suitability of 20 | %this software for any purpose. It is provided "as is" without express 21 | %or implied warranty. 22 | %---------------------------------------------------------------------- 23 | % 24 | %This is an implementation of the algorithm for calculating the 25 | %Structural SIMilarity (SSIM) index between two images. Please refer 26 | %to the following paper: 27 | % 28 | %Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image 29 | %quality assessment: From error measurement to structural similarity" 30 | %IEEE Transactios on Image Processing, vol. 13, no. 1, Jan. 2004. 31 | % 32 | %Kindly report any suggestions or corrections to zhouwang@ieee.org 33 | % 34 | %---------------------------------------------------------------------- 35 | % 36 | %Input : (1) img1: the first image being compared 37 | % (2) img2: the second image being compared 38 | % (3) K: constants in the SSIM index formula (see the above 39 | % reference). defualt value: K = [0.01 0.03] 40 | % (4) window: local window for statistics (see the above 41 | % reference). default widnow is Gaussian given by 42 | % window = fspecial('gaussian', 11, 1.5); 43 | % (5) L: dynamic range of the images. default: L = 255 44 | % 45 | %Output: (1) mssim: the mean SSIM index value between 2 images. 46 | % If one of the images being compared is regarded as 47 | % perfect quality, then mssim can be considered as the 48 | % quality measure of the other image. 49 | % If img1 = img2, then mssim = 1. 50 | % (2) ssim_map: the SSIM index map of the test image. The map 51 | % has a smaller size than the input images. The actual size: 52 | % size(img1) - size(window) + 1. 53 | % 54 | %Default Usage: 55 | % Given 2 test images img1 and img2, whose dynamic range is 0-255 56 | % 57 | % [mssim ssim_map] = ssim_index(img1, img2); 58 | % 59 | %Advanced Usage: 60 | % User defined parameters. For example 61 | % 62 | % K = [0.05 0.05]; 63 | % window = ones(8); 64 | % L = 100; 65 | % [mssim ssim_map] = ssim_index(img1, img2, K, window, L); 66 | % 67 | %See the results: 68 | % 69 | % mssim %Gives the mssim value 70 | % imshow(max(0, ssim_map).^4) %Shows the SSIM index map 71 | % 72 | %======================================================================== 73 | 74 | 75 | if (nargin < 2 || nargin > 5) 76 | ssim_index = -Inf; 77 | ssim_map = -Inf; 78 | return; 79 | end 80 | 81 | if (size(img1) ~= size(img2)) 82 | ssim_index = -Inf; 83 | ssim_map = -Inf; 84 | return; 85 | end 86 | 87 | [M N] = size(img1); 88 | 89 | if (nargin == 2) 90 | if ((M < 11) || (N < 11)) 91 | ssim_index = -Inf; 92 | ssim_map = -Inf; 93 | return 94 | end 95 | window = fspecial('gaussian', 11, 1.5); % 96 | K(1) = 0.01; % default settings 97 | K(2) = 0.03; % 98 | L = 255; % 99 | end 100 | 101 | if (nargin == 3) 102 | if ((M < 11) || (N < 11)) 103 | ssim_index = -Inf; 104 | ssim_map = -Inf; 105 | return 106 | end 107 | window = fspecial('gaussian', 11, 1.5); 108 | L = 255; 109 | if (length(K) == 2) 110 | if (K(1) < 0 || K(2) < 0) 111 | ssim_index = -Inf; 112 | ssim_map = -Inf; 113 | return; 114 | end 115 | else 116 | ssim_index = -Inf; 117 | ssim_map = -Inf; 118 | return; 119 | end 120 | end 121 | 122 | if (nargin == 4) 123 | [H W] = size(window); 124 | if ((H*W) < 4 || (H > M) || (W > N)) 125 | ssim_index = -Inf; 126 | ssim_map = -Inf; 127 | return 128 | end 129 | L = 255; 130 | if (length(K) == 2) 131 | if (K(1) < 0 || K(2) < 0) 132 | ssim_index = -Inf; 133 | ssim_map = -Inf; 134 | return; 135 | end 136 | else 137 | ssim_index = -Inf; 138 | ssim_map = -Inf; 139 | return; 140 | end 141 | end 142 | 143 | if (nargin == 5) 144 | [H W] = size(window); 145 | if ((H*W) < 4 || (H > M) || (W > N)) 146 | ssim_index = -Inf; 147 | ssim_map = -Inf; 148 | return 149 | end 150 | if (length(K) == 2) 151 | if (K(1) < 0 || K(2) < 0) 152 | ssim_index = -Inf; 153 | ssim_map = -Inf; 154 | return; 155 | end 156 | else 157 | ssim_index = -Inf; 158 | ssim_map = -Inf; 159 | return; 160 | end 161 | end 162 | 163 | C1 = (K(1)*L)^2; 164 | C2 = (K(2)*L)^2; 165 | window = window/sum(sum(window)); 166 | img1 = double(img1); 167 | img2 = double(img2); 168 | 169 | mu1 = filter2(window, img1, 'valid'); 170 | mu2 = filter2(window, img2, 'valid'); 171 | mu1_sq = mu1.*mu1; 172 | mu2_sq = mu2.*mu2; 173 | mu1_mu2 = mu1.*mu2; 174 | sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq; 175 | sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq; 176 | sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2; 177 | 178 | if (C1 > 0 & C2 > 0) 179 | ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2)); 180 | else 181 | numerator1 = 2*mu1_mu2 + C1; 182 | numerator2 = 2*sigma12 + C2; 183 | denominator1 = mu1_sq + mu2_sq + C1; 184 | denominator2 = sigma1_sq + sigma2_sq + C2; 185 | ssim_map = ones(size(mu1)); 186 | index = (denominator1.*denominator2 > 0); 187 | ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index)); 188 | index = (denominator1 ~= 0) & (denominator2 == 0); 189 | ssim_map(index) = numerator1(index)./denominator1(index); 190 | end 191 | 192 | mssim = mean2(ssim_map); 193 | 194 | return -------------------------------------------------------------------------------- /Kmeans/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/Kmeans/3096.jpg -------------------------------------------------------------------------------- /Kmeans/Main_Kmeans.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/Kmeans/Main_Kmeans.m -------------------------------------------------------------------------------- /Otsu全局阈值处理/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/Otsu全局阈值处理/3096.jpg -------------------------------------------------------------------------------- /Otsu全局阈值处理/main_OTSU_local.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/Otsu全局阈值处理/main_OTSU_local.m -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # matlab 2 | 3 | Application of FCM and IFCM clustering algorithm in image segmentation, coded by matlab 4 | 5 | FCM和IFCM聚类算法在图像处理的应用,用matlab开发 6 | 7 | FCM clustering algorithm in image segmentation, run the `main_fcm.m` 8 | 9 | FCM算法图像分割,直接运行`main_fcm.m`文件 10 | 11 | IFCM clustering algorithm in image segmentation, run the `main_IFCM.m` 12 | 13 | IFCM算法图像分割,直接运行`main_IFCM.m`文件 14 | 15 | JSEG图像分割,彩色图像分割的一种 16 | 17 | otsu最大类间方差法 18 | 19 | 分水岭阈值分割 20 | 21 | -------------------------------------------------------------------------------- /SegbyEntrory/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/SegbyEntrory/3096.jpg -------------------------------------------------------------------------------- /SegbyEntrory/Main_Seg.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/SegbyEntrory/Main_Seg.m -------------------------------------------------------------------------------- /SegbyEntrory/Myfun.m: -------------------------------------------------------------------------------- 1 | function scalar = Myfun(img) 2 | %% guassain mask filter of weight 3 | sigma = 5; 4 | Weight = fspecial('gaussian',[sigma,sigma],1); 5 | scalar = sum(sum((double(img).*Weight)))/(sigma^2); 6 | 7 | -------------------------------------------------------------------------------- /WOA/Get_Functions_details.m: -------------------------------------------------------------------------------- 1 | %_________________________________________________________________________% 2 | % Whale Optimization Algorithm (WOA) source codes demo 1.0 % 3 | % % 4 | % Developed in MATLAB R2011b(7.13) % 5 | % % 6 | % Author and programmer: Seyedali Mirjalili % 7 | % % 8 | % e-Mail: ali.mirjalili@gmail.com % 9 | % seyedali.mirjalili@griffithuni.edu.au % 10 | % % 11 | % Homepage: http://www.alimirjalili.com % 12 | % % 13 | % Main paper: S. Mirjalili, A. Lewis % 14 | % The Whale Optimization Algorithm, % 15 | % Advances in Engineering Software , in press, % 16 | % DOI: http://dx.doi.org/10.1016/j.advengsoft.2016.01.008 % 17 | % % 18 | %_________________________________________________________________________% 19 | 20 | % This function containts full information and implementations of the benchmark 21 | % functions in Table 1, Table 2, and Table 3 in the paper 22 | 23 | % lb is the lower bound: lb=[lb_1,lb_2,...,lb_d] 24 | % up is the uppper bound: ub=[ub_1,ub_2,...,ub_d] 25 | % dim is the number of variables (dimension of the problem) 26 | 27 | function [lb,ub,dim,fobj] = Get_Functions_details(F) 28 | 29 | 30 | switch F 31 | case 'F1' 32 | fobj = @F1; 33 | lb=-100; 34 | ub=100; 35 | dim=30; 36 | 37 | case 'F2' 38 | fobj = @F2; 39 | lb=-10; 40 | ub=10; 41 | dim=30; 42 | 43 | case 'F3' 44 | fobj = @F3; 45 | lb=-100; 46 | ub=100; 47 | dim=30; 48 | 49 | case 'F4' 50 | fobj = @F4; 51 | lb=-100; 52 | ub=100; 53 | dim=30; 54 | 55 | case 'F5' 56 | fobj = @F5; 57 | lb=-30; 58 | ub=30; 59 | dim=30; 60 | 61 | case 'F6' 62 | fobj = @F6; 63 | lb=-100; 64 | ub=100; 65 | dim=30; 66 | 67 | case 'F7' 68 | fobj = @F7; 69 | lb=-1.28; 70 | ub=1.28; 71 | dim=30; 72 | 73 | case 'F8' 74 | fobj = @F8; 75 | lb=-500; 76 | ub=500; 77 | dim=30; 78 | 79 | case 'F9' 80 | fobj = @F9; 81 | lb=-5.12; 82 | ub=5.12; 83 | dim=30; 84 | 85 | case 'F10' 86 | fobj = @F10; 87 | lb=-32; 88 | ub=32; 89 | dim=30; 90 | 91 | case 'F11' 92 | fobj = @F11; 93 | lb=-600; 94 | ub=600; 95 | dim=30; 96 | 97 | case 'F12' 98 | fobj = @F12; 99 | lb=-50; 100 | ub=50; 101 | dim=30; 102 | 103 | case 'F13' 104 | fobj = @F13; 105 | lb=-50; 106 | ub=50; 107 | dim=30; 108 | 109 | case 'F14' 110 | fobj = @F14; 111 | lb=-65.536; 112 | ub=65.536; 113 | dim=2; 114 | 115 | case 'F15' 116 | fobj = @F15; 117 | lb=-5; 118 | ub=5; 119 | dim=4; 120 | 121 | case 'F16' 122 | fobj = @F16; 123 | lb=-5; 124 | ub=5; 125 | dim=2; 126 | 127 | case 'F17' 128 | fobj = @F17; 129 | lb=[-5,0]; 130 | ub=[10,15]; 131 | dim=2; 132 | 133 | case 'F18' 134 | fobj = @F18; 135 | lb=-2; 136 | ub=2; 137 | dim=2; 138 | 139 | case 'F19' 140 | fobj = @F19; 141 | lb=0; 142 | ub=1; 143 | dim=3; 144 | 145 | case 'F20' 146 | fobj = @F20; 147 | lb=0; 148 | ub=1; 149 | dim=6; 150 | 151 | case 'F21' 152 | fobj = @F21; 153 | lb=0; 154 | ub=10; 155 | dim=4; 156 | 157 | case 'F22' 158 | fobj = @F22; 159 | lb=0; 160 | ub=10; 161 | dim=4; 162 | 163 | case 'F23' 164 | fobj = @F23; 165 | lb=0; 166 | ub=10; 167 | dim=4; 168 | end 169 | 170 | end 171 | 172 | % F1 173 | 174 | function o = F1(x) 175 | o=sum(x.^2); 176 | end 177 | 178 | % F2 179 | 180 | function o = F2(x) 181 | o=sum(abs(x))+prod(abs(x)); 182 | end 183 | 184 | % F3 185 | 186 | function o = F3(x) 187 | dim=size(x,2); 188 | o=0; 189 | for i=1:dim 190 | o=o+sum(x(1:i))^2; 191 | end 192 | end 193 | 194 | % F4 195 | 196 | function o = F4(x) 197 | o=max(abs(x)); 198 | end 199 | 200 | % F5 201 | 202 | function o = F5(x) 203 | dim=size(x,2); 204 | o=sum(100*(x(2:dim)-(x(1:dim-1).^2)).^2+(x(1:dim-1)-1).^2); 205 | end 206 | 207 | % F6 208 | 209 | function o = F6(x) 210 | o=sum(abs((x+.5)).^2); 211 | end 212 | 213 | % F7 214 | 215 | function o = F7(x) 216 | dim=size(x,2); 217 | o=sum([1:dim].*(x.^4))+rand; 218 | end 219 | 220 | % F8 221 | 222 | function o = F8(x) 223 | o=sum(-x.*sin(sqrt(abs(x)))); 224 | end 225 | 226 | % F9 227 | 228 | function o = F9(x) 229 | dim=size(x,2); 230 | o=sum(x.^2-10*cos(2*pi.*x))+10*dim; 231 | end 232 | 233 | % F10 234 | 235 | function o = F10(x) 236 | dim=size(x,2); 237 | o=-20*exp(-.2*sqrt(sum(x.^2)/dim))-exp(sum(cos(2*pi.*x))/dim)+20+exp(1); 238 | end 239 | 240 | % F11 241 | 242 | function o = F11(x) 243 | dim=size(x,2); 244 | o=sum(x.^2)/4000-prod(cos(x./sqrt([1:dim])))+1; 245 | end 246 | 247 | % F12 248 | 249 | function o = F12(x) 250 | dim=size(x,2); 251 | o=(pi/dim)*(10*((sin(pi*(1+(x(1)+1)/4)))^2)+sum((((x(1:dim-1)+1)./4).^2).*... 252 | (1+10.*((sin(pi.*(1+(x(2:dim)+1)./4)))).^2))+((x(dim)+1)/4)^2)+sum(Ufun(x,10,100,4)); 253 | end 254 | 255 | % F13 256 | 257 | function o = F13(x) 258 | dim=size(x,2); 259 | o=.1*((sin(3*pi*x(1)))^2+sum((x(1:dim-1)-1).^2.*(1+(sin(3.*pi.*x(2:dim))).^2))+... 260 | ((x(dim)-1)^2)*(1+(sin(2*pi*x(dim)))^2))+sum(Ufun(x,5,100,4)); 261 | end 262 | 263 | % F14 264 | 265 | function o = F14(x) 266 | aS=[-32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32 -32 -16 0 16 32;,... 267 | -32 -32 -32 -32 -32 -16 -16 -16 -16 -16 0 0 0 0 0 16 16 16 16 16 32 32 32 32 32]; 268 | 269 | for j=1:25 270 | bS(j)=sum((x'-aS(:,j)).^6); 271 | end 272 | o=(1/500+sum(1./([1:25]+bS))).^(-1); 273 | end 274 | 275 | % F15 276 | 277 | function o = F15(x) 278 | aK=[.1957 .1947 .1735 .16 .0844 .0627 .0456 .0342 .0323 .0235 .0246]; 279 | bK=[.25 .5 1 2 4 6 8 10 12 14 16];bK=1./bK; 280 | o=sum((aK-((x(1).*(bK.^2+x(2).*bK))./(bK.^2+x(3).*bK+x(4)))).^2); 281 | end 282 | 283 | % F16 284 | 285 | function o = F16(x) 286 | o=4*(x(1)^2)-2.1*(x(1)^4)+(x(1)^6)/3+x(1)*x(2)-4*(x(2)^2)+4*(x(2)^4); 287 | end 288 | 289 | % F17 290 | 291 | function o = F17(x) 292 | o=(x(2)-(x(1)^2)*5.1/(4*(pi^2))+5/pi*x(1)-6)^2+10*(1-1/(8*pi))*cos(x(1))+10; 293 | end 294 | 295 | % F18 296 | 297 | function o = F18(x) 298 | o=(1+(x(1)+x(2)+1)^2*(19-14*x(1)+3*(x(1)^2)-14*x(2)+6*x(1)*x(2)+3*x(2)^2))*... 299 | (30+(2*x(1)-3*x(2))^2*(18-32*x(1)+12*(x(1)^2)+48*x(2)-36*x(1)*x(2)+27*(x(2)^2))); 300 | end 301 | 302 | % F19 303 | 304 | function o = F19(x) 305 | aH=[3 10 30;.1 10 35;3 10 30;.1 10 35];cH=[1 1.2 3 3.2]; 306 | pH=[.3689 .117 .2673;.4699 .4387 .747;.1091 .8732 .5547;.03815 .5743 .8828]; 307 | o=0; 308 | for i=1:4 309 | o=o-cH(i)*exp(-(sum(aH(i,:).*((x-pH(i,:)).^2)))); 310 | end 311 | end 312 | 313 | % F20 314 | 315 | function o = F20(x) 316 | aH=[10 3 17 3.5 1.7 8;.05 10 17 .1 8 14;3 3.5 1.7 10 17 8;17 8 .05 10 .1 14]; 317 | cH=[1 1.2 3 3.2]; 318 | pH=[.1312 .1696 .5569 .0124 .8283 .5886;.2329 .4135 .8307 .3736 .1004 .9991;... 319 | .2348 .1415 .3522 .2883 .3047 .6650;.4047 .8828 .8732 .5743 .1091 .0381]; 320 | o=0; 321 | for i=1:4 322 | o=o-cH(i)*exp(-(sum(aH(i,:).*((x-pH(i,:)).^2)))); 323 | end 324 | end 325 | 326 | % F21 327 | 328 | function o = F21(x) 329 | aSH=[4 4 4 4;1 1 1 1;8 8 8 8;6 6 6 6;3 7 3 7;2 9 2 9;5 5 3 3;8 1 8 1;6 2 6 2;7 3.6 7 3.6]; 330 | cSH=[.1 .2 .2 .4 .4 .6 .3 .7 .5 .5]; 331 | 332 | o=0; 333 | for i=1:5 334 | o=o-((x-aSH(i,:))*(x-aSH(i,:))'+cSH(i))^(-1); 335 | end 336 | end 337 | 338 | % F22 339 | 340 | function o = F22(x) 341 | aSH=[4 4 4 4;1 1 1 1;8 8 8 8;6 6 6 6;3 7 3 7;2 9 2 9;5 5 3 3;8 1 8 1;6 2 6 2;7 3.6 7 3.6]; 342 | cSH=[.1 .2 .2 .4 .4 .6 .3 .7 .5 .5]; 343 | 344 | o=0; 345 | for i=1:7 346 | o=o-((x-aSH(i,:))*(x-aSH(i,:))'+cSH(i))^(-1); 347 | end 348 | end 349 | 350 | % F23 351 | 352 | function o = F23(x) 353 | aSH=[4 4 4 4;1 1 1 1;8 8 8 8;6 6 6 6;3 7 3 7;2 9 2 9;5 5 3 3;8 1 8 1;6 2 6 2;7 3.6 7 3.6]; 354 | cSH=[.1 .2 .2 .4 .4 .6 .3 .7 .5 .5]; 355 | 356 | o=0; 357 | for i=1:10 358 | o=o-((x-aSH(i,:))*(x-aSH(i,:))'+cSH(i))^(-1); 359 | end 360 | end 361 | 362 | function o=Ufun(x,a,k,m) 363 | o=k.*((x-a).^m).*(x>a)+k.*((-x-a).^m).*(x<(-a)); 364 | end -------------------------------------------------------------------------------- /WOA/WOA.m: -------------------------------------------------------------------------------- 1 | %_________________________________________________________________________% 2 | % Whale Optimization Algorithm (WOA) source codes demo 1.0 % 3 | % % 4 | % Developed in MATLAB R2011b(7.13) % 5 | % % 6 | % Author and programmer: Seyedali Mirjalili % 7 | % % 8 | % e-Mail: ali.mirjalili@gmail.com % 9 | % seyedali.mirjalili@griffithuni.edu.au % 10 | % % 11 | % Homepage: http://www.alimirjalili.com % 12 | % % 13 | % Main paper: S. Mirjalili, A. Lewis % 14 | % The Whale Optimization Algorithm, % 15 | % Advances in Engineering Software , in press, % 16 | % DOI: http://dx.doi.org/10.1016/j.advengsoft.2016.01.008 % 17 | % % 18 | %_________________________________________________________________________% 19 | 20 | 21 | % The Whale Optimization Algorithm 22 | function [Leader_score,Leader_pos,Convergence_curve]=WOA(SearchAgents_no,Max_iter,lb,ub,dim,fobj) 23 | 24 | % initialize position vector and score for the leader 25 | Leader_pos=zeros(1,dim); 26 | Leader_score=inf; %change this to -inf for maximization problems 27 | 28 | 29 | %Initialize the positions of search agents 30 | Positions=initialization(SearchAgents_no,dim,ub,lb); 31 | 32 | Convergence_curve=zeros(1,Max_iter); 33 | 34 | t=0;% Loop counter 35 | 36 | % Main loop 37 | while tub; 42 | Flag4lb=Positions(i,:) for maximization problem 50 | Leader_score=fitness; % Update alpha 51 | Leader_pos=Positions(i,:); 52 | end 53 | 54 | end 55 | 56 | a=2-t*((2)/Max_iter); % a decreases linearly fron 2 to 0 in Eq. (2.3) 57 | 58 | % a2 linearly dicreases from -1 to -2 to calculate t in Eq. (3.12) 59 | a2=-1+t*((-1)/Max_iter); 60 | 61 | % Update the Position of search agents 62 | for i=1:size(Positions,1) 63 | r1=rand(); % r1 is a random number in [0,1] 64 | r2=rand(); % r2 is a random number in [0,1] 65 | 66 | A=2*a*r1-a; % Eq. (2.3) in the paper 67 | C=2*r2; % Eq. (2.4) in the paper 68 | 69 | 70 | b=1; % parameters in Eq. (2.5) 71 | l=(a2-1)*rand+1; % parameters in Eq. (2.5) 72 | 73 | p = rand(); % p in Eq. (2.6) 74 | 75 | for j=1:size(Positions,2) 76 | 77 | if p<0.5 78 | if abs(A)>=1 79 | rand_leader_index = floor(SearchAgents_no*rand()+1); 80 | X_rand = Positions(rand_leader_index, :); 81 | D_X_rand=abs(C*X_rand(j)-Positions(i,j)); % Eq. (2.7) 82 | Positions(i,j)=X_rand(j)-A*D_X_rand; % Eq. (2.8) 83 | 84 | elseif abs(A)<1 85 | D_Leader=abs(C*Leader_pos(j)-Positions(i,j)); % Eq. (2.1) 86 | Positions(i,j)=Leader_pos(j)-A*D_Leader; % Eq. (2.2) 87 | end 88 | 89 | elseif p>=0.5 90 | 91 | distance2Leader=abs(Leader_pos(j)-Positions(i,j)); 92 | % Eq. (2.5) 93 | Positions(i,j)=distance2Leader*exp(b.*l).*cos(l.*2*pi)+Leader_pos(j); 94 | 95 | end 96 | 97 | end 98 | end 99 | t=t+1; 100 | Convergence_curve(t)=Leader_score; 101 | [t Leader_score] 102 | end 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /WOA/WOA.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/WOA/WOA.pdf -------------------------------------------------------------------------------- /WOA/WOA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/WOA/WOA.png -------------------------------------------------------------------------------- /WOA/func_plot.m: -------------------------------------------------------------------------------- 1 | %_________________________________________________________________________% 2 | % Whale Optimization Algorithm (WOA) source codes demo 1.0 % 3 | % % 4 | % Developed in MATLAB R2011b(7.13) % 5 | % % 6 | % Author and programmer: Seyedali Mirjalili % 7 | % % 8 | % e-Mail: ali.mirjalili@gmail.com % 9 | % seyedali.mirjalili@griffithuni.edu.au % 10 | % % 11 | % Homepage: http://www.alimirjalili.com % 12 | % % 13 | % Main paper: S. Mirjalili, A. Lewis % 14 | % The Whale Optimization Algorithm, % 15 | % Advances in Engineering Software , in press, % 16 | % DOI: http://dx.doi.org/10.1016/j.advengsoft.2016.01.008 % 17 | % % 18 | %_________________________________________________________________________% 19 | 20 | % This function draw the benchmark functions 21 | 22 | function func_plot(func_name) 23 | 24 | [lb,ub,dim,fobj]=Get_Functions_details(func_name); 25 | 26 | switch func_name 27 | case 'F1' 28 | x=-100:2:100; y=x; %[-100,100] 29 | 30 | case 'F2' 31 | x=-100:2:100; y=x; %[-10,10] 32 | 33 | case 'F3' 34 | x=-100:2:100; y=x; %[-100,100] 35 | 36 | case 'F4' 37 | x=-100:2:100; y=x; %[-100,100] 38 | case 'F5' 39 | x=-200:2:200; y=x; %[-5,5] 40 | case 'F6' 41 | x=-100:2:100; y=x; %[-100,100] 42 | case 'F7' 43 | x=-1:0.03:1; y=x %[-1,1] 44 | case 'F8' 45 | x=-500:10:500;y=x; %[-500,500] 46 | case 'F9' 47 | x=-5:0.1:5; y=x; %[-5,5] 48 | case 'F10' 49 | x=-20:0.5:20; y=x;%[-500,500] 50 | case 'F11' 51 | x=-500:10:500; y=x;%[-0.5,0.5] 52 | case 'F12' 53 | x=-10:0.1:10; y=x;%[-pi,pi] 54 | case 'F13' 55 | x=-5:0.08:5; y=x;%[-3,1] 56 | case 'F14' 57 | x=-100:2:100; y=x;%[-100,100] 58 | case 'F15' 59 | x=-5:0.1:5; y=x;%[-5,5] 60 | case 'F16' 61 | x=-1:0.01:1; y=x;%[-5,5] 62 | case 'F17' 63 | x=-5:0.1:5; y=x;%[-5,5] 64 | case 'F18' 65 | x=-5:0.06:5; y=x;%[-5,5] 66 | case 'F19' 67 | x=-5:0.1:5; y=x;%[-5,5] 68 | case 'F20' 69 | x=-5:0.1:5; y=x;%[-5,5] 70 | case 'F21' 71 | x=-5:0.1:5; y=x;%[-5,5] 72 | case 'F22' 73 | x=-5:0.1:5; y=x;%[-5,5] 74 | case 'F23' 75 | x=-5:0.1:5; y=x;%[-5,5] 76 | end 77 | 78 | 79 | 80 | L=length(x); 81 | f=[]; 82 | 83 | for i=1:L 84 | for j=1:L 85 | if strcmp(func_name,'F15')==0 && strcmp(func_name,'F19')==0 && strcmp(func_name,'F20')==0 && strcmp(func_name,'F21')==0 && strcmp(func_name,'F22')==0 && strcmp(func_name,'F23')==0 86 | f(i,j)=fobj([x(i),y(j)]); 87 | end 88 | if strcmp(func_name,'F15')==1 89 | f(i,j)=fobj([x(i),y(j),0,0]); 90 | end 91 | if strcmp(func_name,'F19')==1 92 | f(i,j)=fobj([x(i),y(j),0]); 93 | end 94 | if strcmp(func_name,'F20')==1 95 | f(i,j)=fobj([x(i),y(j),0,0,0,0]); 96 | end 97 | if strcmp(func_name,'F21')==1 || strcmp(func_name,'F22')==1 ||strcmp(func_name,'F23')==1 98 | f(i,j)=fobj([x(i),y(j),0,0]); 99 | end 100 | end 101 | end 102 | 103 | surfc(x,y,f,'LineStyle','none'); 104 | 105 | end 106 | 107 | -------------------------------------------------------------------------------- /WOA/initialization.m: -------------------------------------------------------------------------------- 1 | %_________________________________________________________________________% 2 | % Whale Optimization Algorithm (WOA) source codes demo 1.0 % 3 | % % 4 | % Developed in MATLAB R2011b(7.13) % 5 | % % 6 | % Author and programmer: Seyedali Mirjalili % 7 | % % 8 | % e-Mail: ali.mirjalili@gmail.com % 9 | % seyedali.mirjalili@griffithuni.edu.au % 10 | % % 11 | % Homepage: http://www.alimirjalili.com % 12 | % % 13 | % Main paper: S. Mirjalili, A. Lewis % 14 | % The Whale Optimization Algorithm, % 15 | % Advances in Engineering Software , in press, % 16 | % DOI: http://dx.doi.org/10.1016/j.advengsoft.2016.01.008 % 17 | % % 18 | %_________________________________________________________________________% 19 | 20 | % This function initialize the first population of search agents 21 | function Positions=initialization(SearchAgents_no,dim,ub,lb) 22 | 23 | Boundary_no= size(ub,2); % numnber of boundaries 24 | 25 | % If the boundaries of all variables are equal and user enter a signle 26 | % number for both ub and lb 27 | if Boundary_no==1 28 | Positions=rand(SearchAgents_no,dim).*(ub-lb)+lb; 29 | end 30 | 31 | % If each variable has a different lb and ub 32 | if Boundary_no>1 33 | for i=1:dim 34 | ub_i=ub(i); 35 | lb_i=lb(i); 36 | Positions(:,i)=rand(SearchAgents_no,1).*(ub_i-lb_i)+lb_i; 37 | end 38 | end -------------------------------------------------------------------------------- /WOA/main.m: -------------------------------------------------------------------------------- 1 | %_________________________________________________________________________% 2 | % Whale Optimization Algorithm (WOA) source codes demo 1.0 % 3 | % % 4 | % Developed in MATLAB R2011b(7.13) % 5 | % % 6 | % Author and programmer: Seyedali Mirjalili % 7 | % % 8 | % e-Mail: ali.mirjalili@gmail.com % 9 | % seyedali.mirjalili@griffithuni.edu.au % 10 | % % 11 | % Homepage: http://www.alimirjalili.com % 12 | % % 13 | % Main paper: S. Mirjalili, A. Lewis % 14 | % The Whale Optimization Algorithm, % 15 | % Advances in Engineering Software , in press, % 16 | % DOI: http://dx.doi.org/10.1016/j.advengsoft.2016.01.008 % 17 | % % 18 | %_________________________________________________________________________% 19 | 20 | % You can simply define your cost in a seperate file and load its handle to fobj 21 | % The initial parameters that you need are: 22 | %__________________________________________ 23 | % fobj = @YourCostFunction 24 | % dim = number of your variables 25 | % Max_iteration = maximum number of generations 26 | % SearchAgents_no = number of search agents 27 | % lb=[lb1,lb2,...,lbn] where lbn is the lower bound of variable n 28 | % ub=[ub1,ub2,...,ubn] where ubn is the upper bound of variable n 29 | % If all the variables have equal lower bound you can just 30 | % define lb and ub as two single number numbers 31 | 32 | % To run WOA: [Best_score,Best_pos,WOA_cg_curve]=WOA(SearchAgents_no,Max_iteration,lb,ub,dim,fobj) 33 | %__________________________________________ 34 | 35 | clear all 36 | clc 37 | 38 | SearchAgents_no=30; % Number of search agents 39 | 40 | Function_name='F1'; % Name of the test function that can be from F1 to F23 (Table 1,2,3 in the paper) 41 | 42 | Max_iteration=500; % Maximum numbef of iterations 43 | 44 | % Load details of the selected benchmark function 45 | [lb,ub,dim,fobj]=Get_Functions_details(Function_name); 46 | 47 | [Best_score,Best_pos,WOA_cg_curve]=WOA(SearchAgents_no,Max_iteration,lb,ub,dim,fobj); 48 | 49 | figure('Position',[269 240 660 290]) 50 | %Draw search space 51 | subplot(1,2,1); 52 | func_plot(Function_name); 53 | title('Parameter space') 54 | xlabel('x_1'); 55 | ylabel('x_2'); 56 | zlabel([Function_name,'( x_1 , x_2 )']) 57 | 58 | %Draw objective space 59 | subplot(1,2,2); 60 | semilogy(WOA_cg_curve,'Color','r') 61 | title('Objective space') 62 | xlabel('Iteration'); 63 | ylabel('Best score obtained so far'); 64 | 65 | axis tight 66 | grid on 67 | box on 68 | legend('WOA') 69 | 70 | display(['The best solution obtained by WOA is : ', num2str(Best_pos)]); 71 | display(['The best optimal value of the objective funciton found by WOA is : ', num2str(Best_score)]); 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /otsu/3096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/otsu/3096.jpg -------------------------------------------------------------------------------- /otsu/Otsu_Test.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/otsu/Otsu_Test.m -------------------------------------------------------------------------------- /分水岭阈值分割/watershed_Test2.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/分水岭阈值分割/watershed_Test2.m -------------------------------------------------------------------------------- /分水岭阈值分割/watershed_demo.m: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AomanHao/Matlab-Image-Segment/d1fdd270d02a6e2b7acf79a789337e01f8cb6a22/分水岭阈值分割/watershed_demo.m --------------------------------------------------------------------------------