├── Algorithms ├── GMMGrabCutAlgorithm.m ├── GMMGrabCutAlgorithm.m~ ├── GMMGraphCutAlgorithm.m ├── interactive_graphcut.cpp ├── interactive_graphcut.mexmaci64 ├── interactive_graphcut.mexw64 ├── make.m └── maxflow-v3.0 │ ├── CHANGES.TXT │ ├── README.TXT │ ├── block.h │ ├── graph.cpp │ ├── graph.h │ ├── instances.inc │ └── maxflow.cpp ├── LICENSE ├── README.md ├── images ├── black_car.png ├── blue_car.png ├── carsten.jpg ├── fish.png ├── flowers.png ├── flowers_gray.png ├── food.bmp ├── grab_cut_snapshot.png ├── graph_cut_snapshot.png ├── horse.jpg ├── llama.bmp ├── ls.bmp └── man.png ├── mouse_down.m ├── mouse_move.m ├── mouse_up.m ├── ui_update.m ├── user_interface.fig └── user_interface.m /Algorithms/GMMGrabCutAlgorithm.m: -------------------------------------------------------------------------------- 1 | classdef GMMGrabCutAlgorithm %< CoreBaseClass 2 | properties 3 | FgGMM; 4 | BgGMM; 5 | k; % number of components 6 | iter; % number of iteration 7 | lambda; % graph cut parameter, weight of pairwise potential (1.0-20.0) 8 | sigma; % grapu cut parameter, control itensity difference (5.0-20.0) 9 | end 10 | methods 11 | function obj = GMMGrabCutAlgorithm() 12 | obj.FgGMM = gmdistribution(); 13 | obj.BgGMM = gmdistribution(); 14 | end 15 | 16 | % image: input color image with rgb channels 17 | % mask: maks of foreground or background 0--background,1--foreground 18 | % seeds: user-provided scribbles 127--foreground, 255-background 19 | function out = Segment(obj, image, mask, seeds) 20 | D = length(size(image)); 21 | if(D==2) 22 | [H,W]=size(image); 23 | C=1; 24 | else 25 | [H, W, C]=size(image); 26 | end 27 | Ireshape = double(reshape(image,[H*W,C])); 28 | seeds(mask==0)=255; 29 | 30 | obj.lambda = 10.0; 31 | obj.sigma = 40.0; 32 | obj.k = 3; 33 | obj.iter = 5; 34 | 35 | out = mask; 36 | for i = 1: obj.iter 37 | out = update_step(obj, image, Ireshape, out, seeds); 38 | end 39 | end 40 | 41 | function out = update_step(obj, image, Ireshape, init_seg, seeds) 42 | [H, W] = size(init_seg); 43 | Mreshape = reshape(init_seg,[H*W,1]); 44 | FData = Ireshape(Mreshape==1,:); 45 | BData = Ireshape(Mreshape==0,:); 46 | obj.FgGMM = fitgmdist(FData,obj.k, 'RegularizationValue',0.1); 47 | obj.BgGMM = fitgmdist(BData,obj.k, 'RegularizationValue',0.1); 48 | 49 | Fprob = obj.FgGMM.pdf(Ireshape); 50 | Bprob = obj.BgGMM.pdf(Ireshape); 51 | 52 | [flow, out]=interactive_graphcut(double(image),seeds,Fprob, Bprob,obj.lambda,obj.sigma); 53 | out=1-out; 54 | end 55 | end 56 | end -------------------------------------------------------------------------------- /Algorithms/GMMGrabCutAlgorithm.m~: -------------------------------------------------------------------------------- 1 | classdef GMMGrabCutAlgorithm %< CoreBaseClass 2 | properties 3 | FgGMM; 4 | BgGMM; 5 | k; % number of components 6 | iter; % number of iteration 7 | lambda; % graph cut parameter, weight of pairwise potential (1.0-20.0) 8 | sigma; % grapu cut parameter, control itensity difference (5.0-20.0) 9 | end 10 | methods 11 | function obj = GMMGrabCutAlgorithm() 12 | end 13 | 14 | % image: input color image with rgb channels 15 | % mask: maks of foreground or background 0--background,1--foreground 16 | % seeds: user-provided scribbles 127--foreground, 255-background 17 | function out = Segment(obj, image, mask, seeds) 18 | D = length(size(image)); 19 | if(D==2) 20 | [H,W]=size(image); 21 | C=1; 22 | else 23 | [H, W, C]=size(image); 24 | end 25 | 26 | [H, W, C] = size(image); 27 | Ireshape = double(reshape(image,[H*W,C])); 28 | seeds(mask==0)=255; 29 | 30 | obj.FgGMM = gmdistribution(); 31 | obj.BgGMM = gmdistribution(); 32 | obj.lambda = 5.0; 33 | obj.sigma = 40.0; 34 | obj.k = 5; 35 | obj.iter = 5; 36 | 37 | out = mask; 38 | for i = 1: obj.iter 39 | out = update_step(obj, image, Ireshape, out, seeds); 40 | end 41 | end 42 | 43 | function out = update_step(obj, image, Ireshape, init_seg, seeds) 44 | [H, W] = size(init_seg); 45 | Mreshape = reshape(init_seg,[H*W,1]); 46 | FData = Ireshape(Mreshape==1,:); 47 | BData = Ireshape(Mreshape==0,:); 48 | obj.FgGMM = fitgmdist(FData,obj.k); 49 | obj.BgGMM = fitgmdist(BData,obj.k); 50 | 51 | Fprob = obj.FgGMM.pdf(Ireshape); 52 | Bprob = obj.BgGMM.pdf(Ireshape); 53 | 54 | [flow, out]=interactive_graphcut(double(image),seeds,Fprob, Bprob,obj.lambda,obj.sigma); 55 | out=1-out; 56 | end 57 | end 58 | end -------------------------------------------------------------------------------- /Algorithms/GMMGraphCutAlgorithm.m: -------------------------------------------------------------------------------- 1 | classdef GMMGraphCutAlgorithm %< CoreBaseClass 2 | properties 3 | FgGMM; 4 | BgGMM; 5 | 6 | lambda; 7 | sigma; 8 | k; 9 | end 10 | methods 11 | function obj = GMMGraphCutAlgorithm() 12 | obj.FgGMM = gmdistribution(); 13 | obj.BgGMM = gmdistribution(); 14 | end 15 | function out = Segment(obj, image, seeds) 16 | D = length(size(image)); 17 | if(D==2) 18 | [H,W]=size(image); 19 | C=1; 20 | else 21 | [H, W, C]=size(image); 22 | end 23 | Ireshape = double(reshape(image,[H*W,C])); 24 | 25 | obj.lambda = 10.0; 26 | obj.sigma = 40.0; 27 | obj.k = 3; 28 | 29 | Mreshape = reshape(seeds,[H*W,1]); 30 | FData = Ireshape(Mreshape==127,:); 31 | BData = Ireshape(Mreshape==255,:); 32 | obj.FgGMM = fitgmdist(FData,obj.k, 'RegularizationValue',0.1); 33 | obj.BgGMM = fitgmdist(BData,obj.k, 'RegularizationValue',0.1); 34 | 35 | Fprob = obj.FgGMM.pdf(Ireshape); 36 | Bprob = obj.BgGMM.pdf(Ireshape); 37 | 38 | [flow, out]=interactive_graphcut(double(image),seeds,Fprob, Bprob,obj.lambda,obj.sigma); 39 | out=1-out; 40 | end 41 | end 42 | end -------------------------------------------------------------------------------- /Algorithms/interactive_graphcut.cpp: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------ 2 | // guotai wang 3 | // guotai.wang.14@ucl.ac.uk 4 | // 9 Dec, 2014 5 | // interactive graphcut 6 | //------------------------------------------------------------------------ 7 | 8 | #include "mex.h" 9 | #include "maxflow-v3.0/graph.h" 10 | #include 11 | #include 12 | #define FOREGROUND_LABEL 127 13 | #define BACKGROUND_LABEL 255 14 | using namespace std; 15 | 16 | // [flow label]=interactive_graphcut(I,Seeds,foregroundProb,backgroundProb, lambda,sigma); 17 | // I --input graylevel or rgb image. type: double 18 | // Seeds -- 2D image storing scribbles. type: unsigned char. 127--foreground, 255--background 19 | // foregroundProb -- Probability of being foreground. type: double 20 | // foregroundProb -- Probability of being background. type: double 21 | // lambda --CRF parameter, weight of pairwise potential. (1.0, 20.0) 22 | // sigma --CRF parameter, control the significance of itensity difference (5.0, 20.0) 23 | void mexFunction(int nlhs, /* number of expected outputs */ 24 | mxArray *plhs[], /* mxArray output pointer array */ 25 | int nrhs, /* number of inputs */ 26 | const mxArray *prhs[] /* mxArray input pointer array */) 27 | { 28 | // input checks 29 | if (nrhs != 6 ) 30 | { 31 | mexErrMsgTxt ("USAGE: [flow label]=interactive_graphcut(I,Seeds,foregroundProb,backgroundProb,lambda,sigma);"); 32 | } 33 | const mxArray *I = prhs[0]; 34 | const mxArray *Seed = prhs[1]; 35 | const mxArray *FProb = prhs[2]; 36 | const mxArray *BProb = prhs[3]; 37 | double lamda=* mxGetPr(prhs[4]); 38 | double sigma= * mxGetPr(prhs[5]); 39 | 40 | double * IPr=(double *)mxGetPr(I); 41 | unsigned char * SeedPr=(unsigned char *)mxGetPr(Seed); 42 | double * FProbPr = mxGetPr(FProb); 43 | double * BProbPr = mxGetPr(BProb); 44 | 45 | int D = mxGetNumberOfDimensions(I); 46 | const mwSize * Ishape = mxGetDimensions(I); 47 | int channel = (D==2)?1:Ishape[2]; 48 | 49 | // size of image 50 | mwSize m = Ishape[0];//mxGetM(I);//height, number of rows 51 | mwSize n = Ishape[1];//mxGetN(I);//width, number of columns 52 | 53 | //construct graph 54 | typedef Graph GraphType; 55 | GraphType *g = new GraphType(/*estimated # of nodes*/ m*n, /*estimated # of edges*/ 2*m*n); 56 | g->add_node(m*n); 57 | float maxWeight=-1e20; 58 | for(int x=0;x(y,x); 65 | int uperPointx=x; 66 | int uperPointy=y-1; 67 | int LeftPointx=x-1; 68 | int LeftPointy=y; 69 | float n_weight=0; 70 | if(uperPointy>=0 && uperPointyadd_edge(qIndex,pIndex,n_weight,n_weight); 84 | } 85 | if(LeftPointx>=0 && LeftPointxadd_edge(qIndex,pIndex,n_weight,n_weight); 98 | } 99 | if(n_weight>maxWeight) 100 | { 101 | maxWeight=n_weight; 102 | } 103 | } 104 | } 105 | maxWeight=1e10; 106 | 107 | for(int x=0;xadd_tweights(pIndex,s_weight,t_weight); 133 | } 134 | } 135 | // return the results 136 | plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); 137 | double* flow = mxGetPr(plhs[0]); 138 | *flow = g->maxflow(); 139 | printf("max flow: %f\n",*flow); 140 | 141 | // figure out segmentation 142 | plhs[1] = mxCreateNumericMatrix(m, n, mxUINT8_CLASS, mxREAL); 143 | unsigned char * labels = (unsigned char*)mxGetData(plhs[1]); 144 | for (int x = 0; x < n; x++) 145 | { 146 | for (int y=0;ywhat_segment(Index); 150 | } 151 | } 152 | // cleanup 153 | delete g; 154 | } 155 | 156 | -------------------------------------------------------------------------------- /Algorithms/interactive_graphcut.mexmaci64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/Algorithms/interactive_graphcut.mexmaci64 -------------------------------------------------------------------------------- /Algorithms/interactive_graphcut.mexw64: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/Algorithms/interactive_graphcut.mexw64 -------------------------------------------------------------------------------- /Algorithms/make.m: -------------------------------------------------------------------------------- 1 | %MAKE Compiles the maxflowmex library. 2 | 3 | mex interactive_graphcut.cpp maxflow-v3.0/graph.cpp maxflow-v3.0/maxflow.cpp 4 | -------------------------------------------------------------------------------- /Algorithms/maxflow-v3.0/CHANGES.TXT: -------------------------------------------------------------------------------- 1 | List of changes from version 3.0: 2 | - Moved line 3 | #include "instances.inc" 4 | to the end of cpp files to make it compile under GNU c++ compilers 4.2(?) and above 5 | 6 | List of changes from version 2.2: 7 | 8 | - Added functions for accessing graph structure, residual capacities, etc. 9 | (They are needed for implementing maxflow-based algorithms such as primal-dual algorithm for convex MRFs.) 10 | - Added option of reusing trees. 11 | - node_id's are now integers starting from 0. Thus, it is not necessary to store node_id's in a separate array. 12 | - Capacity types are now templated. 13 | - Fixed bug in block.h. (After Block::Reset, ScanFirst() and ScanNext() did not work properly). 14 | - Implementation with a forward star representation of the graph is no longer supported. (It needs less memory, but slightly slower than adjacency list representation.) If you still wish to use it, download version 2.2. 15 | - Note: version 3.0 is released under a different license than version 2.2. 16 | 17 | List of changes from version 2.1: 18 | 19 | - Put the code under GPL license 20 | 21 | List of changes from version 2.02: 22 | 23 | - Fixed a bug in the implementation that uses forward star representation 24 | 25 | List of changes from version 2.01: 26 | 27 | - Added new interface function - Graph::add_tweights(Node_id, captype, captype) 28 | (necessary for the "ENERGY" software package) 29 | 30 | -------------------------------------------------------------------------------- /Algorithms/maxflow-v3.0/README.TXT: -------------------------------------------------------------------------------- 1 | ################################################################### 2 | # # 3 | # MAXFLOW - software for computing mincut/maxflow in a graph # 4 | # Version 3.01 # 5 | # http://www.cs.ucl.ac.uk/staff/V.Kolmogorov/software.html # 6 | # # 7 | # Yuri Boykov (yuri@csd.uwo.ca) # 8 | # Vladimir Kolmogorov (v.kolmogorov@cs.ucl.ac.uk) # 9 | # 2001-2006 # 10 | # # 11 | ################################################################### 12 | 13 | 1. Introduction. 14 | 15 | This software library implements the maxflow algorithm described in 16 | 17 | "An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision." 18 | Yuri Boykov and Vladimir Kolmogorov. 19 | In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 20 | September 2004 21 | 22 | This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov 23 | at Siemens Corporate Research. To make it available for public use, 24 | it was later reimplemented by Vladimir Kolmogorov based on open publications. 25 | 26 | If you use this software for research purposes, you should cite 27 | the aforementioned paper in any resulting publication. 28 | 29 | ---------------------------------------------------------------------- 30 | 31 | REUSING TREES: 32 | 33 | Starting with version 3.0, there is a also an option of reusing search 34 | trees from one maxflow computation to the next, as described in 35 | 36 | "Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts." 37 | Pushmeet Kohli and Philip H.S. Torr 38 | International Conference on Computer Vision (ICCV), 2005 39 | 40 | If you use this option, you should cite 41 | the aforementioned paper in any resulting publication. 42 | 43 | Tested under windows, Visual C++ 6.0 compiler and unix (SunOS 5.8 44 | and RedHat Linux 7.0, GNU c++ compiler). 45 | 46 | ################################################################## 47 | 48 | 2. License & disclaimer. 49 | 50 | Copyright 2001-2006 Vladimir Kolmogorov (v.kolmogorov@cs.ucl.ac.uk), Yuri Boykov (yuri@csd.uwo.ca). 51 | 52 | This software can be used for research purposes only. 53 | If you require another license, you may consider using version 2.21 54 | (which implements exactly the same algorithm, but does not have the option of reusing search trees). 55 | 56 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 57 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 58 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 59 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 60 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 61 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 62 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 63 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 64 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 65 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 66 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 67 | 68 | ################################################################## 69 | 70 | 3. Example usage. 71 | 72 | This section shows how to use the library to compute 73 | a minimum cut on the following graph: 74 | 75 | SOURCE 76 | / \ 77 | 1/ \2 78 | / 3 \ 79 | node0 -----> node1 80 | | <----- | 81 | | 4 | 82 | \ / 83 | 5\ /6 84 | \ / 85 | SINK 86 | 87 | /////////////////////////////////////////////////// 88 | 89 | #include 90 | #include "graph.h" 91 | 92 | int main() 93 | { 94 | typedef Graph GraphType; 95 | GraphType *g = new GraphType(/*estimated # of nodes*/ 2, /*estimated # of edges*/ 1); 96 | 97 | g -> add_node(); 98 | g -> add_node(); 99 | 100 | g -> add_tweights( 0, /* capacities */ 1, 5 ); 101 | g -> add_tweights( 1, /* capacities */ 2, 6 ); 102 | g -> add_edge( 0, 1, /* capacities */ 3, 4 ); 103 | 104 | int flow = g -> maxflow(); 105 | 106 | printf("Flow = %d\n", flow); 107 | printf("Minimum cut:\n"); 108 | if (g->what_segment(0) == GraphType::SOURCE) 109 | printf("node0 is in the SOURCE set\n"); 110 | else 111 | printf("node0 is in the SINK set\n"); 112 | if (g->what_segment(1) == GraphType::SOURCE) 113 | printf("node1 is in the SOURCE set\n"); 114 | else 115 | printf("node1 is in the SINK set\n"); 116 | 117 | delete g; 118 | 119 | return 0; 120 | } 121 | 122 | 123 | /////////////////////////////////////////////////// 124 | -------------------------------------------------------------------------------- /Algorithms/maxflow-v3.0/block.h: -------------------------------------------------------------------------------- 1 | /* block.h */ 2 | /* 3 | Template classes Block and DBlock 4 | Implement adding and deleting items of the same type in blocks. 5 | 6 | If there there are many items then using Block or DBlock 7 | is more efficient than using 'new' and 'delete' both in terms 8 | of memory and time since 9 | (1) On some systems there is some minimum amount of memory 10 | that 'new' can allocate (e.g., 64), so if items are 11 | small that a lot of memory is wasted. 12 | (2) 'new' and 'delete' are designed for items of varying size. 13 | If all items has the same size, then an algorithm for 14 | adding and deleting can be made more efficient. 15 | (3) All Block and DBlock functions are inline, so there are 16 | no extra function calls. 17 | 18 | Differences between Block and DBlock: 19 | (1) DBlock allows both adding and deleting items, 20 | whereas Block allows only adding items. 21 | (2) Block has an additional operation of scanning 22 | items added so far (in the order in which they were added). 23 | (3) Block allows to allocate several consecutive 24 | items at a time, whereas DBlock can add only a single item. 25 | 26 | Note that no constructors or destructors are called for items. 27 | 28 | Example usage for items of type 'MyType': 29 | 30 | /////////////////////////////////////////////////// 31 | #include "block.h" 32 | #define BLOCK_SIZE 1024 33 | typedef struct { int a, b; } MyType; 34 | MyType *ptr, *array[10000]; 35 | 36 | ... 37 | 38 | Block *block = new Block(BLOCK_SIZE); 39 | 40 | // adding items 41 | for (int i=0; i New(); 44 | ptr -> a = ptr -> b = rand(); 45 | } 46 | 47 | // reading items 48 | for (ptr=block->ScanFirst(); ptr; ptr=block->ScanNext()) 49 | { 50 | printf("%d %d\n", ptr->a, ptr->b); 51 | } 52 | 53 | delete block; 54 | 55 | ... 56 | 57 | DBlock *dblock = new DBlock(BLOCK_SIZE); 58 | 59 | // adding items 60 | for (int i=0; i New(); 63 | } 64 | 65 | // deleting items 66 | for (int i=0; i Delete(array[i]); 69 | } 70 | 71 | // adding items 72 | for (int i=0; i New(); 75 | } 76 | 77 | delete dblock; 78 | 79 | /////////////////////////////////////////////////// 80 | 81 | Note that DBlock deletes items by marking them as 82 | empty (i.e., by adding them to the list of free items), 83 | so that this memory could be used for subsequently 84 | added items. Thus, at each moment the memory allocated 85 | is determined by the maximum number of items allocated 86 | simultaneously at earlier moments. All memory is 87 | deallocated only when the destructor is called. 88 | */ 89 | 90 | #ifndef __BLOCK_H__ 91 | #define __BLOCK_H__ 92 | 93 | #include 94 | 95 | /***********************************************************************/ 96 | /***********************************************************************/ 97 | /***********************************************************************/ 98 | 99 | template class Block 100 | { 101 | public: 102 | /* Constructor. Arguments are the block size and 103 | (optionally) the pointer to the function which 104 | will be called if allocation failed; the message 105 | passed to this function is "Not enough memory!" */ 106 | Block(int size, void (*err_function)(char *) = NULL) { first = last = NULL; block_size = size; error_function = err_function; } 107 | 108 | /* Destructor. Deallocates all items added so far */ 109 | ~Block() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } } 110 | 111 | /* Allocates 'num' consecutive items; returns pointer 112 | to the first item. 'num' cannot be greater than the 113 | block size since items must fit in one block */ 114 | Type *New(int num = 1) 115 | { 116 | Type *t; 117 | 118 | if (!last || last->current + num > last->last) 119 | { 120 | if (last && last->next) last = last -> next; 121 | else 122 | { 123 | block *next = (block *) new char [sizeof(block) + (block_size-1)*sizeof(Type)]; 124 | if (!next) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 125 | if (last) last -> next = next; 126 | else first = next; 127 | last = next; 128 | last -> current = & ( last -> data[0] ); 129 | last -> last = last -> current + block_size; 130 | last -> next = NULL; 131 | } 132 | } 133 | 134 | t = last -> current; 135 | last -> current += num; 136 | return t; 137 | } 138 | 139 | /* Returns the first item (or NULL, if no items were added) */ 140 | Type *ScanFirst() 141 | { 142 | for (scan_current_block=first; scan_current_block; scan_current_block = scan_current_block->next) 143 | { 144 | scan_current_data = & ( scan_current_block -> data[0] ); 145 | if (scan_current_data < scan_current_block -> current) return scan_current_data ++; 146 | } 147 | return NULL; 148 | } 149 | 150 | /* Returns the next item (or NULL, if all items have been read) 151 | Can be called only if previous ScanFirst() or ScanNext() 152 | call returned not NULL. */ 153 | Type *ScanNext() 154 | { 155 | while (scan_current_data >= scan_current_block -> current) 156 | { 157 | scan_current_block = scan_current_block -> next; 158 | if (!scan_current_block) return NULL; 159 | scan_current_data = & ( scan_current_block -> data[0] ); 160 | } 161 | return scan_current_data ++; 162 | } 163 | 164 | /* Marks all elements as empty */ 165 | void Reset() 166 | { 167 | block *b; 168 | if (!first) return; 169 | for (b=first; ; b=b->next) 170 | { 171 | b -> current = & ( b -> data[0] ); 172 | if (b == last) break; 173 | } 174 | last = first; 175 | } 176 | 177 | /***********************************************************************/ 178 | 179 | private: 180 | 181 | typedef struct block_st 182 | { 183 | Type *current, *last; 184 | struct block_st *next; 185 | Type data[1]; 186 | } block; 187 | 188 | int block_size; 189 | block *first; 190 | block *last; 191 | 192 | block *scan_current_block; 193 | Type *scan_current_data; 194 | 195 | void (*error_function)(char *); 196 | }; 197 | 198 | /***********************************************************************/ 199 | /***********************************************************************/ 200 | /***********************************************************************/ 201 | 202 | template class DBlock 203 | { 204 | public: 205 | /* Constructor. Arguments are the block size and 206 | (optionally) the pointer to the function which 207 | will be called if allocation failed; the message 208 | passed to this function is "Not enough memory!" */ 209 | DBlock(int size, void (*err_function)(char *) = NULL) { first = NULL; first_free = NULL; block_size = size; error_function = err_function; } 210 | 211 | /* Destructor. Deallocates all items added so far */ 212 | ~DBlock() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } } 213 | 214 | /* Allocates one item */ 215 | Type *New() 216 | { 217 | block_item *item; 218 | 219 | if (!first_free) 220 | { 221 | block *next = first; 222 | first = (block *) new char [sizeof(block) + (block_size-1)*sizeof(block_item)]; 223 | if (!first) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 224 | first_free = & (first -> data[0] ); 225 | for (item=first_free; item next_free = item + 1; 227 | item -> next_free = NULL; 228 | first -> next = next; 229 | } 230 | 231 | item = first_free; 232 | first_free = item -> next_free; 233 | return (Type *) item; 234 | } 235 | 236 | /* Deletes an item allocated previously */ 237 | void Delete(Type *t) 238 | { 239 | ((block_item *) t) -> next_free = first_free; 240 | first_free = (block_item *) t; 241 | } 242 | 243 | /***********************************************************************/ 244 | 245 | private: 246 | 247 | typedef union block_item_st 248 | { 249 | Type t; 250 | block_item_st *next_free; 251 | } block_item; 252 | 253 | typedef struct block_st 254 | { 255 | struct block_st *next; 256 | block_item data[1]; 257 | } block; 258 | 259 | int block_size; 260 | block *first; 261 | block_item *first_free; 262 | 263 | void (*error_function)(char *); 264 | }; 265 | 266 | 267 | #endif 268 | 269 | -------------------------------------------------------------------------------- /Algorithms/maxflow-v3.0/graph.cpp: -------------------------------------------------------------------------------- 1 | /* graph.cpp */ 2 | 3 | 4 | #include 5 | #include 6 | #include 7 | #include "graph.h" 8 | 9 | 10 | template 11 | Graph::Graph(int node_num_max, int edge_num_max, void (*err_function)(char *)) 12 | : node_num(0), 13 | nodeptr_block(NULL), 14 | error_function(err_function) 15 | { 16 | if (node_num_max < 16) node_num_max = 16; 17 | if (edge_num_max < 16) edge_num_max = 16; 18 | 19 | nodes = (node*) malloc(node_num_max*sizeof(node)); 20 | arcs = (arc*) malloc(2*edge_num_max*sizeof(arc)); 21 | if (!nodes || !arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 22 | 23 | node_last = nodes; 24 | node_max = nodes + node_num_max; 25 | arc_last = arcs; 26 | arc_max = arcs + 2*edge_num_max; 27 | 28 | maxflow_iteration = 0; 29 | flow = 0; 30 | } 31 | 32 | template 33 | Graph::~Graph() 34 | { 35 | if (nodeptr_block) 36 | { 37 | delete nodeptr_block; 38 | nodeptr_block = NULL; 39 | } 40 | free(nodes); 41 | free(arcs); 42 | } 43 | 44 | template 45 | void Graph::reset() 46 | { 47 | node_last = nodes; 48 | arc_last = arcs; 49 | node_num = 0; 50 | 51 | if (nodeptr_block) 52 | { 53 | delete nodeptr_block; 54 | nodeptr_block = NULL; 55 | } 56 | 57 | maxflow_iteration = 0; 58 | flow = 0; 59 | } 60 | 61 | template 62 | void Graph::reallocate_nodes(int num) 63 | { 64 | int node_num_max = (int)(node_max - nodes); 65 | node* nodes_old = nodes; 66 | 67 | node_num_max += node_num_max / 2; 68 | if (node_num_max < node_num + num) node_num_max = node_num + num; 69 | nodes = (node*) realloc(nodes_old, node_num_max*sizeof(node)); 70 | if (!nodes) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 71 | 72 | node_last = nodes + node_num; 73 | node_max = nodes + node_num_max; 74 | 75 | if (nodes != nodes_old) 76 | { 77 | arc* a; 78 | for (a=arcs; ahead = (node*) ((char*)a->head + (((char*) nodes) - ((char*) nodes_old))); 81 | } 82 | } 83 | } 84 | 85 | template 86 | void Graph::reallocate_arcs() 87 | { 88 | int arc_num_max = (int)(arc_max - arcs); 89 | int arc_num = (int)(arc_last - arcs); 90 | arc* arcs_old = arcs; 91 | 92 | arc_num_max += arc_num_max / 2; if (arc_num_max & 1) arc_num_max ++; 93 | arcs = (arc*) realloc(arcs_old, arc_num_max*sizeof(arc)); 94 | if (!arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); } 95 | 96 | arc_last = arcs + arc_num; 97 | arc_max = arcs + arc_num_max; 98 | 99 | if (arcs != arcs_old) 100 | { 101 | node* i; 102 | arc* a; 103 | for (i=nodes; ifirst) i->first = (arc*) ((char*)i->first + (((char*) arcs) - ((char*) arcs_old))); 106 | } 107 | for (a=arcs; anext) a->next = (arc*) ((char*)a->next + (((char*) arcs) - ((char*) arcs_old))); 110 | a->sister = (arc*) ((char*)a->sister + (((char*) arcs) - ((char*) arcs_old))); 111 | } 112 | } 113 | } 114 | 115 | #include "instances.inc" 116 | -------------------------------------------------------------------------------- /Algorithms/maxflow-v3.0/graph.h: -------------------------------------------------------------------------------- 1 | /* graph.h */ 2 | /* 3 | This software library implements the maxflow algorithm 4 | described in 5 | 6 | "An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision." 7 | Yuri Boykov and Vladimir Kolmogorov. 8 | In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 9 | September 2004 10 | 11 | This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov 12 | at Siemens Corporate Research. To make it available for public use, 13 | it was later reimplemented by Vladimir Kolmogorov based on open publications. 14 | 15 | If you use this software for research purposes, you should cite 16 | the aforementioned paper in any resulting publication. 17 | 18 | ---------------------------------------------------------------------- 19 | 20 | REUSING TREES: 21 | 22 | Starting with version 3.0, there is a also an option of reusing search 23 | trees from one maxflow computation to the next, as described in 24 | 25 | "Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts." 26 | Pushmeet Kohli and Philip H.S. Torr 27 | International Conference on Computer Vision (ICCV), 2005 28 | 29 | If you use this option, you should cite 30 | the aforementioned paper in any resulting publication. 31 | */ 32 | 33 | 34 | 35 | /* 36 | For description, license, example usage see README.TXT. 37 | */ 38 | 39 | #ifndef __GRAPH_H__ 40 | #define __GRAPH_H__ 41 | 42 | #include 43 | #include "block.h" 44 | 45 | #include 46 | // NOTE: in UNIX you need to use -DNDEBUG preprocessor option to supress assert's!!! 47 | 48 | 49 | 50 | // captype: type of edge capacities (excluding t-links) 51 | // tcaptype: type of t-links (edges between nodes and terminals) 52 | // flowtype: type of total flow 53 | // 54 | // Current instantiations are in instances.inc 55 | template class Graph 56 | { 57 | public: 58 | typedef enum 59 | { 60 | SOURCE = 0, 61 | SINK = 1 62 | } termtype; // terminals 63 | typedef int node_id; 64 | 65 | ///////////////////////////////////////////////////////////////////////// 66 | // BASIC INTERFACE FUNCTIONS // 67 | // (should be enough for most applications) // 68 | ///////////////////////////////////////////////////////////////////////// 69 | 70 | // Constructor. 71 | // The first argument gives an estimate of the maximum number of nodes that can be added 72 | // to the graph, and the second argument is an estimate of the maximum number of edges. 73 | // The last (optional) argument is the pointer to the function which will be called 74 | // if an error occurs; an error message is passed to this function. 75 | // If this argument is omitted, exit(1) will be called. 76 | // 77 | // IMPORTANT: It is possible to add more nodes to the graph than node_num_max 78 | // (and node_num_max can be zero). However, if the count is exceeded, then 79 | // the internal memory is reallocated (increased by 50%) which is expensive. 80 | // Also, temporarily the amount of allocated memory would be more than twice than needed. 81 | // Similarly for edges. 82 | // If you wish to avoid this overhead, you can download version 2.2, where nodes and edges are stored in blocks. 83 | Graph(int node_num_max, int edge_num_max, void (*err_function)(char *) = NULL); 84 | 85 | // Destructor 86 | ~Graph(); 87 | 88 | // Adds node(s) to the graph. By default, one node is added (num=1); then first call returns 0, second call returns 1, and so on. 89 | // If num>1, then several nodes are added, and node_id of the first one is returned. 90 | // IMPORTANT: see note about the constructor 91 | node_id add_node(int num = 1); 92 | 93 | // Adds a bidirectional edge between 'i' and 'j' with the weights 'cap' and 'rev_cap'. 94 | // IMPORTANT: see note about the constructor 95 | void add_edge(node_id i, node_id j, captype cap, captype rev_cap); 96 | 97 | // Adds new edges 'SOURCE->i' and 'i->SINK' with corresponding weights. 98 | // Can be called multiple times for each node. 99 | // Weights can be negative. 100 | // NOTE: the number of such edges is not counted in edge_num_max. 101 | // No internal memory is allocated by this call. 102 | void add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink); 103 | 104 | 105 | // Computes the maxflow. Can be called several times. 106 | // FOR DESCRIPTION OF reuse_trees, SEE mark_node(). 107 | // FOR DESCRIPTION OF changed_list, SEE remove_from_changed_list(). 108 | flowtype maxflow(bool reuse_trees = false, Block* changed_list = NULL); 109 | 110 | // After the maxflow is computed, this function returns to which 111 | // segment the node 'i' belongs (Graph::SOURCE or Graph::SINK). 112 | // 113 | // Occasionally there may be several minimum cuts. If a node can be assigned 114 | // to both the source and the sink, then default_segm is returned. 115 | termtype what_segment(node_id i, termtype default_segm = SOURCE); 116 | 117 | 118 | 119 | ////////////////////////////////////////////// 120 | // ADVANCED INTERFACE FUNCTIONS // 121 | // (provide access to the graph) // 122 | ////////////////////////////////////////////// 123 | 124 | private: 125 | struct node; 126 | struct arc; 127 | 128 | public: 129 | 130 | //////////////////////////// 131 | // 1. Reallocating graph. // 132 | //////////////////////////// 133 | 134 | // Removes all nodes and edges. 135 | // After that functions add_node() and add_edge() must be called again. 136 | // 137 | // Advantage compared to deleting Graph and allocating it again: 138 | // no calls to delete/new (which could be quite slow). 139 | // 140 | // If the graph structure stays the same, then an alternative 141 | // is to go through all nodes/edges and set new residual capacities 142 | // (see functions below). 143 | void reset(); 144 | 145 | //////////////////////////////////////////////////////////////////////////////// 146 | // 2. Functions for getting pointers to arcs and for reading graph structure. // 147 | // NOTE: adding new arcs may invalidate these pointers (if reallocation // 148 | // happens). So it's best not to add arcs while reading graph structure. // 149 | //////////////////////////////////////////////////////////////////////////////// 150 | 151 | // The following two functions return arcs in the same order that they 152 | // were added to the graph. NOTE: for each call add_edge(i,j,cap,cap_rev) 153 | // the first arc returned will be i->j, and the second j->i. 154 | // If there are no more arcs, then the function can still be called, but 155 | // the returned arc_id is undetermined. 156 | typedef arc* arc_id; 157 | arc_id get_first_arc(); 158 | arc_id get_next_arc(arc_id a); 159 | 160 | // other functions for reading graph structure 161 | int get_node_num() { return node_num; } 162 | int get_arc_num() { return (int)(arc_last - arcs); } 163 | void get_arc_ends(arc_id a, node_id& i, node_id& j); // returns i,j to that a = i->j 164 | 165 | /////////////////////////////////////////////////// 166 | // 3. Functions for reading residual capacities. // 167 | /////////////////////////////////////////////////// 168 | 169 | // returns residual capacity of SOURCE->i minus residual capacity of i->SINK 170 | tcaptype get_trcap(node_id i); 171 | // returns residual capacity of arc a 172 | captype get_rcap(arc* a); 173 | 174 | ///////////////////////////////////////////////////////////////// 175 | // 4. Functions for setting residual capacities. // 176 | // NOTE: If these functions are used, the value of the flow // 177 | // returned by maxflow() will not be valid! // 178 | ///////////////////////////////////////////////////////////////// 179 | 180 | void set_trcap(node_id i, tcaptype trcap); 181 | void set_rcap(arc* a, captype rcap); 182 | 183 | //////////////////////////////////////////////////////////////////// 184 | // 5. Functions related to reusing trees & list of changed nodes. // 185 | //////////////////////////////////////////////////////////////////// 186 | 187 | // If flag reuse_trees is true while calling maxflow(), then search trees 188 | // are reused from previous maxflow computation. 189 | // In this case before calling maxflow() the user must 190 | // specify which parts of the graph have changed by calling mark_node(): 191 | // add_tweights(i),set_trcap(i) => call mark_node(i) 192 | // add_edge(i,j),set_rcap(a) => call mark_node(i); mark_node(j) 193 | // 194 | // This option makes sense only if a small part of the graph is changed. 195 | // The initialization procedure goes only through marked nodes then. 196 | // 197 | // mark_node(i) can either be called before or after graph modification. 198 | // Can be called more than once per node, but calls after the first one 199 | // do not have any effect. 200 | // 201 | // NOTE: 202 | // - This option cannot be used in the first call to maxflow(). 203 | // - It is not necessary to call mark_node() if the change is ``not essential'', 204 | // i.e. sign(trcap) is preserved for a node and zero/nonzero status is preserved for an arc. 205 | // - To check that you marked all necessary nodes, you can call maxflow(false) after calling maxflow(true). 206 | // If everything is correct, the two calls must return the same value of flow. (Useful for debugging). 207 | void mark_node(node_id i); 208 | 209 | // If changed_list is not NULL while calling maxflow(), then the algorithm 210 | // keeps a list of nodes which could potentially have changed their segmentation label. 211 | // Nodes which are not in the list are guaranteed to keep their old segmentation label (SOURCE or SINK). 212 | // Example usage: 213 | // 214 | // typedef Graph G; 215 | // G* g = new Graph(nodeNum, edgeNum); 216 | // Block* changed_list = new Block(128); 217 | // 218 | // ... // add nodes and edges 219 | // 220 | // g->maxflow(); // first call should be without arguments 221 | // for (int iter=0; iter<10; iter++) 222 | // { 223 | // ... // change graph, call mark_node() accordingly 224 | // 225 | // g->maxflow(true, changed_list); 226 | // G::node_id* ptr; 227 | // for (ptr=changed_list->ScanFirst(); ptr; ptr=changed_list->ScanNext()) 228 | // { 229 | // G::node_id i = *ptr; assert(i>=0 && iremove_from_changed_list(i); 231 | // // do something with node i... 232 | // if (g->what_segment(i) == G::SOURCE) { ... } 233 | // } 234 | // changed_list->Reset(); 235 | // } 236 | // delete changed_list; 237 | // 238 | // NOTE: 239 | // - If changed_list option is used, then reuse_trees must be used as well. 240 | // - In the example above, the user may omit calls g->remove_from_changed_list(i) and changed_list->Reset() in a given iteration. 241 | // Then during the next call to maxflow(true, &changed_list) new nodes will be added to changed_list. 242 | // - If the next call to maxflow() does not use option reuse_trees, then calling remove_from_changed_list() 243 | // is not necessary. ("changed_list->Reset()" or "delete changed_list" should still be called, though). 244 | void remove_from_changed_list(node_id i) 245 | { 246 | assert(i>=0 && i 0 then tr_cap is residual capacity of the arc SOURCE->node 276 | // otherwise -tr_cap is residual capacity of the arc node->SINK 277 | 278 | }; 279 | 280 | struct arc 281 | { 282 | node *head; // node the arc points to 283 | arc *next; // next arc with the same originating node 284 | arc *sister; // reverse arc 285 | 286 | captype r_cap; // residual capacity 287 | }; 288 | 289 | struct nodeptr 290 | { 291 | node *ptr; 292 | nodeptr *next; 293 | }; 294 | static const int NODEPTR_BLOCK_SIZE = 128; 295 | 296 | node *nodes, *node_last, *node_max; // node_last = nodes+node_num, node_max = nodes+node_num_max; 297 | arc *arcs, *arc_last, *arc_max; // arc_last = arcs+2*edge_num, arc_max = arcs+2*edge_num_max; 298 | 299 | int node_num; 300 | 301 | DBlock *nodeptr_block; 302 | 303 | void (*error_function)(char *); // this function is called if a error occurs, 304 | // with a corresponding error message 305 | // (or exit(1) is called if it's NULL) 306 | 307 | flowtype flow; // total flow 308 | 309 | // reusing trees & list of changed pixels 310 | int maxflow_iteration; // counter 311 | Block *changed_list; 312 | 313 | ///////////////////////////////////////////////////////////////////////// 314 | 315 | node *queue_first[2], *queue_last[2]; // list of active nodes 316 | nodeptr *orphan_first, *orphan_last; // list of pointers to orphans 317 | int TIME; // monotonically increasing global counter 318 | 319 | ///////////////////////////////////////////////////////////////////////// 320 | 321 | void reallocate_nodes(int num); // num is the number of new nodes 322 | void reallocate_arcs(); 323 | 324 | // functions for processing active list 325 | void set_active(node *i); 326 | node *next_active(); 327 | 328 | // functions for processing orphans list 329 | void set_orphan_front(node* i); // add to the beginning of the list 330 | void set_orphan_rear(node* i); // add to the end of the list 331 | 332 | void add_to_changed_list(node* i); 333 | 334 | void maxflow_init(); // called if reuse_trees == false 335 | void maxflow_reuse_trees_init(); // called if reuse_trees == true 336 | void augment(arc *middle_arc); 337 | void process_source_orphan(node *i); 338 | void process_sink_orphan(node *i); 339 | 340 | void test_consistency(node* current_node=NULL); // debug function 341 | }; 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | /////////////////////////////////////// 354 | // Implementation - inline functions // 355 | /////////////////////////////////////// 356 | 357 | 358 | 359 | template 360 | inline typename Graph::node_id Graph::add_node(int num) 361 | { 362 | assert(num > 0); 363 | 364 | if (node_last + num > node_max) reallocate_nodes(num); 365 | 366 | if (num == 1) 367 | { 368 | node_last -> first = NULL; 369 | node_last -> tr_cap = 0; 370 | node_last -> is_marked = 0; 371 | node_last -> is_in_changed_list = 0; 372 | 373 | node_last ++; 374 | return node_num ++; 375 | } 376 | else 377 | { 378 | memset(node_last, 0, num*sizeof(node)); 379 | 380 | node_id i = node_num; 381 | node_num += num; 382 | node_last += num; 383 | return i; 384 | } 385 | } 386 | 387 | template 388 | inline void Graph::add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink) 389 | { 390 | assert(i >= 0 && i < node_num); 391 | 392 | tcaptype delta = nodes[i].tr_cap; 393 | if (delta > 0) cap_source += delta; 394 | else cap_sink -= delta; 395 | flow += (cap_source < cap_sink) ? cap_source : cap_sink; 396 | nodes[i].tr_cap = cap_source - cap_sink; 397 | } 398 | 399 | template 400 | inline void Graph::add_edge(node_id _i, node_id _j, captype cap, captype rev_cap) 401 | { 402 | assert(_i >= 0 && _i < node_num); 403 | assert(_j >= 0 && _j < node_num); 404 | assert(_i != _j); 405 | assert(cap >= 0); 406 | assert(rev_cap >= 0); 407 | 408 | if (arc_last == arc_max) reallocate_arcs(); 409 | 410 | arc *a = arc_last ++; 411 | arc *a_rev = arc_last ++; 412 | 413 | node* i = nodes + _i; 414 | node* j = nodes + _j; 415 | 416 | a -> sister = a_rev; 417 | a_rev -> sister = a; 418 | a -> next = i -> first; 419 | i -> first = a; 420 | a_rev -> next = j -> first; 421 | j -> first = a_rev; 422 | a -> head = j; 423 | a_rev -> head = i; 424 | a -> r_cap = cap; 425 | a_rev -> r_cap = rev_cap; 426 | } 427 | 428 | template 429 | inline typename Graph::arc* Graph::get_first_arc() 430 | { 431 | return arcs; 432 | } 433 | 434 | template 435 | inline typename Graph::arc* Graph::get_next_arc(arc* a) 436 | { 437 | return a + 1; 438 | } 439 | 440 | template 441 | inline void Graph::get_arc_ends(arc* a, node_id& i, node_id& j) 442 | { 443 | assert(a >= arcs && a < arc_last); 444 | i = (node_id) (a->sister->head - nodes); 445 | j = (node_id) (a->head - nodes); 446 | } 447 | 448 | template 449 | inline tcaptype Graph::get_trcap(node_id i) 450 | { 451 | assert(i>=0 && i 456 | inline captype Graph::get_rcap(arc* a) 457 | { 458 | assert(a >= arcs && a < arc_last); 459 | return a->r_cap; 460 | } 461 | 462 | template 463 | inline void Graph::set_trcap(node_id i, tcaptype trcap) 464 | { 465 | assert(i>=0 && i 470 | inline void Graph::set_rcap(arc* a, captype rcap) 471 | { 472 | assert(a >= arcs && a < arc_last); 473 | a->r_cap = rcap; 474 | } 475 | 476 | 477 | template 478 | inline typename Graph::termtype Graph::what_segment(node_id i, termtype default_segm) 479 | { 480 | if (nodes[i].parent) 481 | { 482 | return (nodes[i].is_sink) ? SINK : SOURCE; 483 | } 484 | else 485 | { 486 | return default_segm; 487 | } 488 | } 489 | 490 | template 491 | inline void Graph::mark_node(node_id _i) 492 | { 493 | node* i = nodes + _i; 494 | if (!i->next) 495 | { 496 | /* it's not in the list yet */ 497 | if (queue_last[1]) queue_last[1] -> next = i; 498 | else queue_first[1] = i; 499 | queue_last[1] = i; 500 | i -> next = i; 501 | } 502 | i->is_marked = 1; 503 | } 504 | 505 | 506 | #endif 507 | -------------------------------------------------------------------------------- /Algorithms/maxflow-v3.0/instances.inc: -------------------------------------------------------------------------------- 1 | #include "graph.h" 2 | 3 | #ifdef _MSC_VER 4 | #pragma warning(disable: 4661) 5 | #endif 6 | 7 | // Instantiations: 8 | // IMPORTANT: 9 | // flowtype should be 'larger' than tcaptype 10 | // tcaptype should be 'larger' than captype 11 | 12 | template class Graph; 13 | template class Graph; 14 | template class Graph; 15 | template class Graph; 16 | 17 | -------------------------------------------------------------------------------- /Algorithms/maxflow-v3.0/maxflow.cpp: -------------------------------------------------------------------------------- 1 | /* maxflow.cpp */ 2 | 3 | 4 | #include 5 | #include "graph.h" 6 | 7 | 8 | /* 9 | special constants for node->parent 10 | */ 11 | #define TERMINAL ( (arc *) 1 ) /* to terminal */ 12 | #define ORPHAN ( (arc *) 2 ) /* orphan */ 13 | 14 | 15 | #define INFINITE_D ((int)(((unsigned)-1)/2)) /* infinite distance to the terminal */ 16 | 17 | /***********************************************************************/ 18 | 19 | /* 20 | Functions for processing active list. 21 | i->next points to the next node in the list 22 | (or to i, if i is the last node in the list). 23 | If i->next is NULL iff i is not in the list. 24 | 25 | There are two queues. Active nodes are added 26 | to the end of the second queue and read from 27 | the front of the first queue. If the first queue 28 | is empty, it is replaced by the second queue 29 | (and the second queue becomes empty). 30 | */ 31 | 32 | 33 | template 34 | inline void Graph::set_active(node *i) 35 | { 36 | if (!i->next) 37 | { 38 | /* it's not in the list yet */ 39 | if (queue_last[1]) queue_last[1] -> next = i; 40 | else queue_first[1] = i; 41 | queue_last[1] = i; 42 | i -> next = i; 43 | } 44 | } 45 | 46 | /* 47 | Returns the next active node. 48 | If it is connected to the sink, it stays in the list, 49 | otherwise it is removed from the list 50 | */ 51 | template 52 | inline typename Graph::node* Graph::next_active() 53 | { 54 | node *i; 55 | 56 | while ( 1 ) 57 | { 58 | if (!(i=queue_first[0])) 59 | { 60 | queue_first[0] = i = queue_first[1]; 61 | queue_last[0] = queue_last[1]; 62 | queue_first[1] = NULL; 63 | queue_last[1] = NULL; 64 | if (!i) return NULL; 65 | } 66 | 67 | /* remove it from the active list */ 68 | if (i->next == i) queue_first[0] = queue_last[0] = NULL; 69 | else queue_first[0] = i -> next; 70 | i -> next = NULL; 71 | 72 | /* a node in the list is active iff it has a parent */ 73 | if (i->parent) return i; 74 | } 75 | } 76 | 77 | /***********************************************************************/ 78 | 79 | template 80 | inline void Graph::set_orphan_front(node *i) 81 | { 82 | nodeptr *np; 83 | i -> parent = ORPHAN; 84 | np = nodeptr_block -> New(); 85 | np -> ptr = i; 86 | np -> next = orphan_first; 87 | orphan_first = np; 88 | } 89 | 90 | template 91 | inline void Graph::set_orphan_rear(node *i) 92 | { 93 | nodeptr *np; 94 | i -> parent = ORPHAN; 95 | np = nodeptr_block -> New(); 96 | np -> ptr = i; 97 | if (orphan_last) orphan_last -> next = np; 98 | else orphan_first = np; 99 | orphan_last = np; 100 | np -> next = NULL; 101 | } 102 | 103 | /***********************************************************************/ 104 | 105 | template 106 | inline void Graph::add_to_changed_list(node *i) 107 | { 108 | if (changed_list && !i->is_in_changed_list) 109 | { 110 | node_id* ptr = changed_list->New(); 111 | *ptr = (node_id)(i - nodes); 112 | i->is_in_changed_list = true; 113 | } 114 | } 115 | 116 | /***********************************************************************/ 117 | 118 | template 119 | void Graph::maxflow_init() 120 | { 121 | node *i; 122 | 123 | queue_first[0] = queue_last[0] = NULL; 124 | queue_first[1] = queue_last[1] = NULL; 125 | orphan_first = NULL; 126 | 127 | TIME = 0; 128 | 129 | for (i=nodes; i next = NULL; 132 | i -> is_marked = 0; 133 | i -> is_in_changed_list = 0; 134 | i -> TS = TIME; 135 | if (i->tr_cap > 0) 136 | { 137 | /* i is connected to the source */ 138 | i -> is_sink = 0; 139 | i -> parent = TERMINAL; 140 | set_active(i); 141 | i -> DIST = 1; 142 | } 143 | else if (i->tr_cap < 0) 144 | { 145 | /* i is connected to the sink */ 146 | i -> is_sink = 1; 147 | i -> parent = TERMINAL; 148 | set_active(i); 149 | i -> DIST = 1; 150 | } 151 | else 152 | { 153 | i -> parent = NULL; 154 | } 155 | } 156 | } 157 | 158 | template 159 | void Graph::maxflow_reuse_trees_init() 160 | { 161 | node* i; 162 | node* j; 163 | node* queue = queue_first[1]; 164 | arc* a; 165 | nodeptr* np; 166 | 167 | queue_first[0] = queue_last[0] = NULL; 168 | queue_first[1] = queue_last[1] = NULL; 169 | orphan_first = orphan_last = NULL; 170 | 171 | TIME ++; 172 | 173 | while ((i=queue)) 174 | { 175 | queue = i->next; 176 | if (queue == i) queue = NULL; 177 | i->next = NULL; 178 | i->is_marked = 0; 179 | set_active(i); 180 | 181 | if (i->tr_cap == 0) 182 | { 183 | if (i->parent) set_orphan_rear(i); 184 | continue; 185 | } 186 | 187 | if (i->tr_cap > 0) 188 | { 189 | if (!i->parent || i->is_sink) 190 | { 191 | i->is_sink = 0; 192 | for (a=i->first; a; a=a->next) 193 | { 194 | j = a->head; 195 | if (!j->is_marked) 196 | { 197 | if (j->parent == a->sister) set_orphan_rear(j); 198 | if (j->parent && j->is_sink && a->r_cap > 0) set_active(j); 199 | } 200 | } 201 | add_to_changed_list(i); 202 | } 203 | } 204 | else 205 | { 206 | if (!i->parent || !i->is_sink) 207 | { 208 | i->is_sink = 1; 209 | for (a=i->first; a; a=a->next) 210 | { 211 | j = a->head; 212 | if (!j->is_marked) 213 | { 214 | if (j->parent == a->sister) set_orphan_rear(j); 215 | if (j->parent && !j->is_sink && a->sister->r_cap > 0) set_active(j); 216 | } 217 | } 218 | add_to_changed_list(i); 219 | } 220 | } 221 | i->parent = TERMINAL; 222 | i -> TS = TIME; 223 | i -> DIST = 1; 224 | } 225 | 226 | //test_consistency(); 227 | 228 | /* adoption */ 229 | while ((np=orphan_first)) 230 | { 231 | orphan_first = np -> next; 232 | i = np -> ptr; 233 | nodeptr_block -> Delete(np); 234 | if (!orphan_first) orphan_last = NULL; 235 | if (i->is_sink) process_sink_orphan(i); 236 | else process_source_orphan(i); 237 | } 238 | /* adoption end */ 239 | 240 | //test_consistency(); 241 | } 242 | 243 | template 244 | void Graph::augment(arc *middle_arc) 245 | { 246 | node *i; 247 | arc *a; 248 | tcaptype bottleneck; 249 | 250 | 251 | /* 1. Finding bottleneck capacity */ 252 | /* 1a - the source tree */ 253 | bottleneck = middle_arc -> r_cap; 254 | for (i=middle_arc->sister->head; ; i=a->head) 255 | { 256 | a = i -> parent; 257 | if (a == TERMINAL) break; 258 | if (bottleneck > a->sister->r_cap) bottleneck = a -> sister -> r_cap; 259 | } 260 | if (bottleneck > i->tr_cap) bottleneck = i -> tr_cap; 261 | /* 1b - the sink tree */ 262 | for (i=middle_arc->head; ; i=a->head) 263 | { 264 | a = i -> parent; 265 | if (a == TERMINAL) break; 266 | if (bottleneck > a->r_cap) bottleneck = a -> r_cap; 267 | } 268 | if (bottleneck > - i->tr_cap) bottleneck = - i -> tr_cap; 269 | 270 | 271 | /* 2. Augmenting */ 272 | /* 2a - the source tree */ 273 | middle_arc -> sister -> r_cap += bottleneck; 274 | middle_arc -> r_cap -= bottleneck; 275 | for (i=middle_arc->sister->head; ; i=a->head) 276 | { 277 | a = i -> parent; 278 | if (a == TERMINAL) break; 279 | a -> r_cap += bottleneck; 280 | a -> sister -> r_cap -= bottleneck; 281 | if (!a->sister->r_cap) 282 | { 283 | set_orphan_front(i); // add i to the beginning of the adoption list 284 | } 285 | } 286 | i -> tr_cap -= bottleneck; 287 | if (!i->tr_cap) 288 | { 289 | set_orphan_front(i); // add i to the beginning of the adoption list 290 | } 291 | /* 2b - the sink tree */ 292 | for (i=middle_arc->head; ; i=a->head) 293 | { 294 | a = i -> parent; 295 | if (a == TERMINAL) break; 296 | a -> sister -> r_cap += bottleneck; 297 | a -> r_cap -= bottleneck; 298 | if (!a->r_cap) 299 | { 300 | set_orphan_front(i); // add i to the beginning of the adoption list 301 | } 302 | } 303 | i -> tr_cap += bottleneck; 304 | if (!i->tr_cap) 305 | { 306 | set_orphan_front(i); // add i to the beginning of the adoption list 307 | } 308 | 309 | 310 | flow += bottleneck; 311 | } 312 | 313 | /***********************************************************************/ 314 | 315 | template 316 | void Graph::process_source_orphan(node *i) 317 | { 318 | node *j; 319 | arc *a0, *a0_min = NULL, *a; 320 | int d, d_min = INFINITE_D; 321 | 322 | /* trying to find a new parent */ 323 | for (a0=i->first; a0; a0=a0->next) 324 | if (a0->sister->r_cap) 325 | { 326 | j = a0 -> head; 327 | if (!j->is_sink && (a=j->parent)) 328 | { 329 | /* checking the origin of j */ 330 | d = 0; 331 | while ( 1 ) 332 | { 333 | if (j->TS == TIME) 334 | { 335 | d += j -> DIST; 336 | break; 337 | } 338 | a = j -> parent; 339 | d ++; 340 | if (a==TERMINAL) 341 | { 342 | j -> TS = TIME; 343 | j -> DIST = 1; 344 | break; 345 | } 346 | if (a==ORPHAN) { d = INFINITE_D; break; } 347 | j = a -> head; 348 | } 349 | if (dhead; j->TS!=TIME; j=j->parent->head) 358 | { 359 | j -> TS = TIME; 360 | j -> DIST = d --; 361 | } 362 | } 363 | } 364 | } 365 | 366 | if (i->parent = a0_min) 367 | { 368 | i -> TS = TIME; 369 | i -> DIST = d_min + 1; 370 | } 371 | else 372 | { 373 | /* no parent is found */ 374 | add_to_changed_list(i); 375 | 376 | /* process neighbors */ 377 | for (a0=i->first; a0; a0=a0->next) 378 | { 379 | j = a0 -> head; 380 | if (!j->is_sink && (a=j->parent)) 381 | { 382 | if (a0->sister->r_cap) set_active(j); 383 | if (a!=TERMINAL && a!=ORPHAN && a->head==i) 384 | { 385 | set_orphan_rear(j); // add j to the end of the adoption list 386 | } 387 | } 388 | } 389 | } 390 | } 391 | 392 | template 393 | void Graph::process_sink_orphan(node *i) 394 | { 395 | node *j; 396 | arc *a0, *a0_min = NULL, *a; 397 | int d, d_min = INFINITE_D; 398 | 399 | /* trying to find a new parent */ 400 | for (a0=i->first; a0; a0=a0->next) 401 | if (a0->r_cap) 402 | { 403 | j = a0 -> head; 404 | if (j->is_sink && (a=j->parent)) 405 | { 406 | /* checking the origin of j */ 407 | d = 0; 408 | while ( 1 ) 409 | { 410 | if (j->TS == TIME) 411 | { 412 | d += j -> DIST; 413 | break; 414 | } 415 | a = j -> parent; 416 | d ++; 417 | if (a==TERMINAL) 418 | { 419 | j -> TS = TIME; 420 | j -> DIST = 1; 421 | break; 422 | } 423 | if (a==ORPHAN) { d = INFINITE_D; break; } 424 | j = a -> head; 425 | } 426 | if (dhead; j->TS!=TIME; j=j->parent->head) 435 | { 436 | j -> TS = TIME; 437 | j -> DIST = d --; 438 | } 439 | } 440 | } 441 | } 442 | 443 | if (i->parent = a0_min) 444 | { 445 | i -> TS = TIME; 446 | i -> DIST = d_min + 1; 447 | } 448 | else 449 | { 450 | /* no parent is found */ 451 | add_to_changed_list(i); 452 | 453 | /* process neighbors */ 454 | for (a0=i->first; a0; a0=a0->next) 455 | { 456 | j = a0 -> head; 457 | if (j->is_sink && (a=j->parent)) 458 | { 459 | if (a0->r_cap) set_active(j); 460 | if (a!=TERMINAL && a!=ORPHAN && a->head==i) 461 | { 462 | set_orphan_rear(j); // add j to the end of the adoption list 463 | } 464 | } 465 | } 466 | } 467 | } 468 | 469 | /***********************************************************************/ 470 | 471 | template 472 | flowtype Graph::maxflow(bool reuse_trees, Block* _changed_list) 473 | { 474 | node *i, *j, *current_node = NULL; 475 | arc *a; 476 | nodeptr *np, *np_next; 477 | 478 | if (!nodeptr_block) 479 | { 480 | nodeptr_block = new DBlock(NODEPTR_BLOCK_SIZE, error_function); 481 | } 482 | 483 | changed_list = _changed_list; 484 | if (maxflow_iteration == 0 && reuse_trees) { if (error_function) (*error_function)("reuse_trees cannot be used in the first call to maxflow()!"); exit(1); } 485 | if (changed_list && !reuse_trees) { if (error_function) (*error_function)("changed_list cannot be used without reuse_trees!"); exit(1); } 486 | 487 | if (reuse_trees) maxflow_reuse_trees_init(); 488 | else maxflow_init(); 489 | 490 | // main loop 491 | while ( 1 ) 492 | { 493 | // test_consistency(current_node); 494 | 495 | if ((i=current_node)) 496 | { 497 | i -> next = NULL; /* remove active flag */ 498 | if (!i->parent) i = NULL; 499 | } 500 | if (!i) 501 | { 502 | if (!(i = next_active())) break; 503 | } 504 | 505 | /* growth */ 506 | if (!i->is_sink) 507 | { 508 | /* grow source tree */ 509 | for (a=i->first; a; a=a->next) 510 | if (a->r_cap) 511 | { 512 | j = a -> head; 513 | if (!j->parent) 514 | { 515 | j -> is_sink = 0; 516 | j -> parent = a -> sister; 517 | j -> TS = i -> TS; 518 | j -> DIST = i -> DIST + 1; 519 | set_active(j); 520 | add_to_changed_list(j); 521 | } 522 | else if (j->is_sink) break; 523 | else if (j->TS <= i->TS && 524 | j->DIST > i->DIST) 525 | { 526 | /* heuristic - trying to make the distance from j to the source shorter */ 527 | j -> parent = a -> sister; 528 | j -> TS = i -> TS; 529 | j -> DIST = i -> DIST + 1; 530 | } 531 | } 532 | } 533 | else 534 | { 535 | /* grow sink tree */ 536 | for (a=i->first; a; a=a->next) 537 | if (a->sister->r_cap) 538 | { 539 | j = a -> head; 540 | if (!j->parent) 541 | { 542 | j -> is_sink = 1; 543 | j -> parent = a -> sister; 544 | j -> TS = i -> TS; 545 | j -> DIST = i -> DIST + 1; 546 | set_active(j); 547 | add_to_changed_list(j); 548 | } 549 | else if (!j->is_sink) { a = a -> sister; break; } 550 | else if (j->TS <= i->TS && 551 | j->DIST > i->DIST) 552 | { 553 | /* heuristic - trying to make the distance from j to the sink shorter */ 554 | j -> parent = a -> sister; 555 | j -> TS = i -> TS; 556 | j -> DIST = i -> DIST + 1; 557 | } 558 | } 559 | } 560 | 561 | TIME ++; 562 | 563 | if (a) 564 | { 565 | i -> next = i; /* set active flag */ 566 | current_node = i; 567 | 568 | /* augmentation */ 569 | augment(a); 570 | /* augmentation end */ 571 | 572 | /* adoption */ 573 | while ((np=orphan_first)) 574 | { 575 | np_next = np -> next; 576 | np -> next = NULL; 577 | 578 | while ((np=orphan_first)) 579 | { 580 | orphan_first = np -> next; 581 | i = np -> ptr; 582 | nodeptr_block -> Delete(np); 583 | if (!orphan_first) orphan_last = NULL; 584 | if (i->is_sink) process_sink_orphan(i); 585 | else process_source_orphan(i); 586 | } 587 | 588 | orphan_first = np_next; 589 | } 590 | /* adoption end */ 591 | } 592 | else current_node = NULL; 593 | } 594 | // test_consistency(); 595 | 596 | if (!reuse_trees || (maxflow_iteration % 64) == 0) 597 | { 598 | delete nodeptr_block; 599 | nodeptr_block = NULL; 600 | } 601 | 602 | maxflow_iteration ++; 603 | return flow; 604 | } 605 | 606 | /***********************************************************************/ 607 | 608 | 609 | template 610 | void Graph::test_consistency(node* current_node) 611 | { 612 | node *i; 613 | arc *a; 614 | int r; 615 | int num1 = 0, num2 = 0; 616 | 617 | // test whether all nodes i with i->next!=NULL are indeed in the queue 618 | for (i=nodes; inext || i==current_node) num1 ++; 621 | } 622 | for (r=0; r<3; r++) 623 | { 624 | i = (r == 2) ? current_node : queue_first[r]; 625 | if (i) 626 | for ( ; ; i=i->next) 627 | { 628 | num2 ++; 629 | if (i->next == i) 630 | { 631 | if (r<2) assert(i == queue_last[r]); 632 | else assert(i == current_node); 633 | break; 634 | } 635 | } 636 | } 637 | assert(num1 == num2); 638 | 639 | for (i=nodes; iparent == NULL) {} 643 | else if (i->parent == ORPHAN) {} 644 | else if (i->parent == TERMINAL) 645 | { 646 | if (!i->is_sink) assert(i->tr_cap > 0); 647 | else assert(i->tr_cap < 0); 648 | } 649 | else 650 | { 651 | if (!i->is_sink) assert (i->parent->sister->r_cap > 0); 652 | else assert (i->parent->r_cap > 0); 653 | } 654 | // test whether passive nodes in search trees have neighbors in 655 | // a different tree through non-saturated edges 656 | if (i->parent && !i->next) 657 | { 658 | if (!i->is_sink) 659 | { 660 | assert(i->tr_cap >= 0); 661 | for (a=i->first; a; a=a->next) 662 | { 663 | if (a->r_cap > 0) assert(a->head->parent && !a->head->is_sink); 664 | } 665 | } 666 | else 667 | { 668 | assert(i->tr_cap <= 0); 669 | for (a=i->first; a; a=a->next) 670 | { 671 | if (a->sister->r_cap > 0) assert(a->head->parent && a->head->is_sink); 672 | } 673 | } 674 | } 675 | // test marking invariants 676 | if (i->parent && i->parent!=ORPHAN && i->parent!=TERMINAL) 677 | { 678 | assert(i->TS <= i->parent->head->TS); 679 | if (i->TS == i->parent->head->TS) assert(i->DIST > i->parent->head->DIST); 680 | } 681 | } 682 | } 683 | 684 | #include "instances.inc" 685 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GrabCut-GraphCut 2 | Matlab implementation of GrabCut and GraphCut for interactive image segmentation. 3 | 4 | GrabCut needs the user to provide a bounding box to segment an object. After getting an initial sgmentation, the user can provide scribbles for refinement. 5 | 6 | GraphCut needs the user to provide a set of scribbles for the foreground and background to segment an object. Refinement is also allowed by giving more scribbles. 7 | 8 | This repository uses the maxflow algorithm provided by http://vision.csd.uwo.ca/code/ 9 | 10 | This implementation was developed for comparison with DeepIGeoS. If you use this repository, please cite the following paper: 11 | 12 | Wang, Guotai, et al. "DeepIGeos: A deep interactive geodesic framework for medical image segmentation." IEEE Transactions on Pattern Analysis and Machine Intelligence, vol 41(7), pp 1559 - 1572, 2019. https://ieeexplore.ieee.org/document/8370732 13 | 14 | # How to use: 15 | 16 | 1, download the code. 17 | 18 | 2, go to the folder "Algorithms", run make.m to compile the maxflow algoithm. 19 | 20 | 3, run user_interface.m and load an image, start to segment! 21 | 22 | ![graphcut](./images/graph_cut_snapshot.png) 23 | 24 | A snapshot for GraphCut. 25 | 26 | ![grabcut](./images/grab_cut_snapshot.png) 27 | 28 | A snapshot for GrabCut. 29 | 30 | # Reference 31 | 32 | [1] Boykov, Yuri Y., and M-P. Jolly. "Interactive graph cuts for optimal boundary & region segmentation of objects in ND images." Computer Vision, 2001. ICCV 2001. Proceedings. Eighth IEEE International Conference on. Vol. 1. IEEE, 2001. 33 | 34 | [2] Rother, Carsten, Vladimir Kolmogorov, and Andrew Blake. "Grabcut: Interactive foreground extraction using iterated graph cuts." ACM transactions on graphics (TOG). Vol. 23. No. 3. ACM, 2004. 35 | -------------------------------------------------------------------------------- /images/black_car.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/black_car.png -------------------------------------------------------------------------------- /images/blue_car.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/blue_car.png -------------------------------------------------------------------------------- /images/carsten.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/carsten.jpg -------------------------------------------------------------------------------- /images/fish.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/fish.png -------------------------------------------------------------------------------- /images/flowers.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/flowers.png -------------------------------------------------------------------------------- /images/flowers_gray.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/flowers_gray.png -------------------------------------------------------------------------------- /images/food.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/food.bmp -------------------------------------------------------------------------------- /images/grab_cut_snapshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/grab_cut_snapshot.png -------------------------------------------------------------------------------- /images/graph_cut_snapshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/graph_cut_snapshot.png -------------------------------------------------------------------------------- /images/horse.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/horse.jpg -------------------------------------------------------------------------------- /images/llama.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/llama.bmp -------------------------------------------------------------------------------- /images/ls.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/ls.bmp -------------------------------------------------------------------------------- /images/man.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/images/man.png -------------------------------------------------------------------------------- /mouse_down.m: -------------------------------------------------------------------------------- 1 | function mouse_down(imagefig,varargins) 2 | global glb_handles; 3 | global bounding_box_state; 4 | global mouse_state; 5 | global bb_p1; 6 | global bb_p2; 7 | global last_point; 8 | xlim = get(gca, 'XLim'); 9 | ylim = get(gca, 'YLIm'); 10 | temp = get(gca,'currentpoint'); 11 | if(temp(1,1)xlim(2) || temp(1,2)ylim(2)) 12 | return; 13 | end 14 | interaction_bb = get(glb_handles.radiobutton_bb, 'value'); 15 | if(interaction_bb) 16 | if(bounding_box_state==0 || bounding_box_state==2) 17 | bb_p1 = [temp(1,1), temp(1,2)]; 18 | bounding_box_state=1; 19 | else 20 | bb_p2 = [temp(1,1), temp(1,2)]; 21 | bounding_box_state=2; 22 | set(glb_handles.radiobutton_scrb, 'value',1); 23 | end 24 | end 25 | mouse_state=1; 26 | last_point = [temp(1,1), temp(1,2)]; -------------------------------------------------------------------------------- /mouse_move.m: -------------------------------------------------------------------------------- 1 | function mouse_move(imagefig,varargins) 2 | global mouse_state; 3 | global glb_handles; 4 | global last_point; 5 | global Seeds; 6 | xlim = get(gca, 'XLim'); 7 | ylim = get(gca, 'YLIm'); 8 | temp = get(gca,'currentpoint'); 9 | temp = [temp(1,1), temp(1,2)]; 10 | if(temp(1)xlim(2) || temp(2)ylim(2)) 11 | return 12 | end 13 | interaction_scrb = get(glb_handles.radiobutton_scrb, 'value'); 14 | if(interaction_scrb && mouse_state) 15 | % should draw scribbles on roi 16 | mouse_botton = get(gcbf, 'SelectionType'); 17 | if(strcmp(mouse_botton,'normal')) % left mouse bottom 18 | hold on; 19 | p=plot([last_point(1), temp(1)],[last_point(2), temp(2)], 'r','MarkerSize',10); 20 | p(1).LineWidth = 2; 21 | Seeds = draw_line_on_img(Seeds, last_point, temp, 127); 22 | elseif(strcmp(mouse_botton,'alt')) % right mouse bottom 23 | hold on; 24 | p=plot([last_point(1), temp(1)],[last_point(2), temp(2)], 'b','MarkerSize',10); 25 | p(1).LineWidth = 2; 26 | Seeds = draw_line_on_img(Seeds, last_point, temp, 255); 27 | end 28 | last_point = temp; 29 | end 30 | ui_update(); 31 | 32 | function Ilab = draw_line_on_img(I, p1, p2, lab) 33 | [H, W]=size(I); 34 | Ilab = I; 35 | Hdiff = abs(p2(2)-p1(2)); 36 | Wdiff = abs(p2(1)-p1(1)); 37 | if(Hdiff>Wdiff) 38 | step = 1.0/(Hdiff+1); 39 | else 40 | step = 1.0/(Wdiff+1); 41 | end 42 | for i = step:step:1 43 | p = p1*(1.0-i)+p2*i; 44 | Ilab(int16(p(2)),int16(p(1)))=lab; 45 | if(min(H,W)>40) 46 | Ilab(int16(p(2)+1),int16(p(1)))=lab; 47 | Ilab(int16(p(2)-1),int16(p(1)))=lab; 48 | Ilab(int16(p(2)),int16(p(1))+1)=lab; 49 | Ilab(int16(p(2)),int16(p(1))-1)=lab; 50 | end 51 | end 52 | 53 | 54 | -------------------------------------------------------------------------------- /mouse_up.m: -------------------------------------------------------------------------------- 1 | function mouse_up(imagefig,varargins) 2 | global mouse_state; 3 | mouse_state=0; -------------------------------------------------------------------------------- /ui_update.m: -------------------------------------------------------------------------------- 1 | function ui_update() 2 | global glb_handles; 3 | global Image; 4 | global Seeds; 5 | global Seg; 6 | global bounding_box_state; 7 | global bb_p1 bb_p2; 8 | global bb_x0 bb_x1 bb_y0 bb_y1; 9 | if(length(size(Image))==2) % gray image 10 | im_show = repmat(Image, [1,1,3]); 11 | else 12 | im_show = Image; 13 | end 14 | xlim = get(gca, 'XLim'); 15 | ylim = get(gca, 'YLIm'); 16 | currentpoint = get(gca,'currentpoint'); 17 | temp = [currentpoint(1,1), currentpoint(1,2)]; 18 | 19 | if(bounding_box_state == 1 || bounding_box_state == 2) % roi has been defined 20 | if(bounding_box_state==1) 21 | temp = [max(temp(1), xlim(1)), max(temp(2), ylim(1))]; 22 | temp = [min(temp(1), xlim(2)), min(temp(2), ylim(2))]; 23 | [bb_x0, bb_x1, bb_y0, bb_y1]=get_bounding_box(bb_p1, temp); 24 | end 25 | 26 | % if(~get(glb_handles.checkbox1, 'Value')) 27 | % im_show = addSeeds(im_show, Seeds); 28 | % end 29 | end 30 | 31 | im_show = addSeeds(im_show, Seeds); 32 | im_show = addCountor(im_show, Seg, 'g'); 33 | cla(glb_handles.axes1,'reset'); 34 | imshow(im_show); 35 | 36 | interaction_bb = get(glb_handles.radiobutton_bb, 'value'); 37 | if(interaction_bb) 38 | if(bounding_box_state == 0 || bounding_box_state == 2) 39 | draw_cross(xlim, ylim, temp); 40 | end 41 | end 42 | if(bounding_box_state == 1 || bounding_box_state == 2) 43 | % draw roi 44 | 45 | if(bounding_box_state == 1) 46 | draw_bounding_box(bb_x0, bb_x1, bb_y0, bb_y1, 'y'); 47 | else 48 | draw_bounding_box(bb_x0, bb_x1, bb_y0, bb_y1, 'b'); 49 | end 50 | end 51 | 52 | function draw_cross(xlim, ylim, temp) 53 | 54 | if(temp(1)>xlim(1) && temp(1)ylim(1) && temp(2)=Isize(1)-1 || j<=2 || j>=Isize(2)-1) 108 | continue; 109 | end 110 | if(seg(i,j)~=0 && ~(seg(i-1,j)~=0 && seg(i+1,j)~=0 && seg(i,j-1)~=0 && seg(i,j+1)~=0)) 111 | output(i,j,1)=colorvector(1); 112 | output(i,j,2)=colorvector(2); 113 | output(i,j,3)=colorvector(3); 114 | end 115 | end 116 | end 117 | 118 | function output=addSeeds(rgb,seed) 119 | Isize = size(rgb); 120 | Ssize = size(seed); 121 | assert(Isize(1)==Ssize(1) && Isize(2) ==Ssize(2)); 122 | for i=1:Isize(1) 123 | for j=1:Isize(2) 124 | if(seed(i,j)==127) 125 | rgb(i,j,:) = [255, 0, 0]; 126 | elseif(seed(i,j)==255) 127 | rgb(i,j,:) = [0, 0, 255]; 128 | end 129 | end 130 | end 131 | output = rgb; 132 | -------------------------------------------------------------------------------- /user_interface.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taigw/GrabCut-GraphCut/8fd85e06e8b456447c614c8f3e03ed3d72d7d7c3/user_interface.fig -------------------------------------------------------------------------------- /user_interface.m: -------------------------------------------------------------------------------- 1 | function varargout = user_interface(varargin) 2 | % seg_interface MATLAB code for seg_interface.fig 3 | % seg_interface, by itself, creates a new seg_interface or raises the existing 4 | % singleton*. 5 | % 6 | % H = interface_interface returns the handle to a new seg_interface or the handle to 7 | % the existing singleton*. 8 | % 9 | % seg_interface('CALLBACK',hObject,eventData,handles,...) calls the local 10 | % function named CALLBACK in seg_interface.M with the given input arguments. 11 | % 12 | % seg_interface('Property','Value',...) creates a new seg_interface or raises the 13 | % existing singleton*. Starting from the left, property value pairs are 14 | % applied to the GUI before seg_interface_OpeningFcn gets called. An 15 | % unrecognized property name or invalid value makes property application 16 | % stop. All inputs are passed to seg_interface_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 seg_interface 24 | 25 | % Last Modified by GUIDE v2.5 18-Dec-2018 15:07:44 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', @seg_interface_OpeningFcn, ... 32 | 'gui_OutputFcn', @seg_interface_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 seg_interface is made visible. 48 | function seg_interface_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 seg_interface (see VARARGIN) 54 | 55 | % Choose default command line output for seg_interface 56 | handles.output = hObject; 57 | 58 | % Update handles structure 59 | guidata(hObject, handles); 60 | 61 | % UIWAIT makes seg_interface wait for user response (see UIRESUME) 62 | % uiwait(handles.figure1); 63 | % reset(handles.axes1); 64 | % cla(handles.axes1); 65 | set(gcf,'WindowButtonDownFcn',{@mouse_down}); 66 | set(gcf,'WindowButtonMotionFcn',{@mouse_move}); 67 | set(gcf,'WindowButtonUpFcn',{@mouse_up}); 68 | global glb_handles; 69 | global mouse_state; 70 | global bounding_box_state; 71 | glb_handles = handles; 72 | addpath('./Algorithms'); 73 | mouse_state = 0; 74 | bounding_box_state= 0; 75 | 76 | % --- Outputs from this function are returned to the command line. 77 | function varargout = seg_interface_OutputFcn(hObject, eventdata, handles) 78 | % varargout cell array for returning output args (see VARARGOUT); 79 | % hObject handle to figure 80 | % eventdata reserved - to be defined in a future version of MATLAB 81 | % handles structure with handles and user data (see GUIDATA) 82 | 83 | % Get default command line output from handles structure 84 | varargout{1} = handles.output; 85 | 86 | % --- Executes on button press in pushbutton_load. 87 | function pushbutton_load_Callback(hObject, eventdata, handles) 88 | % hObject handle to pushbutton_load (see GCBO) 89 | % eventdata reserved - to be defined in a future version of MATLAB 90 | % handles structure with handles and user data (see GUIDATA) 91 | global Image; 92 | [filename, pathname, filterindex] = uigetfile({'*.png';'*.jpg';'*.bmp'},'File Selector'); 93 | Image = imread(fullfile(pathname, filename)); 94 | popupmenu1_Callback(hObject, eventdata, handles); 95 | 96 | % --- Executes on button press in pushbutton_seg. 97 | function pushbutton_seg_Callback(hObject, eventdata, handles) 98 | % hObject handle to pushbutton_save (see GCBO) 99 | % eventdata reserved - to be defined in a future version of MATLAB 100 | % handles structure with handles and user data (see GUIDATA) 101 | global Image; 102 | global Seeds; 103 | global Seg; 104 | global bb_x0 bb_x1 bb_y0 bb_y1; 105 | global bounding_box_state; 106 | 107 | current_method = get(handles.popupmenu1,'Value'); 108 | % graph cut 109 | if(current_method == 1) 110 | if(sum(sum(Seeds==127))==0 || sum(sum(Seeds==255))==0) 111 | disp('scribbles not provided!'); 112 | return; 113 | end 114 | graphcut = GMMGraphCutAlgorithm(); 115 | Seg =graphcut.Segment(Image, Seeds); 116 | % grab cut 117 | else 118 | [H, W, C] = size(Image); 119 | if(bounding_box_state ~=2 ) 120 | disp('bounding box not provided!'); 121 | return; 122 | end 123 | mask = zeros([H,W]); 124 | mask(bb_y0:bb_y1, bb_x0:bb_x1)=1; 125 | grabcut = GMMGrabCutAlgorithm(); 126 | Seg =grabcut.Segment(Image, mask,Seeds); 127 | end 128 | ui_update(); 129 | 130 | % --- Executes on button press in pushbutton_save. 131 | function pushbutton_save_Callback(hObject, eventdata, handles) 132 | % hObject handle to pushbutton_save (see GCBO) 133 | % eventdata reserved - to be defined in a future version of MATLAB 134 | % handles structure with handles and user data (see GUIDATA) 135 | global Seg; 136 | [filename, pathname] = uiputfile({'*.png';'*.jpg';'*.bmp'},'File Selector'); 137 | imwrite(Seg*255,fullfile(pathname, filename)); 138 | 139 | 140 | % --- Executes on selection change in popupmenu1. 141 | function popupmenu1_Callback(hObject, eventdata, handles) 142 | % hObject handle to popupmenu1 (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 | % Hints: contents = cellstr(get(hObject,'String')) returns popupmenu1 contents as cell array 147 | % contents{get(hObject,'Value')} returns selected item from popupmenu1 148 | global Image; 149 | global Seeds; 150 | global Seg; 151 | global bounding_box_state; 152 | current_value = get(handles.popupmenu1, 'Value'); 153 | if(current_value == 1) % graph cut 154 | set(handles.radiobutton_bb, 'Visible','Off'); 155 | set(handles.radiobutton_scrb, 'Value', 1.0); 156 | else 157 | set(handles.radiobutton_bb, 'Visible','On'); 158 | set(handles.radiobutton_bb, 'Value', 1.0); 159 | end 160 | [H, W, C] = size(Image); 161 | Seeds = uint8(zeros([H,W])); 162 | Seg = uint8(zeros([H, W])); 163 | bounding_box_state = 0; 164 | ui_update(); 165 | 166 | % --- Executes during object creation, after setting all properties. 167 | function popupmenu1_CreateFcn(hObject, eventdata, handles) 168 | % hObject handle to popupmenu1 (see GCBO) 169 | % eventdata reserved - to be defined in a future version of MATLAB 170 | % handles empty - handles not created until after all CreateFcns called 171 | 172 | % Hint: popupmenu controls usually have a white background on Windows. 173 | % See ISPC and COMPUTER. 174 | if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) 175 | set(hObject,'BackgroundColor','white'); 176 | end 177 | --------------------------------------------------------------------------------