├── .gitattributes
├── LICENSE
├── MBS
├── BG.m
├── MBS.m
├── MBS.mexw64
├── MxArray.obj
├── demo.JPG
├── demo.m
├── doMBS.m
├── getParam.m
├── mex
│ ├── MBS.cpp
│ ├── MBS.hpp
│ ├── MxArray.cpp
│ ├── MxArray.hpp
│ ├── MxArray.obj
│ ├── compile.m
│ ├── compile_win.m
│ └── mexopencv.hpp
└── readme.txt
├── README.md
├── blendTexture.m
├── build_graphCutMex.m
├── calcDist.m
├── calcHomo.m
├── gradient_blend.m
├── graphCutMex.cpp
├── graphCutMex.h
├── graphCutMex.m
├── graphCutMex.mexw64
├── homographyAlign.m
├── main.m
├── matchDelete.m
├── maxflow-v3.03.src
├── CHANGES.TXT
├── GPL.TXT
├── README.TXT
├── block.h
├── graph.cpp
├── graph.h
├── instances.inc
└── maxflow.cpp
├── mbs_saliency.m
├── modelspecific
├── hnormalise.m
├── homography_degen.m
├── homography_fit.m
├── homography_res.m
├── iscolinear.m
├── normalise2dpts.m
├── vgg_H_from_x_lin.m
├── vgg_condition_2d.m
├── vgg_conditioner_from_pts.m
└── vgg_get_nonhomg.m
├── randIndex.m
├── ransacx.m
├── registerTexture.m
├── siftMatch.m
└── vlfeat-0.9.21
└── README.txt
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 | *.cpp linguist-language=MATLAB
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 tianli liao
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/MBS/BG.m:
--------------------------------------------------------------------------------
1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2 | % Implemetation of the saliency detction method described in paper
3 | % "Minimum Barrier Salient Object Detection at 80 FPS", Jianming Zhang,
4 | % Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price, Radomir Mech, ICCV,
5 | % 2015
6 | %
7 | % Copyright (C) 2015 Jianming Zhang
8 | %
9 | % This program is free software: you can redistribute it and/or modify
10 | % it under the terms of the GNU General Public License as published by
11 | % the Free Software Foundation, either version 3 of the License, or
12 | % (at your option) any later version.
13 | %
14 | % This program is distributed in the hope that it will be useful,
15 | % but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | % GNU General Public License for more details.
18 | %
19 | % You should have received a copy of the GNU General Public License
20 | % along with this program. If not, see .
21 | %
22 | % If you have problems about this software, please contact:
23 | % jimmie33@gmail.com
24 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 |
26 | function bgMap = BG(I, reg, m_ratio)
27 |
28 | I = single(I);
29 | rowMargin = round(m_ratio*size(I,1));
30 | colMargin = round(m_ratio*size(I,2));
31 | mRegion = [];
32 | mRegion{end+1} = I(1:rowMargin,:,:);
33 | mRegion{end+1} = I(end-rowMargin+1:end,:,:);
34 | mRegion{end+1} = I(:,1:colMargin,:);
35 | mRegion{end+1} = I(:,end-colMargin+1:end,:);
36 |
37 | tmpMap = zeros(size(I,1)*size(I,2),4);
38 | for i = 1:4
39 | R = reshape(mRegion{i}, size(mRegion{i},1)*size(mRegion{i},2),[]);
40 | covMat = cov(R) + reg*eye(size(I,3));
41 | [U,S,V] = svd(covMat);
42 | P = U*diag(1./diag(sqrt(S)));
43 | V = sum(abs(bsxfun(@minus, reshape(I, size(I,1)*size(I,2),[]), mean(R))*P),2);
44 | tmpMap(:,i) = mat2gray(V);
45 | end
46 |
47 | bgMap = sum(tmpMap,2) - max(tmpMap, [], 2);
48 | bgMap = reshape(bgMap,size(I,1),size(I,2));
49 | bgMap = mat2gray(bgMap);
50 |
51 |
--------------------------------------------------------------------------------
/MBS/MBS.m:
--------------------------------------------------------------------------------
1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2 | % Implemetation of the saliency detction method described in paper
3 | % "Minimum Barrier Salient Object Detection at 80 FPS", Jianming Zhang,
4 | % Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price, Radomir Mech, ICCV,
5 | % 2015
6 | %
7 | % Copyright (C) 2015 Jianming Zhang
8 | %
9 | % This program is free software: you can redistribute it and/or modify
10 | % it under the terms of the GNU General Public License as published by
11 | % the Free Software Foundation, either version 3 of the License, or
12 | % (at your option) any later version.
13 | %
14 | % This program is distributed in the hope that it will be useful,
15 | % but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | % GNU General Public License for more details.
18 | %
19 | % You should have received a copy of the GNU General Public License
20 | % along with this program. If not, see .
21 | %
22 | % If you have problems about this software, please contact:
23 | % jimmie33@gmail.com
24 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 |
26 | % usage: MBS I
27 | %
28 | % I: uint8 3-channle image
29 | % use_lab: boolean flag for using the Lab color space (true by default)
30 | % remove_border: boolean flag for removing artificial border (true by default)
31 | % use_geodesice: boolean flag for replacing MBD with geodesic distance (false by default)
--------------------------------------------------------------------------------
/MBS/MBS.mexw64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/MBS/MBS.mexw64
--------------------------------------------------------------------------------
/MBS/MxArray.obj:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/MBS/MxArray.obj
--------------------------------------------------------------------------------
/MBS/demo.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/MBS/demo.JPG
--------------------------------------------------------------------------------
/MBS/demo.m:
--------------------------------------------------------------------------------
1 |
2 | % MB
3 | paramMB = getParam();
4 | paramMB.use_backgroundness = false;
5 | % MB+
6 | paramMBplus = getParam();
7 | paramMBplus.verbose = true; % to show run time for each step
8 |
9 | % Geodesic
10 | paramGeo = getParam();
11 | paramGeo.use_backgroundness = false;
12 | paramGeo.use_geodesic = true;
13 |
14 | I = imread('demo.jpg');
15 |
16 | paramMBD.use_backgroudness = true;
17 | [pMap1, dMap1] = doMBS(I, paramMB);
18 | [pMapG, dMapG] = doMBS(I, paramGeo);
19 | [pMap2] = doMBS(I, paramMBplus);
20 |
21 | % display results
22 | fh = figure(1);
23 | set(fh, 'OuterPosition', [500,600,800,300]);
24 |
25 | subplot(1,3,1)
26 | imshow(I);
27 | title('Input')
28 |
29 | subplot(1,3,2)
30 | imshow(pMap1)
31 | title('MB')
32 |
33 | subplot(1,3,3)
34 | imshow(pMap2)
35 | title('MB+')
36 |
37 |
38 | fh = figure(2);
39 | set(fh, 'OuterPosition', [500,100,800,500]);
40 |
41 | subplot(2,3,1)
42 | imshow(I);
43 | title('Input')
44 |
45 | subplot(2,3,2)
46 | imshow(dMap1)
47 | title('MBD Map')
48 |
49 | subplot(2,3,3)
50 | imshow(pMap1)
51 | title('MB')
52 |
53 | subplot(2,3,5)
54 | imshow(dMapG)
55 | title('Geodesic Distance Map')
56 | subplot(2,3,6)
57 | imshow(pMapG)
58 | title('Geodesic Saliency Map')
59 |
60 |
--------------------------------------------------------------------------------
/MBS/doMBS.m:
--------------------------------------------------------------------------------
1 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2 | % Implemetation of the saliency detction method described in paper
3 | % "Minimum Barrier Salient Object Detection at 80 FPS", Jianming Zhang,
4 | % Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price, Radomir Mech, ICCV,
5 | % 2015
6 | %
7 | % Copyright (C) 2015 Jianming Zhang
8 | %
9 | % This program is free software: you can redistribute it and/or modify
10 | % it under the terms of the GNU General Public License as published by
11 | % the Free Software Foundation, either version 3 of the License, or
12 | % (at your option) any later version.
13 | %
14 | % This program is distributed in the hope that it will be useful,
15 | % but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | % GNU General Public License for more details.
18 | %
19 | % You should have received a copy of the GNU General Public License
20 | % along with this program. If not, see .
21 | %
22 | % If you have problems about this software, please contact:
23 | % jimmie33@gmail.com
24 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 |
26 |
27 | function [pMap, dMap] = doMBS(I, param)
28 |
29 | if ~exist('param','var')
30 | param = getParam();
31 | end
32 |
33 | scale = param.MAX_DIM/max(size(I,1),size(I,2));
34 | Ir = imresize(I, scale);
35 |
36 | % check the type of the Ir
37 | if ~isa(Ir, 'uint8')
38 | Ir = mat2gray(Ir);
39 | Ir = uint8(Ir*255);
40 | end
41 | if size(Ir, 3) == 1
42 | Ir = repmat(Ir,[1,1,3]);
43 | end
44 |
45 | % compute saliency
46 | tic
47 | dMap = MBS(Ir, param.use_lab, param.remove_border, param.use_geodesic);
48 | t1 = toc;
49 |
50 |
51 | if param.use_backgroundness
52 | tic
53 | bgMap = BG(Ir, param.COV_REG,param.MARGIN_RATIO);
54 | t2 = toc;
55 | dMap = dMap + bgMap;
56 | end
57 | pMap = dMap;
58 |
59 | % postprocess
60 | tic
61 | if param.center_bias
62 | cmap = imresize(param.cmap, [size(pMap,1), size(pMap,2)]);
63 | pMap = pMap.*cmap;
64 | end
65 | pMap = mat2gray(pMap);
66 | radius = floor(param.smooth_alpha*sqrt(mean(pMap(:))));
67 | pMap = morphSmooth(pMap, max(radius, 3));
68 | pMap = enhanceContrast(pMap, param.contrast_b);
69 | t3 = toc;
70 |
71 | pMap = imresize(pMap, [size(I,1), size(I,2)]);
72 | pMap = mat2gray(pMap);
73 |
74 | if param.verbose
75 | fprintf('computing MBD map: %f\n', t1);
76 | if param.use_backgroundness
77 | fprintf('computing BG map: %f\n', t2);
78 | end
79 | fprintf('postprocessing: %f\n', t3);
80 | end
81 |
82 |
83 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
84 | function sMap = morphSmooth(I,width)
85 | % opening by reconstruction followed by closing by reconstruction
86 | % see the following material for detailed explanations
87 | % http://www.mathworks.com/products/demos/image/watershed/ipexwatershed.html
88 | I = uint8(I*255);
89 | se = strel('square',width);
90 | Ie = imerode(I, se);
91 | Iobr = imreconstruct(Ie, I);
92 | Iobrd = imdilate(Iobr, se);
93 | Iobrcbr = imreconstruct(imcomplement(Iobrd), imcomplement(Iobr));
94 | Iobrcbr = imcomplement(Iobrcbr);
95 | sMap = mat2gray(Iobrcbr);
96 |
97 | function pMap = enhanceContrast(I, b)
98 |
99 | t = 0.5*max(I(:));
100 | v1 = mean(I(I>=t));
101 | v2 = mean(I(I.
21 | %
22 | % If you have problems about this software, please contact:
23 | % jimmie33@gmail.com
24 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
25 |
26 |
27 | function param = getParam()
28 |
29 | param.MAX_DIM = 300; % max image dimension in computation
30 | param.use_lab = true; % use Lab color space
31 | param.remove_border = true; % detect and remove artificial image frames
32 | param.use_geodesic = false; % flag for replacing geodesic distance with MBD
33 | param.use_backgroundness = true; % MB+
34 | param.COV_REG = 50; % covariance regularization term for the maximum value of 255*255
35 | param.MARGIN_RATIO = 0.1; % the boundary margion for computing backgroundness map
36 | param.cmap = getCenterMap(param.MAX_DIM); % the center distance map for center bias
37 | param.center_bias = true;
38 | param.smooth_alpha = 50; % see eqn. 9
39 | param.contrast_b = 10; % see eqn. 11
40 | param.verbose = false;
41 |
42 | function cmap = getCenterMap(dim)
43 | X = [1:dim] - dim/2; X = repmat(X.^2,[dim,1]);
44 | Y = X';
45 | cmap = sqrt(X+Y);
46 | cmap = 1-mat2gray(cmap);
--------------------------------------------------------------------------------
/MBS/mex/MBS.cpp:
--------------------------------------------------------------------------------
1 | /*****************************************************************************
2 | * Implemetation of the saliency detction method described in paper
3 | * "Minimum Barrier Salient Object Detection at 80 FPS", Jianming Zhang,
4 | * Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price, Radomir Mech, ICCV,
5 | * 2015
6 | *
7 | * Copyright (C) 2015 Jianming Zhang
8 | *
9 | * This program is free software: you can redistribute it and/or modify
10 | * it under the terms of the GNU General Public License as published by
11 | * the Free Software Foundation, either version 3 of the License, or
12 | * (at your option) any later version.
13 | *
14 | * This program is distributed in the hope that it will be useful,
15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | * GNU General Public License for more details.
18 | *
19 | * You should have received a copy of the GNU General Public License
20 | * along with this program. If not, see .
21 | *
22 | * If you have problems about this software, please contact:
23 | * jimmie33@gmail.com
24 | *******************************************************************************/
25 |
26 | #include
27 | #include
28 | #include "opencv2/opencv.hpp"
29 | #include "mexopencv.hpp"
30 | #include "MBS.hpp"
31 | #include
32 | #include
33 |
34 | using namespace std;
35 | using namespace cv;
36 |
37 | #define MAX_IMG_DIM 300
38 | #define TOLERANCE 0.01
39 | #define FRAME_MAX 20
40 | #define SOBEL_THRESH 0.4
41 |
42 | MBS::MBS(const Mat& src)
43 | :mAttMapCount(0)
44 | {
45 | mSrc=src.clone();
46 | mSaliencyMap = Mat::zeros(src.size(), CV_32FC1);
47 |
48 | split(mSrc, mFeatureMaps);
49 |
50 | for (int i = 0; i < mFeatureMaps.size(); i++)
51 | {
52 | //normalize(mFeatureMaps[i], mFeatureMaps[i], 255.0, 0.0, NORM_MINMAX);
53 | medianBlur(mFeatureMaps[i], mFeatureMaps[i], 5);
54 | }
55 | }
56 |
57 | void MBS::computeSaliency(bool use_geodesic)
58 | {
59 |
60 | if (use_geodesic)
61 | mMBSMap = fastGeodesic(mFeatureMaps);
62 | else
63 | mMBSMap = fastMBS(mFeatureMaps);
64 | normalize(mMBSMap, mMBSMap, 0.0, 1.0, NORM_MINMAX);
65 | mSaliencyMap = mMBSMap;
66 | }
67 |
68 | Mat MBS::getSaliencyMap()
69 | {
70 | Mat ret;
71 | normalize(mSaliencyMap, ret, 0.0, 255.0, NORM_MINMAX);
72 | ret.convertTo(ret, CV_8UC1);
73 | return ret;
74 | }
75 |
76 |
77 | void rasterScan(const Mat& featMap, Mat& map, Mat& lb, Mat& ub)
78 | {
79 | Size sz = featMap.size();
80 | float *pMapup = (float*)map.data + 1;
81 | float *pMap = pMapup + sz.width;
82 | uchar *pFeatup = featMap.data + 1;
83 | uchar *pFeat = pFeatup + sz.width;
84 | uchar *pLBup = lb.data + 1;
85 | uchar *pLB = pLBup + sz.width;
86 | uchar *pUBup = ub.data + 1;
87 | uchar *pUB = pUBup + sz.width;
88 |
89 | float mapPrev;
90 | float featPrev;
91 | uchar lbPrev, ubPrev;
92 |
93 | float lfV, upV;
94 | int flag;
95 | for (int r = 1; r < sz.height - 1; r++)
96 | {
97 | mapPrev = *(pMap - 1);
98 | featPrev = *(pFeat - 1);
99 | lbPrev = *(pLB - 1);
100 | ubPrev = *(pUB - 1);
101 |
102 |
103 | for (int c = 1; c < sz.width - 1; c++)
104 | {
105 | lfV = MAX(*pFeat, ubPrev) - MIN(*pFeat, lbPrev);//(*pFeat >= lbPrev && *pFeat <= ubPrev) ? mapPrev : mapPrev + abs((float)(*pFeat) - featPrev);
106 | upV = MAX(*pFeat, *pUBup) - MIN(*pFeat, *pLBup);//(*pFeat >= *pLBup && *pFeat <= *pUBup) ? *pMapup : *pMapup + abs((float)(*pFeat) - (float)(*pFeatup));
107 |
108 | flag = 0;
109 | if (lfV < *pMap)
110 | {
111 | *pMap = lfV;
112 | flag = 1;
113 | }
114 | if (upV < *pMap)
115 | {
116 | *pMap = upV;
117 | flag = 2;
118 | }
119 |
120 | switch (flag)
121 | {
122 | case 0: // no update
123 | break;
124 | case 1: // update from left
125 | *pLB = MIN(*pFeat, lbPrev);
126 | *pUB = MAX(*pFeat, ubPrev);
127 | break;
128 | case 2: // update from up
129 | *pLB = MIN(*pFeat, *pLBup);
130 | *pUB = MAX(*pFeat, *pUBup);
131 | break;
132 | default:
133 | break;
134 | }
135 |
136 | mapPrev = *pMap;
137 | pMap++; pMapup++;
138 | featPrev = *pFeat;
139 | pFeat++; pFeatup++;
140 | lbPrev = *pLB;
141 | pLB++; pLBup++;
142 | ubPrev = *pUB;
143 | pUB++; pUBup++;
144 | }
145 | pMapup += 2; pMap += 2;
146 | pFeat += 2; pFeatup += 2;
147 | pLBup += 2; pLB += 2;
148 | pUBup += 2; pUB += 2;
149 | }
150 | }
151 |
152 | void invRasterScan(const Mat& featMap, Mat& map, Mat& lb, Mat& ub)
153 | {
154 | Size sz = featMap.size();
155 | int datalen = sz.width*sz.height;
156 | float *pMapdn = (float*)map.data + datalen - 2;
157 | float *pMap = pMapdn - sz.width;
158 | uchar *pFeatdn = featMap.data + datalen - 2;
159 | uchar *pFeat = pFeatdn - sz.width;
160 | uchar *pLBdn = lb.data + datalen - 2;
161 | uchar *pLB = pLBdn - sz.width;
162 | uchar *pUBdn = ub.data + datalen - 2;
163 | uchar *pUB = pUBdn - sz.width;
164 |
165 | float mapPrev;
166 | float featPrev;
167 | uchar lbPrev, ubPrev;
168 |
169 | float rtV, dnV;
170 | int flag;
171 | for (int r = 1; r < sz.height - 1; r++)
172 | {
173 | mapPrev = *(pMap + 1);
174 | featPrev = *(pFeat + 1);
175 | lbPrev = *(pLB + 1);
176 | ubPrev = *(pUB + 1);
177 |
178 | for (int c = 1; c < sz.width - 1; c++)
179 | {
180 | rtV = MAX(*pFeat, ubPrev) - MIN(*pFeat, lbPrev);//(*pFeat >= lbPrev && *pFeat <= ubPrev) ? mapPrev : mapPrev + abs((float)(*pFeat) - featPrev);
181 | dnV = MAX(*pFeat, *pUBdn) - MIN(*pFeat, *pLBdn);//(*pFeat >= *pLBdn && *pFeat <= *pUBdn) ? *pMapdn : *pMapdn + abs((float)(*pFeat) - (float)(*pFeatdn));
182 |
183 | flag = 0;
184 | if (rtV < *pMap)
185 | {
186 | *pMap = rtV;
187 | flag = 1;
188 | }
189 | if (dnV < *pMap)
190 | {
191 | *pMap = dnV;
192 | flag = 2;
193 | }
194 |
195 | switch (flag)
196 | {
197 | case 0: // no update
198 | break;
199 | case 1: // update from right
200 | *pLB = MIN(*pFeat, lbPrev);
201 | *pUB = MAX(*pFeat, ubPrev);
202 | break;
203 | case 2: // update from down
204 | *pLB = MIN(*pFeat, *pLBdn);
205 | *pUB = MAX(*pFeat, *pUBdn);
206 | break;
207 | default:
208 | break;
209 | }
210 |
211 | mapPrev = *pMap;
212 | pMap--; pMapdn--;
213 | featPrev = *pFeat;
214 | pFeat--; pFeatdn--;
215 | lbPrev = *pLB;
216 | pLB--; pLBdn--;
217 | ubPrev = *pUB;
218 | pUB--; pUBdn--;
219 | }
220 |
221 |
222 | pMapdn -= 2; pMap -= 2;
223 | pFeatdn -= 2; pFeat -= 2;
224 | pLBdn -= 2; pLB -= 2;
225 | pUBdn -= 2; pUB -= 2;
226 | }
227 | }
228 |
229 | cv::Mat fastMBS(const std::vector featureMaps)
230 | {
231 | assert(featureMaps[0].type() == CV_8UC1);
232 |
233 | Size sz = featureMaps[0].size();
234 | Mat ret = Mat::zeros(sz, CV_32FC1);
235 | if (sz.width < 3 || sz.height < 3)
236 | return ret;
237 |
238 | for (int i = 0; i < featureMaps.size(); i++)
239 | {
240 | Mat map = Mat::zeros(sz, CV_32FC1);
241 | Mat mapROI(map, Rect(1, 1, sz.width - 2, sz.height - 2));
242 | mapROI.setTo(Scalar(100000));
243 | Mat lb = featureMaps[i].clone();
244 | Mat ub = featureMaps[i].clone();
245 |
246 | rasterScan(featureMaps[i], map, lb, ub);
247 | invRasterScan(featureMaps[i], map, lb, ub);
248 | rasterScan(featureMaps[i], map, lb, ub);
249 |
250 | ret += map;
251 | }
252 |
253 | return ret;
254 |
255 | }
256 |
257 | float getThreshForGeo(const Mat& src)
258 | {
259 | float ret;
260 | Size sz = src.size();
261 |
262 | uchar *pFeatup = src.data + 1;
263 | uchar *pFeat = pFeatup + sz.width;
264 | uchar *pfeatdn = pFeat + sz.width;
265 |
266 | float featPrev;
267 |
268 | for (int r = 1; r < sz.height - 1; r++)
269 | {
270 | featPrev = *(pFeat - 1);
271 |
272 | for (int c = 1; c < sz.width - 1; c++)
273 | {
274 | float temp = MIN(abs(*pFeat-featPrev),abs(*pFeat-*(pFeat+1)));
275 | temp = MIN(temp,abs(*pFeat-*pFeatup));
276 | temp = MIN(temp,abs(*pFeat-*pfeatdn));
277 | ret += temp;
278 |
279 | featPrev = *pFeat;
280 | pFeat++; pFeatup++; pfeatdn++;
281 | }
282 | pFeat += 2; pFeatup += 2; pfeatdn += 2;
283 | }
284 | return ret / ((sz.width - 2)*(sz.height - 2));
285 | }
286 |
287 | void rasterScanGeo(const Mat& featMap, Mat& map, float thresh)
288 | {
289 | Size sz = featMap.size();
290 | float *pMapup = (float*)map.data + 1;
291 | float *pMap = pMapup + sz.width;
292 | uchar *pFeatup = featMap.data + 1;
293 | uchar *pFeat = pFeatup + sz.width;
294 |
295 | float mapPrev;
296 | float featPrev;
297 |
298 | float lfV, upV;
299 | int flag;
300 | for (int r = 1; r < sz.height - 1; r++)
301 | {
302 | mapPrev = *(pMap - 1);
303 | featPrev = *(pFeat - 1);
304 |
305 |
306 | for (int c = 1; c < sz.width - 1; c++)
307 | {
308 | lfV = (abs(featPrev - *pFeat)>thresh ? abs(featPrev - *pFeat):0.0f) + mapPrev;
309 | upV = (abs(*pFeatup - *pFeat)>thresh ? abs(*pFeatup - *pFeat):0.0f) + *pMapup;
310 |
311 | if (lfV < *pMap)
312 | {
313 | *pMap = lfV;
314 | }
315 | if (upV < *pMap)
316 | {
317 | *pMap = upV;
318 | }
319 |
320 | mapPrev = *pMap;
321 | pMap++; pMapup++;
322 | featPrev = *pFeat;
323 | pFeat++; pFeatup++;
324 | }
325 | pMapup += 2; pMap += 2;
326 | pFeat += 2; pFeatup += 2;
327 | }
328 | }
329 |
330 | void invRasterScanGeo(const Mat& featMap, Mat& map, float thresh)
331 | {
332 | Size sz = featMap.size();
333 | int datalen = sz.width*sz.height;
334 | float *pMapdn = (float*)map.data + datalen - 2;
335 | float *pMap = pMapdn - sz.width;
336 | uchar *pFeatdn = featMap.data + datalen - 2;
337 | uchar *pFeat = pFeatdn - sz.width;
338 |
339 | float mapPrev;
340 | float featPrev;
341 |
342 | float rtV, dnV;
343 | int flag;
344 | for (int r = 1; r < sz.height - 1; r++)
345 | {
346 | mapPrev = *(pMap + 1);
347 | featPrev = *(pFeat + 1);
348 |
349 | for (int c = 1; c < sz.width - 1; c++)
350 | {
351 | rtV = (abs(featPrev - *pFeat)>thresh ? abs(featPrev - *pFeat):0.0f) + mapPrev;
352 | dnV = (abs(*pFeatdn - *pFeat)>thresh ? abs(*pFeatdn - *pFeat):0.0f) + *pMapdn;
353 |
354 | if (rtV < *pMap)
355 | {
356 | *pMap = rtV;
357 | }
358 | if (dnV < *pMap)
359 | {
360 | *pMap = dnV;
361 | }
362 |
363 | mapPrev = *pMap;
364 | pMap--; pMapdn--;
365 | featPrev = *pFeat;
366 | pFeat--; pFeatdn--;
367 | }
368 |
369 |
370 | pMapdn -= 2; pMap -= 2;
371 | pFeatdn -= 2; pFeat -= 2;
372 | }
373 | }
374 |
375 | cv::Mat fastGeodesic(const std::vector featureMaps)
376 | {
377 | assert(featureMaps[0].type() == CV_8UC1);
378 |
379 | Size sz = featureMaps[0].size();
380 | Mat ret = Mat::zeros(sz, CV_32FC1);
381 | if (sz.width < 3 || sz.height < 3)
382 | return ret;
383 |
384 |
385 | for (int i = 0; i < featureMaps.size(); i++)
386 | {
387 | // determines the threshold for clipping
388 | float thresh = getThreshForGeo(featureMaps[i]);
389 | //cout << thresh << endl;
390 | Mat map = Mat::zeros(sz, CV_32FC1);
391 | Mat mapROI(map, Rect(1, 1, sz.width - 2, sz.height - 2));
392 | mapROI.setTo(Scalar(1000000000));
393 |
394 | rasterScanGeo(featureMaps[i], map, thresh);
395 | invRasterScanGeo(featureMaps[i], map, thresh);
396 | rasterScanGeo(featureMaps[i], map, thresh);
397 |
398 | ret += map;
399 | }
400 |
401 | return ret;
402 |
403 | }
404 |
405 | int findFrameMargin(const Mat& img, bool reverse)
406 | {
407 | Mat edgeMap, edgeMapDil, edgeMask;
408 | Sobel(img, edgeMap, CV_16SC1, 0, 1);
409 | edgeMap = abs(edgeMap);
410 | edgeMap.convertTo(edgeMap, CV_8UC1);
411 | edgeMask = edgeMap < (SOBEL_THRESH * 255.0);
412 | dilate(edgeMap, edgeMapDil, Mat(), Point(-1, -1), 2);
413 | edgeMap = edgeMap == edgeMapDil;
414 | edgeMap.setTo(Scalar(0.0), edgeMask);
415 |
416 |
417 | if (!reverse)
418 | {
419 | for (int i = edgeMap.rows - 1; i >= 0; i--)
420 | if (mean(edgeMap.row(i))[0] > 0.6*255.0)
421 | return i + 1;
422 | }
423 | else
424 | {
425 | for (int i = 0; i < edgeMap.rows; i++)
426 | if (mean(edgeMap.row(i))[0] > 0.6*255.0)
427 | return edgeMap.rows - i;
428 | }
429 |
430 | return 0;
431 | }
432 |
433 | bool removeFrame(const cv::Mat& inImg, cv::Mat& outImg, cv::Rect &roi)
434 | {
435 | if (inImg.rows < 2 * (FRAME_MAX + 3) || inImg.cols < 2 * (FRAME_MAX + 3))
436 | {
437 | roi = Rect(0, 0, inImg.cols, inImg.rows);
438 | outImg = inImg;
439 | return false;
440 | }
441 |
442 | Mat imgGray;
443 | cvtColor(inImg, imgGray, CV_RGB2GRAY);
444 |
445 | int up, dn, lf, rt;
446 |
447 | up = findFrameMargin(imgGray.rowRange(0, FRAME_MAX), false);
448 | dn = findFrameMargin(imgGray.rowRange(imgGray.rows - FRAME_MAX, imgGray.rows), true);
449 | lf = findFrameMargin(imgGray.colRange(0, FRAME_MAX).t(), false);
450 | rt = findFrameMargin(imgGray.colRange(imgGray.cols - FRAME_MAX, imgGray.cols).t(), true);
451 |
452 | int margin = MAX(up, MAX(dn, MAX(lf, rt)));
453 | if ( margin == 0 )
454 | {
455 | roi = Rect(0, 0, imgGray.cols, imgGray.rows);
456 | outImg = inImg;
457 | return false;
458 | }
459 |
460 | int count = 0;
461 | count = up == 0 ? count : count + 1;
462 | count = dn == 0 ? count : count + 1;
463 | count = lf == 0 ? count : count + 1;
464 | count = rt == 0 ? count : count + 1;
465 |
466 | // cut four border region if at least 2 border frames are detected
467 | if (count > 1)
468 | {
469 | margin += 2;
470 | roi = Rect(margin, margin, inImg.cols - 2*margin, inImg.rows - 2*margin);
471 | outImg = Mat(inImg, roi);
472 |
473 | return true;
474 | }
475 |
476 | // otherwise, cut only one border
477 | up = up == 0 ? up : up + 2;
478 | dn = dn == 0 ? dn : dn + 2;
479 | lf = lf == 0 ? lf : lf + 2;
480 | rt = rt == 0 ? rt : rt + 2;
481 |
482 |
483 | roi = Rect(lf, up, inImg.cols - lf - rt, inImg.rows - up - dn);
484 | outImg = Mat(inImg, roi);
485 |
486 | return true;
487 |
488 | }
489 |
490 | Mat doWork(
491 | const Mat& src,
492 | bool use_lab,
493 | bool remove_border,
494 | bool use_geodesic
495 | )
496 | {
497 | Mat src_small;
498 | float w = (float)src.cols, h = (float)src.rows;
499 | float maxD = max(w,h);
500 | resize(src,src_small,Size((int)(MAX_IMG_DIM*w/maxD),(int)(MAX_IMG_DIM*h/maxD)),0.0,0.0,INTER_AREA);// standard: width: 300 pixel
501 | Mat srcRoi;
502 | Rect roi;
503 | // detect and remove the artifical frame of the image
504 | if (remove_border)
505 | removeFrame(src_small, srcRoi, roi);
506 | else
507 | {
508 | srcRoi = src_small;
509 | roi = Rect(0, 0, src_small.cols, src_small.rows);
510 | }
511 |
512 |
513 | if (use_lab)
514 | cvtColor(srcRoi, srcRoi, CV_RGB2Lab);
515 |
516 | /* Computing saliency */
517 | MBS mbs(srcRoi);
518 | mbs.computeSaliency(use_geodesic);
519 |
520 | Mat resultRoi=mbs.getSaliencyMap();
521 | Mat result = Mat::zeros(src_small.size(), CV_32FC1);
522 |
523 | normalize(resultRoi, Mat(result, roi), 0.0, 1.0, NORM_MINMAX);
524 |
525 | resize(result, result, src.size());
526 | return result;
527 | }
528 |
529 |
530 | /**
531 | * Main entry called from Matlab
532 | * @param nlhs number of left-hand-side arguments
533 | * @param plhs pointers to mxArrays in the left-hand-side
534 | * @param nrhs number of right-hand-side arguments
535 | * @param prhs pointers to mxArrays in the right-hand-side
536 | */
537 | void mexFunction( int nlhs, mxArray *plhs[],
538 | int nrhs, const mxArray *prhs[] )
539 | {
540 | // Check the number of arguments
541 | if (nrhs<1 || nrhs > 4 || nlhs>1)
542 | mexErrMsgIdAndTxt("mexopencv:error","Wrong number of arguments");
543 |
544 | // Decide second arguments
545 | bool use_geodesic = false;
546 | bool use_lab = true;
547 | bool remove_border = true;
548 | if (nrhs >= 2)
549 | use_lab = mxIsLogicalScalarTrue(prhs[1]);
550 | if (nrhs >= 3)
551 | remove_border = mxIsLogicalScalarTrue(prhs[2]);
552 | if (nrhs >= 4)
553 | use_geodesic = mxIsLogicalScalarTrue(prhs[3]);
554 |
555 | // Apply
556 | Mat src(((MxArray)prhs[0]).toMat()), dst;
557 | dst = doWork(src, use_lab, remove_border, use_geodesic);
558 | plhs[0] = MxArray(dst);
559 | }
560 |
--------------------------------------------------------------------------------
/MBS/mex/MBS.hpp:
--------------------------------------------------------------------------------
1 | /*****************************************************************************
2 | * Implemetation of the saliency detction method described in paper
3 | * "Minimum Barrier Salient Object Detection at 80 FPS", Jianming Zhang,
4 | * Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price, Radomir Mech, ICCV,
5 | * 2015
6 | *
7 | * Copyright (C) 2015 Jianming Zhang
8 | *
9 | * This program is free software: you can redistribute it and/or modify
10 | * it under the terms of the GNU General Public License as published by
11 | * the Free Software Foundation, either version 3 of the License, or
12 | * (at your option) any later version.
13 | *
14 | * This program is distributed in the hope that it will be useful,
15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 | * GNU General Public License for more details.
18 | *
19 | * You should have received a copy of the GNU General Public License
20 | * along with this program. If not, see .
21 | *
22 | * If you have problems about this software, please contact:
23 | * jimmie33@gmail.com
24 | *******************************************************************************/
25 |
26 | #ifndef BMS_H
27 | #define BMS_H
28 |
29 | #ifdef IMDEBUG
30 | #include
31 | #endif
32 | #include
33 | #include
34 | #include
35 |
36 |
37 | static cv::RNG MBS_RNG;
38 |
39 | class MBS
40 | {
41 | public:
42 | MBS (const cv::Mat& src);
43 | cv::Mat getSaliencyMap();
44 | void computeSaliency(bool use_geodesic = false);
45 | cv::Mat getMBSMap() const { return mMBSMap; }
46 | private:
47 | cv::Mat mSaliencyMap;
48 | cv::Mat mMBSMap;
49 | int mAttMapCount;
50 | cv::Mat mBorderPriorMap;
51 | cv::Mat mSrc;
52 | std::vector mFeatureMaps;
53 | void whitenFeatMap(float reg);
54 | void computeBorderPriorMap(float reg, float marginRatio);
55 | };
56 |
57 | cv::Mat computeCWS(const cv::Mat src, float reg, float marginRatio);
58 | cv::Mat fastMBS(const std::vector featureMaps);
59 | cv::Mat fastGeodesic(const std::vector featureMaps);
60 |
61 | int findFrameMargin(const cv::Mat& img, bool reverse);
62 | bool removeFrame(const cv::Mat& inImg, cv::Mat& outImg, cv::Rect &roi);
63 |
64 | #endif
--------------------------------------------------------------------------------
/MBS/mex/MxArray.cpp:
--------------------------------------------------------------------------------
1 | /** Implemenation of MxArray.
2 | * @file MxArray.cpp
3 | * @author Kota Yamaguchi
4 | * @date 2012
5 | */
6 | #include "MxArray.hpp"
7 |
8 | namespace { // namespace
9 |
10 | /** Field names for cv::Moments.
11 | */
12 | const char *cv_moments_fields[10] = {"m00", "m10", "m01", "m20", "m11", "m02",
13 | "m30", "m21", "m12", "m03"};
14 | /** Field names for cv::RotatedRect.
15 | */
16 | const char *cv_rotated_rect_fields[3] = {"center", "size", "angle"};
17 | /** Field names for cv::TermCriteria.
18 | */
19 | const char *cv_term_criteria_fields[3] = {"type", "maxCount", "epsilon"};
20 | /** Field names for cv::Keypoint.
21 | */
22 | const char *cv_keypoint_fields[6] = {"pt", "size", "angle", "response",
23 | "octave", "class_id"};
24 | /** Field names for cv::DMatch.
25 | */
26 | const char *cv_dmatch_fields[4] = {"queryIdx", "trainIdx", "imgIdx",
27 | "distance"};
28 |
29 | /** Translates data type definition used in OpenCV to that of Matlab.
30 | * @param classid data type of matlab's mxArray. e.g., mxDOUBLE_CLASS.
31 | * @return opencv's data type. e.g., CV_8U.
32 | */
33 | const ConstMap DepthOf = ConstMap
34 | (mxDOUBLE_CLASS, CV_64F)
35 | (mxSINGLE_CLASS, CV_32F)
36 | (mxINT8_CLASS, CV_8S)
37 | (mxUINT8_CLASS, CV_8U)
38 | (mxINT16_CLASS, CV_16S)
39 | (mxUINT16_CLASS, CV_16U)
40 | (mxINT32_CLASS, CV_32S)
41 | (mxUINT32_CLASS, CV_32S)
42 | (mxLOGICAL_CLASS, CV_8U);
43 |
44 | /** Translates data type definition used in Matlab to that of OpenCV.
45 | * @param depth data depth of opencv's Mat class. e.g., CV_32F.
46 | * @return data type of matlab's mxArray. e.g., mxDOUBLE_CLASS.
47 | */
48 | const ConstMap ClassIDOf = ConstMap
49 | (CV_64F, mxDOUBLE_CLASS)
50 | (CV_32F, mxSINGLE_CLASS)
51 | (CV_8S, mxINT8_CLASS)
52 | (CV_8U, mxUINT8_CLASS)
53 | (CV_16S, mxINT16_CLASS)
54 | (CV_16U, mxUINT16_CLASS)
55 | (CV_32S, mxINT32_CLASS);
56 |
57 | /** Comparison operator for sparse matrix elements.
58 | */
59 | struct CompareSparseMatNode {
60 | bool operator () (const cv::SparseMat::Node* rhs,
61 | const cv::SparseMat::Node* lhs)
62 | {
63 | if (rhs->idx[1] < lhs->idx[1])
64 | return true;
65 | if (rhs->idx[1] == lhs->idx[1] && rhs->idx[0] < lhs->idx[0])
66 | return true;
67 | return false;
68 | }
69 | };
70 |
71 | /** InvTermCritType map for option processing.
72 | */
73 | const ConstMap InvTermCritType = ConstMap
74 | (cv::TermCriteria::COUNT, "Count")
75 | (cv::TermCriteria::EPS, "EPS")
76 | (cv::TermCriteria::COUNT+cv::TermCriteria::EPS, "Count+EPS");
77 |
78 | /** TermCritType map for option processing.
79 | */
80 | const ConstMap TermCritType = ConstMap
81 | ("Count", cv::TermCriteria::COUNT)
82 | ("EPS", cv::TermCriteria::EPS)
83 | ("Count+EPS", cv::TermCriteria::COUNT+cv::TermCriteria::EPS);
84 |
85 | } // namespace
86 |
87 | MxArray& MxArray::operator=(const MxArray& rhs)
88 | {
89 | if (this != &rhs)
90 | this->p_ = rhs.p_;
91 | return *this;
92 | }
93 |
94 | MxArray::MxArray(const int i)
95 | : p_(mxCreateDoubleScalar(static_cast(i)))
96 | {
97 | if (!p_)
98 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
99 | }
100 |
101 | MxArray::MxArray(const double d) : p_(mxCreateDoubleScalar(d))
102 | {
103 | if (!p_)
104 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
105 | }
106 |
107 | MxArray::MxArray(const bool b) : p_(mxCreateLogicalScalar(b))
108 | {
109 | if (!p_)
110 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
111 | }
112 |
113 | MxArray::MxArray(const std::string& s) : p_(mxCreateString(s.c_str()))
114 | {
115 | if (!p_)
116 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
117 | }
118 |
119 | MxArray::MxArray(const cv::Mat& mat, mxClassID classid, bool transpose)
120 | {
121 | if (mat.empty())
122 | {
123 | p_ = mxCreateNumericArray(0, 0, mxDOUBLE_CLASS, mxREAL);
124 | if (!p_)
125 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
126 | return;
127 | }
128 | cv::Mat input = (mat.dims == 2 && transpose) ? mat.t() : mat;
129 | // Create a new mxArray.
130 | const int nchannels = input.channels();
131 | const int* dims_ = input.size;
132 | std::vector d(dims_, dims_ + input.dims);
133 | d.push_back(nchannels);
134 | classid = (classid == mxUNKNOWN_CLASS)
135 | ? ClassIDOf[input.depth()] : classid;
136 | std::swap(d[0], d[1]);
137 | if (classid == mxLOGICAL_CLASS)
138 | {
139 | // OpenCV's logical true is any nonzero while matlab's true is 1.
140 | cv::compare(input, 0, input, cv::CMP_NE);
141 | input.setTo(1, input);
142 | p_ = mxCreateLogicalArray(d.size(), &d[0]);
143 | }
144 | else {
145 | p_ = mxCreateNumericArray(d.size(), &d[0], classid, mxREAL);
146 | }
147 | if (!p_)
148 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
149 | // Copy each channel.
150 | std::vector channels;
151 | split(input, channels);
152 | std::vector si(d.size(), 0); // subscript index.
153 | int type = CV_MAKETYPE(DepthOf[classid], 1); // destination type.
154 | for (int i = 0; i < nchannels; ++i)
155 | {
156 | si[si.size() - 1] = i; // last dim is a channel index.
157 | void *ptr = reinterpret_cast(
158 | reinterpret_cast(mxGetData(p_)) +
159 | mxGetElementSize(p_) * subs(si));
160 | cv::Mat m(input.dims, dims_, type, ptr);
161 | channels[i].convertTo(m, type); // Write to mxArray through m.
162 | }
163 | }
164 |
165 | MxArray::MxArray(const cv::SparseMat& mat)
166 | {
167 | if (mat.dims() != 2)
168 | mexErrMsgIdAndTxt("mexopencv:error", "cv::Mat is not 2D");
169 | if (mat.type() != CV_32FC1)
170 | mexErrMsgIdAndTxt("mexopencv:error", "cv::Mat is not float");
171 | // Create a sparse array.
172 | int m = mat.size(0), n = mat.size(1), nnz = mat.nzcount();
173 | p_ = mxCreateSparse(m, n, nnz, mxREAL);
174 | if (!p_)
175 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
176 | mwIndex *ir = mxGetIr(p_);
177 | mwIndex *jc = mxGetJc(p_);
178 | if (ir == NULL || jc == NULL)
179 | mexErrMsgIdAndTxt("mexopencv:error", "Unknown error");
180 | // Sort nodes before we put elems into mxArray.
181 | std::vector nodes;
182 | nodes.reserve(nnz);
183 | for (cv::SparseMatConstIterator it = mat.begin(); it != mat.end(); ++it)
184 | nodes.push_back(it.node());
185 | std::sort(nodes.begin(), nodes.end(), CompareSparseMatNode());
186 | // Copy data.
187 | double *pr = mxGetPr(p_);
188 | int i = 0;
189 | jc[0] = 0;
190 | for (std::vector::const_iterator
191 | it = nodes.begin(); it != nodes.end(); ++it)
192 | {
193 | mwIndex row = (*it)->idx[0], col = (*it)->idx[1];
194 | ir[i] = row;
195 | jc[col+1] = i+1;
196 | pr[i] = static_cast(mat.value(*it));
197 | ++i;
198 | }
199 | }
200 |
201 | MxArray::MxArray(const cv::Moments& m) :
202 | p_(mxCreateStructMatrix(1, 1, 10, cv_moments_fields))
203 | {
204 | if (!p_)
205 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
206 | set("m00", m.m00);
207 | set("m10", m.m10);
208 | set("m01", m.m01);
209 | set("m20", m.m20);
210 | set("m11", m.m11);
211 | set("m02", m.m02);
212 | set("m30", m.m30);
213 | set("m12", m.m12);
214 | set("m21", m.m21);
215 | set("m03", m.m03);
216 | }
217 |
218 | MxArray::MxArray(const cv::KeyPoint& p) :
219 | p_(mxCreateStructMatrix(1, 1, 6, cv_keypoint_fields))
220 | {
221 | if (!p_)
222 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
223 | set("pt", p.pt);
224 | set("size", p.size);
225 | set("angle", p.angle);
226 | set("response", p.response);
227 | set("octave", p.octave);
228 | set("class_id", p.class_id);
229 | }
230 |
231 | MxArray::MxArray(const std::vector& v) :
232 | p_(mxCreateStructMatrix(1, v.size(), 6, cv_keypoint_fields))
233 | {
234 | if (!p_)
235 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
236 | for (size_t i = 0; i < v.size(); ++i)
237 | {
238 | set("pt", v[i].pt, i);
239 | set("size", v[i].size, i);
240 | set("angle", v[i].angle, i);
241 | set("response", v[i].response, i);
242 | set("octave", v[i].octave, i);
243 | set("class_id", v[i].class_id, i);
244 | }
245 | }
246 |
247 | MxArray::MxArray(const cv::DMatch& m) :
248 | p_(mxCreateStructMatrix(1, 1, 4, cv_keypoint_fields))
249 | {
250 | if (!p_)
251 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
252 | set("queryIdx", m.queryIdx);
253 | set("trainIdx", m.trainIdx);
254 | set("imgIdx", m.imgIdx);
255 | set("distance", m.distance);
256 | }
257 |
258 | MxArray::MxArray(const std::vector& v) :
259 | p_(mxCreateStructMatrix(1, v.size(), 4, cv_dmatch_fields))
260 | {
261 | if (!p_)
262 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
263 | for (size_t i = 0; i < v.size(); ++i)
264 | {
265 | set("queryIdx", v[i].queryIdx, i);
266 | set("trainIdx", v[i].trainIdx, i);
267 | set("imgIdx", v[i].imgIdx, i);
268 | set("distance", v[i].distance, i);
269 | }
270 | }
271 |
272 | MxArray::MxArray(const cv::RotatedRect& m) :
273 | p_(mxCreateStructMatrix(1, 1, 3, cv_rotated_rect_fields))
274 | {
275 | if (!p_)
276 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
277 | set("center", m.center);
278 | set("size", m.size);
279 | set("angle", m.angle);
280 | }
281 |
282 | MxArray::MxArray(const cv::TermCriteria& t) :
283 | p_(mxCreateStructMatrix(1, 1, 3, cv_term_criteria_fields))
284 | {
285 | if (!p_)
286 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
287 | set("type", InvTermCritType[t.type]);
288 | set("maxCount", t.maxCount);
289 | set("epsilon", t.epsilon);
290 | }
291 |
292 | MxArray::MxArray(const char** fields, int nfields, int m, int n) :
293 | p_(mxCreateStructMatrix(m, n, nfields, fields))
294 | {
295 | if (!p_)
296 | mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
297 | }
298 |
299 | int MxArray::toInt() const {
300 | if (numel() != 1)
301 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray is not a scalar");
302 | return at(0);
303 | }
304 |
305 | double MxArray::toDouble() const {
306 | if (numel() != 1)
307 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray is not a scalar");
308 | return at(0);
309 | }
310 |
311 | bool MxArray::toBool() const {
312 | if (numel() != 1)
313 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray is not a scalar");
314 | return at(0);
315 | }
316 |
317 | std::string MxArray::toString() const
318 | {
319 | if (!isChar())
320 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray not of type char");
321 | char *pc = mxArrayToString(p_);
322 | std::string s(pc);
323 | mxFree(pc);
324 | return s;
325 | }
326 |
327 | cv::Mat MxArray::toMat(int depth, bool transpose) const
328 | {
329 | // Create cv::Mat object.
330 | std::vector d(dims(), dims()+ndims());
331 | int ndims = (d.size()>2) ? d.size()-1 : d.size();
332 | int nchannels = (d.size()>2) ? *(d.end()-1) : 1;
333 | depth = (depth==CV_USRTYPE1) ? DepthOf[classID()] : depth;
334 | std::swap(d[0], d[1]);
335 | cv::Mat mat(ndims, &d[0], CV_MAKETYPE(depth, nchannels));
336 | // Copy each channel.
337 | std::vector channels(nchannels);
338 | std::vector si(d.size(), 0); // subscript index
339 | int type = CV_MAKETYPE(DepthOf[classID()], 1); // Source type
340 | for (int i = 0; i(
344 | reinterpret_cast(mxGetData(p_))+
345 | mxGetElementSize(p_)*subs(si));
346 | cv::Mat m(ndims, &d[0], type, pd);
347 | // Read from mxArray through m
348 | m.convertTo(channels[i], CV_MAKETYPE(depth, 1));
349 | }
350 | cv::merge(channels, mat);
351 | return (mat.dims==2 && transpose) ? cv::Mat(mat.t()) : mat;
352 | }
353 |
354 | cv::MatND MxArray::toMatND(int depth, bool transpose) const
355 | {
356 | // Create cv::Mat object.
357 | std::vector d(dims(), dims()+ndims());
358 | std::swap(d[0], d[1]);
359 | cv::MatND m(ndims(), &d[0], CV_MAKETYPE(DepthOf[classID()], 1),
360 | mxGetData(p_));
361 | // Copy.
362 | cv::MatND mat;
363 | depth = (depth==CV_USRTYPE1) ? CV_MAKETYPE(DepthOf[classID()], 1) : depth;
364 | m.convertTo(mat, CV_MAKETYPE(depth, 1));
365 | return (mat.dims==2 && transpose) ? cv::Mat(mat.t()) : mat;
366 | }
367 |
368 | cv::SparseMat MxArray::toSparseMat() const
369 | {
370 | // Check if it's sparse.
371 | if (!isSparse() || !isDouble())
372 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray is not sparse");
373 | mwIndex *ir = mxGetIr(p_);
374 | mwIndex *jc = mxGetJc(p_);
375 | if (ir == NULL || jc == NULL)
376 | mexErrMsgIdAndTxt("mexopencv:error", "Unknown error");
377 | // Create cv::SparseMat.
378 | int m = mxGetM(p_), n = mxGetN(p_);
379 | int dims[] = {m, n};
380 | cv::SparseMat mat(2, dims, CV_32F);
381 | // Copy data.
382 | double *pr = mxGetPr(p_);
383 | for (int j=0; j(ir[i], j) = static_cast(pr[i]);
389 | }
390 | return mat;
391 | }
392 |
393 | cv::Moments MxArray::toMoments(mwIndex index) const
394 | {
395 | return cv::Moments(
396 | (isField("m00")) ? at("m00", index).toDouble() : 0,
397 | (isField("m10")) ? at("m10", index).toDouble() : 0,
398 | (isField("m01")) ? at("m01", index).toDouble() : 0,
399 | (isField("m20")) ? at("m20", index).toDouble() : 0,
400 | (isField("m11")) ? at("m11", index).toDouble() : 0,
401 | (isField("m02")) ? at("m02", index).toDouble() : 0,
402 | (isField("m30")) ? at("m30", index).toDouble() : 0,
403 | (isField("m12")) ? at("m12", index).toDouble() : 0,
404 | (isField("m21")) ? at("m21", index).toDouble() : 0,
405 | (isField("m03")) ? at("m03", index).toDouble() : 0
406 | );
407 | }
408 |
409 | cv::KeyPoint MxArray::toKeyPoint(mwIndex index) const
410 | {
411 | return cv::KeyPoint(
412 | at("pt", index).toPoint2f(),
413 | at("size", index).toDouble(),
414 | (isField("angle")) ? at("angle", index).toDouble() : -1,
415 | (isField("response")) ? at("response", index).toDouble() : 0,
416 | (isField("octave")) ? at("octave", index).toInt() : 0,
417 | (isField("class_id")) ? at("class_id", index).toInt() : -1
418 | );
419 | }
420 |
421 | cv::DMatch MxArray::toDMatch(mwIndex index) const
422 | {
423 | return cv::DMatch(
424 | (isField("queryIdx")) ? at("queryIdx", index).toInt() : 0,
425 | (isField("trainIdx")) ? at("trainIdx", index).toInt() : 0,
426 | (isField("imgIdx")) ? at("imgIdx", index).toInt() : 0,
427 | (isField("distance")) ? at("distance", index).toDouble() : 0
428 | );
429 | }
430 |
431 | cv::Range MxArray::toRange() const
432 | {
433 | cv::Range r;
434 | if (isNumeric() && numel()==2)
435 | r = cv::Range(at(0), at(1));
436 | else if (isChar() && toString()==":")
437 | r = cv::Range::all();
438 | else
439 | mexErrMsgIdAndTxt("mexopencv:error", "Invalid range value");
440 | return r;
441 | }
442 |
443 | cv::TermCriteria MxArray::toTermCriteria(mwIndex index) const
444 | {
445 | MxArray _type(at("type", index));
446 | return cv::TermCriteria(
447 | (_type.isChar()) ? TermCritType[_type.toString()] : _type.toInt(),
448 | at("maxCount", index).toInt(),
449 | at("epsilon", index).toDouble()
450 | );
451 | }
452 |
453 | std::string MxArray::fieldname(int index) const
454 | {
455 | const char *f = mxGetFieldNameByNumber(p_, index);
456 | if (!f)
457 | mexErrMsgIdAndTxt("mexopencv:error",
458 | "Failed to get field name at %d\n", index);
459 | return std::string(f);
460 | }
461 |
462 | std::vector MxArray::fieldnames() const
463 | {
464 | if (!isStruct())
465 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray is not a struct array");
466 | int n = nfields();
467 | std::vector v;
468 | v.reserve(n);
469 | for (int i = 0; i < n; ++i)
470 | v.push_back(fieldname(i));
471 | return v;
472 | }
473 |
474 | mwIndex MxArray::subs(mwIndex i, mwIndex j) const
475 | {
476 | if (i < 0 || i >= rows() || j < 0 || j >= cols())
477 | mexErrMsgIdAndTxt("mexopencv:error", "Subscript out of range");
478 | mwIndex s[] = {i, j};
479 | return mxCalcSingleSubscript(p_, 2, s);
480 | }
481 |
482 | mwIndex MxArray::subs(const std::vector& si) const
483 | {
484 | return mxCalcSingleSubscript(p_, si.size(), &si[0]);
485 | }
486 |
487 | MxArray MxArray::at(const std::string& fieldName, mwIndex index) const
488 | {
489 | if (!isStruct())
490 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray is not struct");
491 | if (index < 0 || numel() <= index)
492 | mexErrMsgIdAndTxt("mexopencv:error", "Out of range in struct array");
493 | mxArray* pm = mxGetField(p_, index, fieldName.c_str());
494 | if (!pm)
495 | mexErrMsgIdAndTxt("mexopencv:error",
496 | "Field '%s' doesn't exist",
497 | fieldName.c_str());
498 | return MxArray(pm);
499 | }
500 |
501 | template <>
502 | MxArray MxArray::at(mwIndex index) const
503 | {
504 | if (!isCell())
505 | mexErrMsgIdAndTxt("mexopencv:error", "MxArray is not cell");
506 | return MxArray(mxGetCell(p_, index));
507 | }
508 |
509 | template <>
510 | void MxArray::set(mwIndex index, const MxArray& value)
511 | {
512 | if (index < 0 || numel() <= index)
513 | mexErrMsgIdAndTxt("mexopencv:error", "Accessing invalid range");
514 | if (!isCell())
515 | mexErrMsgIdAndTxt("mexopencv:error", "Not cell array");
516 | mxSetCell(const_cast(p_), index,
517 | static_cast(value));
518 | }
519 |
520 | template <>
521 | std::vector MxArray::toVector() const
522 | {
523 | if (isCell())
524 | {
525 | int n = numel();
526 | std::vector v;
527 | v.reserve(n);
528 | for (int i = 0; i < n; ++i)
529 | v.push_back(MxArray(mxGetCell(p_, i)));
530 | return v;
531 | }
532 | else
533 | return std::vector(1, *this);
534 | }
535 |
536 | template <>
537 | std::vector MxArray::toVector() const
538 | {
539 | return toVector(
540 | std::const_mem_fun_ref_t(&MxArray::toString));
541 | }
542 |
543 | template <>
544 | std::vector MxArray::toVector() const
545 | {
546 | std::vector v(toVector());
547 | std::vector vm;
548 | vm.reserve(v.size());
549 | for (std::vector::iterator it = v.begin(); it < v.end(); ++it)
550 | vm.push_back((*it).toMat());
551 | return vm;
552 | }
553 |
554 | template <>
555 | std::vector MxArray::toVector() const
556 | {
557 | return toVector(
558 | std::const_mem_fun_ref_t(&MxArray::toPoint));
559 | }
560 |
561 | template <>
562 | std::vector MxArray::toVector() const
563 | {
564 | return toVector(
565 | std::const_mem_fun_ref_t(&MxArray::toPoint2f));
566 | }
567 |
568 | template <>
569 | std::vector MxArray::toVector() const
570 | {
571 | return toVector(
572 | std::const_mem_fun_ref_t(&MxArray::toPoint3f));
573 | }
574 |
575 | template <>
576 | std::vector MxArray::toVector() const
577 | {
578 | int n = numel();
579 | std::vector v;
580 | v.reserve(n);
581 | if (isCell())
582 | for (int i = 0; i < n; ++i)
583 | v.push_back(at(i).toKeyPoint());
584 | else if (isStruct())
585 | for (int i = 0; i < n; ++i)
586 | v.push_back(toKeyPoint(i));
587 | else
588 | mexErrMsgIdAndTxt("mexopencv:error",
589 | "MxArray unable to convert to std::vector");
590 | return v;
591 | }
592 |
593 | template <>
594 | std::vector MxArray::toVector() const
595 | {
596 | int n = numel();
597 | std::vector v;
598 | v.reserve(n);
599 | if (isCell())
600 | for (int i = 0; i < n; ++i)
601 | v.push_back(at(i).toDMatch());
602 | else if (isStruct())
603 | for (int i = 0; i < n; ++i)
604 | v.push_back(toDMatch(i));
605 | else
606 | mexErrMsgIdAndTxt("mexopencv:error",
607 | "MxArray unable to convert to std::vector");
608 | return v;
609 | }
610 |
--------------------------------------------------------------------------------
/MBS/mex/MxArray.obj:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/MBS/mex/MxArray.obj
--------------------------------------------------------------------------------
/MBS/mex/compile.m:
--------------------------------------------------------------------------------
1 | % make the mex file
2 | % Jianming Zhang
3 | % 3/22/2016
4 |
5 | function compile()
6 |
7 | % set the paths to your opencv libs (tested using Opencv2.4)
8 | opts.opencv_include_path = 'D:\opencv2.4.9\opencv\build\include'; % OpenCV include path
9 | opts.opencv_lib_path = 'D:\opencv2.4.9\opencv\build\x64\vc10\lib'; % OpenCV lib path
10 |
11 | opts.clean = false; % clean mode
12 | opts.dryrun = false; % dry run mode
13 | opts.verbose = 1; % output verbosity
14 | opts.debug = false; % enable debug symbols in MEX-files
15 |
16 |
17 | % Clean
18 | if opts.clean
19 | if opts.verbose > 0
20 | fprintf('Cleaning all generated files...\n');
21 | end
22 |
23 | cmd = fullfile('../',['*.' mexext]);
24 | if opts.verbose > 0, disp(cmd); end
25 | if ~opts.dryrun, delete(cmd); end
26 |
27 | cmd = fullfile('*.o');
28 | if opts.verbose > 0, disp(cmd); end
29 | if ~opts.dryrun, delete(cmd); end
30 |
31 | return;
32 | end
33 |
34 | % compile flags
35 | [cv_cflags,cv_libs] = pkg_config(opts);
36 | mex_flags = sprintf('%s %s', cv_cflags, cv_libs);
37 | if opts.verbose > 1
38 | mex_flags = ['-v ' mex_flags]; % verbose mex output
39 | end
40 | if opts.debug
41 | mex_flags = ['-g ' mex_flags]; % debug vs. optimized builds
42 | end
43 | compstr = computer;
44 | is64bit = strcmp(compstr(end-1:end),'64');
45 | if (is64bit)
46 | mex_flags = ['-largeArrayDims ' mex_flags];
47 | end
48 |
49 | % Compile MxArray and BMS
50 | src = 'mex\MxArray.cpp';
51 |
52 | cmd = sprintf('mex %s -c %s', mex_flags, src);
53 | if opts.verbose > 0, disp(cmd); end
54 | if ~opts.dryrun, eval(cmd); end
55 |
56 | src = {'mex\MBS.cpp'};
57 | % Compile the mex file
58 | for i = 1:numel(src)
59 | obj = 'MxArray.obj';
60 | cmd = sprintf('mex %s %s %s -outdir ../', mex_flags, src{i}, obj);
61 | if opts.verbose > 0, disp(cmd); end
62 | if ~opts.dryrun, eval(cmd); end
63 | end
64 |
65 | end
66 |
67 | %
68 | % Helper functions for windows
69 | %
70 | function [cflags,libs] = pkg_config(opts)
71 | %PKG_CONFIG constructs OpenCV-related option flags
72 | I_path = opts.opencv_include_path;
73 | L_path = opts.opencv_lib_path;
74 | l_options = strcat({' -l'}, lib_names(L_path));
75 | %if opts.debug
76 | % l_options = strcat(l_options,'d'); % link against debug binaries
77 | %end
78 | l_options = [l_options{:}];
79 |
80 | if ~exist(I_path,'dir')
81 | error('OpenCV include path not found: %s', I_path);
82 | end
83 | if ~exist(L_path,'dir')
84 | error('OpenCV library path not found: %s', L_path);
85 | end
86 |
87 | cflags = sprintf('-I''%s''', I_path);
88 | libs = sprintf('-L''%s'' %s', L_path, l_options);
89 | end
90 |
91 | function l = lib_names(L_path)
92 | %LIB_NAMES return library names
93 | l = {'opencv_core', 'opencv_imgproc', 'opencv_highgui'};
94 | end
--------------------------------------------------------------------------------
/MBS/mex/compile_win.m:
--------------------------------------------------------------------------------
1 | % make the mex file
2 | % Jianming Zhang
3 | % 3/22/2016
4 |
5 | function compile_win()
6 |
7 | % set the values
8 | opts.opencv_include_path = 'D:\Program Files\opencv_2.4.9\opencv\build\include'; % OpenCV include path
9 | opts.opencv_lib_path = 'D:\Program Files\opencv_2.4.9\opencv\build\x64\vc12\lib'; % OpenCV lib path
10 |
11 | opts.clean = false; % clean mode
12 | opts.dryrun = false; % dry run mode
13 | opts.verbose = 1; % output verbosity
14 | opts.debug = false; % enable debug symbols in MEX-files
15 |
16 |
17 | % Clean
18 | if opts.clean
19 | if opts.verbose > 0
20 | fprintf('Cleaning all generated files...\n');
21 | end
22 |
23 | cmd = fullfile('../',['*.' mexext]);
24 | if opts.verbose > 0, disp(cmd); end
25 | if ~opts.dryrun, delete(cmd); end
26 |
27 | cmd = fullfile('*.obj');
28 | if opts.verbose > 0, disp(cmd); end
29 | if ~opts.dryrun, delete(cmd); end
30 |
31 | return;
32 | end
33 |
34 | % compile flags
35 | [cv_cflags,cv_libs] = pkg_config(opts);
36 | mex_flags = sprintf('%s %s', cv_cflags, cv_libs);
37 | if opts.verbose > 1
38 | mex_flags = ['-v ' mex_flags]; % verbose mex output
39 | end
40 | if opts.debug
41 | mex_flags = ['-g ' mex_flags]; % debug vs. optimized builds
42 | end
43 | compstr = computer;
44 | is64bit = strcmp(compstr(end-1:end),'64');
45 | if (is64bit)
46 | mex_flags = ['-largeArrayDims ' mex_flags];
47 | end
48 |
49 | % Compile MxArray and BMS
50 | src = 'MxArray.cpp';
51 |
52 | cmd = sprintf('mex %s -c %s', mex_flags, src);
53 | if opts.verbose > 0, disp(cmd); end
54 | if ~opts.dryrun, eval(cmd); end
55 |
56 | src = {'MBS.cpp'};
57 | % Compile the mex file
58 | for i = 1:numel(src)
59 | obj = 'MxArray.obj';
60 | cmd = sprintf('mex %s %s %s -outdir ../', mex_flags, src{i}, obj);
61 | if opts.verbose > 0, disp(cmd); end
62 | if ~opts.dryrun, eval(cmd); end
63 | end
64 |
65 | end
66 |
67 | %
68 | % Helper functions for windows
69 | %
70 | function [cflags,libs] = pkg_config(opts)
71 | %PKG_CONFIG constructs OpenCV-related option flags
72 | I_path = opts.opencv_include_path;
73 | L_path = opts.opencv_lib_path;
74 | l_options = strcat({' -l'}, lib_names(L_path));
75 | %if opts.debug
76 | % l_options = strcat(l_options,'d'); % link against debug binaries
77 | %end
78 | l_options = [l_options{:}];
79 |
80 | if ~exist(I_path,'dir')
81 | error('OpenCV include path not found: %s', I_path);
82 | end
83 | if ~exist(L_path,'dir')
84 | error('OpenCV library path not found: %s', L_path);
85 | end
86 |
87 | cflags = sprintf('-I''%s''', I_path);
88 | libs = sprintf('-L''%s'' %s', L_path, l_options);
89 | end
90 |
91 | function l = lib_names(L_path)
92 | %LIB_NAMES return library names
93 | d = dir( fullfile(L_path,'opencv_*.lib') );
94 | l = regexp({d.name}, '(opencv_core.+)\.lib|(opencv_imgproc.+)\.lib|(opencv_highgui.+)\.lib', 'tokens', 'once');
95 | l = [l{:}];
96 | end
--------------------------------------------------------------------------------
/MBS/mex/mexopencv.hpp:
--------------------------------------------------------------------------------
1 | /**
2 | * @file mexopencv.hpp
3 | * @brief Global constant definitions
4 | * @author Kota Yamaguchi
5 | * @date 2012
6 | *
7 | * The header file for a Matlab mex function that uses OpenCV library.
8 | * The file includes definition of MxArray class that converts between mxArray
9 | * and a couple of std:: and cv:: data types including cv::Mat.
10 | */
11 | #ifndef __MEXOPENCV_HPP__
12 | #define __MEXOPENCV_HPP__
13 |
14 | #include "MxArray.hpp"
15 |
16 | // Global constants
17 |
18 | /** BorderType map for option processing
19 | */
20 | const ConstMap BorderType = ConstMap
21 | ("Replicate", cv::BORDER_REPLICATE)
22 | ("Constant", cv::BORDER_CONSTANT)
23 | ("Reflect", cv::BORDER_REFLECT)
24 | ("Wrap", cv::BORDER_WRAP)
25 | ("Reflect101", cv::BORDER_REFLECT_101)
26 | ("Transparent", cv::BORDER_TRANSPARENT)
27 | ("Default", cv::BORDER_DEFAULT)
28 | ("Isolated", cv::BORDER_ISOLATED);
29 |
30 | /** Interpolation type map for option processing
31 | */
32 | const ConstMap InterType = ConstMap
33 | ("Nearest", cv::INTER_NEAREST) //!< nearest neighbor interpolation
34 | ("Linear", cv::INTER_LINEAR) //!< bilinear interpolation
35 | ("Cubic", cv::INTER_CUBIC) //!< bicubic interpolation
36 | ("Area", cv::INTER_AREA) //!< area-based (or super) interpolation
37 | ("Lanczos4", cv::INTER_LANCZOS4) //!< Lanczos interpolation over 8x8 neighborhood
38 | ("Max", cv::INTER_MAX);
39 | //("WarpInverseMap", cv::WARP_INVERSE_MAP);
40 |
41 | /** Thresholding type map for option processing
42 | */
43 | const ConstMap ThreshType = ConstMap
44 | ("Binary", cv::THRESH_BINARY)
45 | ("BinaryInv", cv::THRESH_BINARY_INV)
46 | ("Trunc", cv::THRESH_TRUNC)
47 | ("ToZero", cv::THRESH_TOZERO)
48 | ("ToZeroInv", cv::THRESH_TOZERO_INV)
49 | ("Mask", cv::THRESH_MASK);
50 | //("Otsu", cv::THRESH_OTSU);
51 |
52 | /** Distance types for Distance Transform and M-estimators
53 | */
54 | const ConstMap DistType = ConstMap
55 | ("User", CV_DIST_USER)
56 | ("L1", CV_DIST_L1)
57 | ("L2", CV_DIST_L2)
58 | ("C", CV_DIST_C)
59 | ("L12", CV_DIST_L12)
60 | ("Fair", CV_DIST_FAIR)
61 | ("Welsch", CV_DIST_WELSCH)
62 | ("Huber", CV_DIST_HUBER);
63 |
64 | /** Line type for drawing
65 | */
66 | const ConstMap LineType = ConstMap
67 | ("8", 8)
68 | ("4", 4)
69 | ("AA", CV_AA);
70 |
71 | /** Font faces for drawing
72 | */
73 | const ConstMap FontFace = ConstMap
74 | ("HersheySimplex", CV_FONT_HERSHEY_SIMPLEX)
75 | ("HersheyPlain", CV_FONT_HERSHEY_PLAIN)
76 | ("HersheyDuplex", CV_FONT_HERSHEY_DUPLEX)
77 | ("HersheyComplex", CV_FONT_HERSHEY_COMPLEX)
78 | ("HersheyTriplex", CV_FONT_HERSHEY_TRIPLEX)
79 | ("HersheyComplexSmall", CV_FONT_HERSHEY_COMPLEX_SMALL)
80 | ("HersheyScriptSimplex", CV_FONT_HERSHEY_SCRIPT_SIMPLEX)
81 | ("HersheyScriptComplex", CV_FONT_HERSHEY_SCRIPT_COMPLEX);
82 |
83 | /** Font styles for drawing
84 | */
85 | const ConstMap FontStyle = ConstMap
86 | ("Regular", 0)
87 | ("Italic", CV_FONT_ITALIC);
88 | #endif
89 |
--------------------------------------------------------------------------------
/MBS/readme.txt:
--------------------------------------------------------------------------------
1 | This is a matlab implementation of the method described in:
2 |
3 | "Minimum Barrier Salient Object Detection at 80 FPS", Jianming Zhang,
4 | Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price, Radomir Mech, ICCV, 2015
5 |
6 | Contact: jimmie33@gmail.com
7 |
8 | Prerequisite: OpenCV 2.4+
9 |
10 | Usage:
11 |
12 | 1. Go to the folder "mex"
13 | 2. modify the opencv include and lib paths in "compile.m/compile_win.m"
14 | (for Linux/Windows)
15 | 3. run "compile/compile_win" in matlab (for Linux/Windows)
16 | 4. Go to the root folder
17 | 5. run "demo"
18 |
19 |
20 | This matlab implementation is provided for research purpose only. For fully
21 | reproducing the results in our ICCV paper, please use the original Windows
22 | executable program.
23 |
24 | The matlab implementation is slower than the window executable, mainly due
25 | to the morphological post-processing step. We use the highly optimized IPP
26 | library for the morphological operations in our C++ implementation, which
27 | are much faster than the corresponding Matlab functions.
28 |
29 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Perception-based seam cutting for image stitching
2 |
3 | This repository is our implementation of the paper, Perception-based seam cutting for image stitching. If you use any code or data from our work, please cite our paper.
4 |
5 | ### Usage
6 |
7 | 1. Download code, add images in the folder "Imgs" in the main path and run the "main.m".
8 |
9 | 2. This codehas been tested on 64bit Windows; for other platforms, you'll need to compile your own mex files for "graphCutMex" and saliency detection library in "MBS".
10 |
11 | ### Citation
12 | ```
13 | @article{li2018perception,
14 | title={Perception-based seam cutting for image stitching},
15 | author={Li, Nan and Liao, Tianli and Wang, Chao},
16 | journal={Signal, Image and Video Processing},
17 | volume={12},
18 | number={5},
19 | pages={967--974},
20 | year={2018},
21 | publisher={Springer}
22 | }
23 | ```
24 |
25 | ### Contact
26 |
27 | If you have any comments, suggestions, or questions, please contact me (tianli.liao@haut.edu.cn).
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/blendTexture.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/blendTexture.m
--------------------------------------------------------------------------------
/build_graphCutMex.m:
--------------------------------------------------------------------------------
1 | function build_graphCutMex
2 | % build_graphCutMex builds package graphCutMex
3 | %
4 | % Anton Osokin (firstname.lastname@gmail.com), 19.05.2013
5 |
6 | maxFlowPath = 'maxflow-v3.03.src';
7 |
8 | mexCmd = ['mex graphCutMex.cpp -output graphCutMex -largeArrayDims ', '-I', maxFlowPath];
9 | eval(mexCmd);
10 |
--------------------------------------------------------------------------------
/calcDist.m:
--------------------------------------------------------------------------------
1 | function d = calcDist(H,pts1,pts2)
2 | % Project PTS1 to PTS3 using H, then calcultate the distances between
3 | % PTS2 and PTS3
4 |
5 | n = size(pts1,2);
6 | pts3 = H*[pts1;ones(1,n)];
7 | pts3 = pts3(1:2,:)./repmat(pts3(3,:),2,1);
8 | d = sum((pts2-pts3).^2,1);
9 |
10 | end
--------------------------------------------------------------------------------
/calcHomo.m:
--------------------------------------------------------------------------------
1 | function H = calcHomo(pts1,pts2)
2 | %% use Direct linear tranformation (DLT) to calculate homography
3 | % approxmation: H*[pts1; ones(1,size(pts1,2))] = [pts2; ones(1,size(pts2,2))]
4 | % Normalise point distribution.
5 | data_pts = [ pts1; ones(1,size(pts1,2)) ; pts2; ones(1,size(pts2,2)) ];
6 | [ dat_norm_pts1,T1 ] = normalise2dpts(data_pts(1:3,:));
7 | [ dat_norm_pts2,T2 ] = normalise2dpts(data_pts(4:6,:));
8 | data_norm = [ dat_norm_pts1 ; dat_norm_pts2 ];
9 |
10 | %-----------------------
11 | % Global homography (H).
12 | %-----------------------
13 | %fprintf('DLT (projective transform) on inliers\n');
14 | % Refine homography using DLT on inliers.
15 | %fprintf('> Refining homography (H) using DLT...');
16 | [ h,~,~,~ ] = feval('homography_fit',data_norm);
17 | H = T2\(reshape(h,3,3)*T1);
18 |
19 | end
--------------------------------------------------------------------------------
/gradient_blend.m:
--------------------------------------------------------------------------------
1 | function result = gradient_blend(source, mask, target)
2 | % Uses gradient-domain editing to blend a source image into a target image.
3 | % The target image is the background onto which a region of the source
4 | % image is copied and blended; the region of the source image to be
5 | % transferred is given by a binary mask.
6 | %
7 | % Inputs:
8 | % source: The image from which pixels will be transferred onto the target.
9 | % mask: A binary matrix specifying the region of the source image that
10 | % should be blended into the target.
11 | % target: The image into which the selected source region is blended;
12 | % this serves as the background for blending.
13 | %
14 | % Outputs:
15 | % result: An image of the same dimensions as the source/target,
16 | % representing the output of the gradient domain blending.
17 | %
18 | % This function assumes that the inputs, source, mask, and target, all have
19 | % the same width and height.
20 |
21 |
22 | % To simplify edge cases, we add a 1-pixel border around the source,
23 | % target, and mask. For the source and target images, the extra 1-pixel
24 | % border is created by copying pixel values along the edge, essentially
25 | % extending the original images. For the mask, the extra 1-pixel border
26 | % just consists of all 0s, since we do not want that border to be selected.
27 | % This border is removed after blending.
28 | source = padarray(source, [1,1], 'symmetric');
29 | target = padarray(target, [1,1], 'symmetric');
30 | mask = padarray(mask, [1,1]);
31 |
32 | [t_rows, t_cols, ~] = size(target);
33 |
34 | % We reshape the source and target to have dimensions t_rows*t_cols x 3,
35 | % turning each color channel into a column vector. This greatly simplifies
36 | % later computations, which are performed across all color channels
37 | % simultaneously.
38 | s = reshape(source, t_rows*t_cols, []);
39 | t = reshape(target, t_rows*t_cols, []);
40 |
41 | % Allocate the RHS vector b.
42 | b = zeros(t_rows*t_cols, 3);
43 |
44 | disp('Constructing the matrix A...');
45 | tic
46 |
47 | % We construct the matrix A efficiently from a set of three vectors:
48 | % row_vec has entries that represent row indexes of A; col_vec has entries
49 | % that represent column indexes of A, and value_vec has entries that
50 | % represent the values at specific positions inside A. These three vectors
51 | % are correlated, such that the final matrix A will have (row_vec(index),
52 | % col_vec(index)) = value_vec(index). Thus, for each entry in A, we add one
53 | % entry into each of row_vec, col_vec, and value_vec.
54 | row_vec = zeros(t_rows*t_cols, 1);
55 | col_vec = zeros(t_rows*t_cols, 1);
56 | value_vec = zeros(t_rows*t_cols, 1);
57 |
58 | % Each row of the sparse matrix A represents a linear equation; this
59 | % variable is used to keep track of the current row inside A.
60 | equation_num = 1;
61 |
62 | % The matrix A has one equation for each pixel in the target image; we
63 | % iterate through them, and insert the appropriate values in the matrix A
64 | % and the corresponding values in b:
65 | for index = 1:t_rows*t_cols
66 | if mask(index)
67 | %
68 | b(index,:) = 4*s(index,:) - s(index-1,:) - s(index+1,:) - s(index+t_rows,:) - s(index-t_rows,:);
69 |
70 | % Insert a 4 into A at the index of the current central pixel.
71 | row_vec(equation_num) = index;
72 | col_vec(equation_num) = index;
73 | value_vec(equation_num) = 4;
74 | equation_num = equation_num + 1;
75 |
76 | % Insert a -1 for the pixel below the current pixel:
77 | row_vec(equation_num) = index;
78 | col_vec(equation_num) = index + 1;
79 | value_vec(equation_num) = -1;
80 | equation_num = equation_num + 1;
81 |
82 | % Insert a -1 for the pixel above the current pixel:
83 | row_vec(equation_num) = index;
84 | col_vec(equation_num) = index - 1;
85 | value_vec(equation_num) = -1;
86 | equation_num = equation_num + 1;
87 |
88 | % Insert a -1 for the pixel to the left of the current pixel:
89 | row_vec(equation_num) = index;
90 | col_vec(equation_num) = index - t_rows;
91 | value_vec(equation_num) = -1;
92 | equation_num = equation_num + 1;
93 |
94 | % Insert a -1 for the pixel to the right of the current pixel:
95 | row_vec(equation_num) = index;
96 | col_vec(equation_num) = index + t_rows;
97 | value_vec(equation_num) = -1;
98 | equation_num = equation_num + 1;
99 | else
100 | % If the current pixel location is not in the mask, the final value
101 | % in the blended image is the same as the original value in the
102 | % target image, so we insert a 1 in the matrix A, and copy the
103 | % target value into the appropriate position of the vector b:
104 | row_vec(equation_num) = index;
105 | col_vec(equation_num) = index;
106 | value_vec(equation_num) = 1;
107 | equation_num = equation_num + 1;
108 |
109 | b(index,:) = t(index,:);
110 | end
111 | end
112 |
113 | % We create the sparse matrix efficiently:
114 | A = sparse(row_vec, col_vec, value_vec, t_rows*t_cols, t_rows*t_cols);
115 |
116 | toc
117 | disp('Finished constructing the matrix A...')
118 |
119 | % Solve for each color channel:
120 | f_red = A \ b(:,1);
121 | f_green = A \ b(:,2);
122 | f_blue = A \ b(:,3);
123 |
124 | % Reshape to the original size:
125 | f_red = reshape(f_red, [t_rows, t_cols]);
126 | f_green = reshape(f_green, [t_rows, t_cols]);
127 | f_blue = reshape(f_blue, [t_rows, t_cols]);
128 |
129 | % Stack the channels back together:
130 | result = zeros(t_rows, t_cols, 3);
131 | result(:,:,1) = f_red;
132 | result(:,:,2) = f_green;
133 | result(:,:,3) = f_blue;
134 |
135 | % Chop off the border:
136 | result = result(2:t_rows-1, 2:t_cols-1, :);
137 |
138 | end
--------------------------------------------------------------------------------
/graphCutMex.cpp:
--------------------------------------------------------------------------------
1 |
2 | #include "graphCutMex.h"
3 | #include "mex.h"
4 |
5 | #include
6 | #include
7 |
8 | #define INFTY INT_MAX
9 |
10 | //define types
11 | typedef double EnergyType;
12 | mxClassID MATLAB_ENERGYTERM_TYPE = mxDOUBLE_CLASS;
13 |
14 | typedef double EnergyTermType;
15 | mxClassID MATLAB_ENERGY_TYPE = mxDOUBLE_CLASS;
16 |
17 | typedef double LabelType;
18 | mxClassID MATLAB_LABEL_TYPE = mxDOUBLE_CLASS;
19 | /*
20 | typedef int EnergyType;
21 | mxClassID MATLAB_ENERGYTERM_TYPE = mxINT32_CLASS;
22 |
23 | typedef int EnergyTermType;
24 | mxClassID MATLAB_ENERGY_TYPE = mxINT32_CLASS;
25 |
26 | typedef int LabelType;
27 | mxClassID MATLAB_LABEL_TYPE = mxINT32_CLASS;
28 | */
29 |
30 | typedef Graph GraphType;
31 |
32 | double round(double a);
33 | int isInteger(double a);
34 |
35 | #define MATLAB_ASSERT(expr,msg) if (!(expr)) { mexErrMsgTxt(msg);}
36 |
37 | #if !defined(MX_API_VER) || MX_API_VER < 0x07030000
38 | typedef int mwSize;
39 | typedef int mwIndex;
40 | #endif
41 |
42 |
43 |
44 | void mexFunction(int nlhs, mxArray *plhs[],
45 | int nrhs, const mxArray *prhs[])
46 | {
47 | MATLAB_ASSERT( nrhs == 2, "graphCutMex: Wrong number of input parameters: expected 2");
48 | MATLAB_ASSERT( nlhs <= 2, "graphCutMex: Too many output arguments: expected 2 or less");
49 |
50 | //Fix input parameter order:
51 | const mxArray *uInPtr = (nrhs >= 1) ? prhs[0] : NULL; //unary
52 | const mxArray *pInPtr = (nrhs >= 2) ? prhs[1] : NULL; //pairwise
53 |
54 | //Fix output parameter order:
55 | mxArray **cOutPtr = (nlhs >= 1) ? &plhs[0] : NULL; //cut
56 | mxArray **lOutPtr = (nlhs >= 2) ? &plhs[1] : NULL; //labels
57 |
58 | //node number
59 | int numNodes;
60 |
61 | // get unary potentials
62 | MATLAB_ASSERT(mxGetNumberOfDimensions(uInPtr) == 2, "graphCutMex: The first paramater is not 2-dimensional");
63 | MATLAB_ASSERT(mxGetClassID(uInPtr) == MATLAB_ENERGYTERM_TYPE, "graphCutMex: Unary potentials are of wrong type");
64 | MATLAB_ASSERT(mxGetPi(uInPtr) == NULL, "graphCutMex: Unary potentials should not be complex");
65 |
66 | numNodes = mxGetM(uInPtr);
67 |
68 | MATLAB_ASSERT(numNodes >= 1, "graphCutMex: The number of nodes is not positive");
69 | MATLAB_ASSERT(mxGetN(uInPtr) == 2, "graphCutMex: The first paramater is not of size #nodes x 2");
70 |
71 | EnergyTermType* termW = (EnergyTermType*)mxGetData(uInPtr);
72 |
73 | //get pairwise potentials
74 | MATLAB_ASSERT(mxGetNumberOfDimensions(pInPtr) == 2, "graphCutMex: The second paramater is not 2-dimensional");
75 |
76 | mwSize numEdges = mxGetM(pInPtr);
77 |
78 | MATLAB_ASSERT( mxGetN(pInPtr) == 4, "graphCutMex: The second paramater is not of size #edges x 4");
79 | MATLAB_ASSERT(mxGetClassID(pInPtr) == MATLAB_ENERGYTERM_TYPE, "graphCutMex: Pairwise potentials are of wrong type");
80 |
81 | EnergyTermType* edges = (EnergyTermType*)mxGetData(pInPtr);
82 | for(int i = 0; i < numEdges; i++)
83 | {
84 | MATLAB_ASSERT(1 <= round(edges[i]) && round(edges[i]) <= numNodes, "graphCutMex: error in pairwise terms array: wrong vertex index");
85 | MATLAB_ASSERT(isInteger(edges[i]), "graphCutMex: error in pairwise terms array: wrong vertex index");
86 | MATLAB_ASSERT(1 <= round(edges[i + numEdges]) && round(edges[i + numEdges]) <= numNodes, "graphCutMex: error in pairwise terms array: wrong vertex index");
87 | MATLAB_ASSERT(isInteger(edges[i + numEdges]), "graphCutMex: error in pairwise terms array: wrong vertex index");
88 | MATLAB_ASSERT(edges[i + 2 * numEdges] + edges[i + 3 * numEdges] >= 0, "graphCutMex: error in pairwise terms array: nonsubmodular edge");
89 | }
90 |
91 |
92 | // start computing
93 | if (nlhs == 0){
94 | return;
95 | }
96 |
97 | //prepare graph
98 | GraphType *g = new GraphType( numNodes, numEdges);
99 |
100 | for(int i = 0; i < numNodes; i++)
101 | {
102 | g -> add_node();
103 | g -> add_tweights( i, termW[i], termW[numNodes + i]);
104 | }
105 |
106 | for(int i = 0; i < numEdges; i++)
107 | if(edges[i] < 1 || edges[i] > numNodes || edges[numEdges + i] < 1 || edges[numEdges + i] > numNodes || edges[i] == edges[numEdges + i] || !isInteger(edges[i]) || !isInteger(edges[numEdges + i])){
108 | mexWarnMsgIdAndTxt("graphCutMex:pairwisePotentials", "Some edge has invalid vertex numbers and therefore it is ignored");
109 | }
110 | else
111 | if(edges[2 * numEdges + i] + edges[3 * numEdges + i] < 0){
112 | mexWarnMsgIdAndTxt("graphCutMex:pairwisePotentials", "Some edge is non-submodular and therefore it is ignored");
113 | }
114 | else
115 | {
116 | if (edges[2 * numEdges + i] >= 0 && edges[3 * numEdges + i] >= 0)
117 | g -> add_edge((GraphType::node_id)round(edges[i] - 1), (GraphType::node_id)round(edges[numEdges + i] - 1), edges[2 * numEdges + i], edges[3 * numEdges + i]);
118 | else
119 | if (edges[2 * numEdges + i] <= 0 && edges[3 * numEdges + i] >= 0)
120 | {
121 | g -> add_edge((GraphType::node_id)round(edges[i] - 1), (GraphType::node_id)round(edges[numEdges + i] - 1), 0, edges[3 * numEdges + i] + edges[2 * numEdges + i]);
122 | g -> add_tweights((GraphType::node_id)round(edges[i] - 1), 0, edges[2 * numEdges + i]);
123 | g -> add_tweights((GraphType::node_id)round(edges[numEdges + i] - 1),0 , -edges[2 * numEdges + i]);
124 | }
125 | else
126 | if (edges[2 * numEdges + i] >= 0 && edges[3 * numEdges + i] <= 0)
127 | {
128 | g -> add_edge((GraphType::node_id)round(edges[i] - 1), (GraphType::node_id)round(edges[numEdges + i] - 1), edges[3 * numEdges + i] + edges[2 * numEdges + i], 0);
129 | g -> add_tweights((GraphType::node_id)round(edges[i] - 1),0 , -edges[3 * numEdges + i]);
130 | g -> add_tweights((GraphType::node_id)round(edges[numEdges + i] - 1), 0, edges[3 * numEdges + i]);
131 | }
132 | else
133 | mexWarnMsgIdAndTxt("graphCutMex:pairwisePotentials", "Something strange with an edge and therefore it is ignored");
134 | }
135 |
136 | //compute flow
137 | EnergyType flow = g -> maxflow();
138 |
139 | //output minimum value
140 | if (cOutPtr != NULL){
141 | *cOutPtr = mxCreateNumericMatrix(1, 1, MATLAB_ENERGY_TYPE, mxREAL);
142 | *(EnergyType*)mxGetData(*cOutPtr) = (EnergyType)flow;
143 | }
144 |
145 | //output minimum cut
146 | if (lOutPtr != NULL){
147 | *lOutPtr = mxCreateNumericMatrix(numNodes, 1, MATLAB_LABEL_TYPE, mxREAL);
148 | LabelType* segment = (LabelType*)mxGetData(*lOutPtr);
149 | for(int i = 0; i < numNodes; i++)
150 | segment[i] = g -> what_segment(i);
151 | }
152 |
153 | delete g;
154 | }
155 |
156 | double round(double a)
157 | {
158 | return floor(a + 0.5);
159 | }
160 |
161 |
162 | int isInteger(double a)
163 | {
164 | return (abs(a - round(a)) < 1e-6);
165 | }
166 |
--------------------------------------------------------------------------------
/graphCutMex.h:
--------------------------------------------------------------------------------
1 |
2 | #ifndef __GRAPHCUTMEX_H__
3 | #define __GRAPHCUTMEX_H__
4 |
5 | #include "graph.h"
6 | #include "graph.cpp"
7 | #include "maxflow.cpp"
8 |
9 | #endif
10 |
--------------------------------------------------------------------------------
/graphCutMex.m:
--------------------------------------------------------------------------------
1 | % graphCutMex - Matlab wrapper to the implementation of min-cut algorithm by Yuri Boykov and Vladimir Kolmogorov:
2 | % http://pub.ist.ac.at/~vnk/software/maxflow-v3.03.src.zip
3 | % This version can automatically perform reparametrization on all submodular edges.
4 | %
5 | % The algorithm is described in:
6 | % Yuri Boykov and Vladimir Kolmogorov, 'An Experimental Comparison of Min-Cut/Max-Flow Algorithms for
7 | % Energy Minimization in Vision', IEEE Transactions on Pattern Analysis and Machine Intelligence, vol.
8 | % 26, no. 9, pp. 1124-1137, Sept. 2004.
9 | %
10 | % Usage:
11 | % [cut] = graphCutMex(termWeights, edgeWeights);
12 | % [cut, labels] = graphCutMex(termWeights, edgeWeights);
13 | %
14 | % Inputs:
15 | % termWeights - the edges connecting the source and the sink with the regular nodes (array of type double, size : [numNodes, 2])
16 | % termWeights(i, 1) is the weight of the edge connecting the source with node #i
17 | % termWeights(i, 2) is the weight of the edge connecting node #i with the sink
18 | % numNodes is determined from the size of termWeights.
19 | % edgeWeights - the edges connecting regular nodes with each other (array of type double, array size [numEdges, 4])
20 | % edgeWeights(i, 3) connects node #edgeWeights(i, 1) to node #edgeWeights(i, 2)
21 | % edgeWeights(i, 4) connects node #edgeWeights(i, 2) to node #edgeWeights(i, 1)
22 | % The only requirement on edge weights is submodularity: edgeWeights(i, 3) + edgeWeights(i, 4) >= 0
23 | %
24 | % Outputs:
25 | % cut - the minimum cut value (type double)
26 | % labels - a vector of length numNodes, where labels(i) is 0 or 1 if node #i belongs to S (source) or T (sink) respectively.
27 | %
28 | % To build the code in Matlab choose reasonable compiler and run build_graphCutMex.m
29 | % Run example_graphCutMex.m to test the code
30 | %
31 | % Anton Osokin (firstname.lastname@gmail.com), 19.05.2013
32 |
--------------------------------------------------------------------------------
/graphCutMex.mexw64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/graphCutMex.mexw64
--------------------------------------------------------------------------------
/homographyAlign.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/homographyAlign.m
--------------------------------------------------------------------------------
/main.m:
--------------------------------------------------------------------------------
1 | clear; clc; close all;
2 | %% Setup VLFeat toolbox.
3 | %----------------------
4 | addpath('modelspecific');
5 | addpath('MBS'); % for saliency detection
6 | cd vlfeat-0.9.21/toolbox;
7 | feval('vl_setup');
8 | cd ../..;
9 |
10 | imgpath = 'Imgs\';
11 |
12 | img_format = '*.jpg';
13 | outpath = [imgpath, 'results\'];%testpatch
14 | dir_folder = dir(strcat(imgpath, img_format));
15 | if ~exist(outpath,'dir'); mkdir(outpath); end
16 |
17 | path1 = sprintf('%s%s',imgpath, dir_folder(1).name); %
18 | path2 = sprintf('%s%s',imgpath, dir_folder(2).name); %
19 | img1 = im2double(imread(path1)); % target image
20 | img2 = im2double(imread(path2)); % reference image
21 |
22 | %% saliency detection
23 |
24 | pMap_1 = mbs_saliency(img1);
25 | pMap_2 = mbs_saliency(img2);
26 |
27 | %% image alignment
28 | fprintf('> image alignment...');tic;
29 | [warped_img1, warped_pmap1, warped_img2, warped_pmap2] = registerTexture(img1, pMap_1, img2, pMap_2, imgpath);
30 | fprintf('done (%fs)\n', toc);
31 |
32 | %% image composition
33 | fprintf('> seam cutting...');tic;
34 | imgout = blendTexture(warped_img1, warped_pmap1, warped_img2, warped_pmap2);
35 | fprintf('done (%fs)\n', toc);
36 |
--------------------------------------------------------------------------------
/matchDelete.m:
--------------------------------------------------------------------------------
1 | function [matches1, matches2] = matchDelete(pts1, pts2, height, width)
2 |
3 | %% delete the wrong matches (one-to-more)
4 | [~, ind_1] = unique(pts1', 'rows');
5 | pts1 = pts1(:,ind_1');
6 | pts2 = pts2(:,ind_1');
7 | [~, ind_2] = unique(pts2', 'rows');
8 | pts1 = pts1(:,ind_2');
9 | pts2 = pts2(:,ind_2');
10 |
11 | %% use histogram (horizontal and vertical orientation) delete outliers
12 | thr = 0.1;
13 | % horizontal histogram
14 | xbins = (-width+width*thr/2:width*thr:width-width*thr/2);
15 | counts1 = hist(pts1(1,:)-pts2(1,:), xbins);
16 | [~,ia1] = max(counts1);
17 | C1 = find(pts1(1,:)-pts2(1,:)>=max(-width,-width+(ia1-2)*width*thr) & pts1(1,:)-pts2(1,:)<=min(width,-width+(ia1+1)*width*thr));
18 | % vertical histogram
19 | ybins = (-height+height*thr/2: height*thr: height-height*thr/2);
20 | counts2 = hist(pts1(2,:)-pts2(2,:), ybins);
21 | [~, ia2] = max(counts2);
22 | C2 = find(pts1(2,:)-pts2(2,:)>=max(-height,-height+(ia2-2)*height*thr) & pts1(2,:)-pts2(2,:)<=min(height, -height+(ia2+1)*height*thr));
23 | % final inliers after 1st filter
24 | C = intersect(C1,C2);
25 | pts1 = pts1(:,C);
26 | pts2 = pts2(:,C);
27 |
28 | %% RANSAC delete
29 | coef.minPtNum = 4; %max(min(round(size(pts1,2)/4),10),4);
30 | coef.iterNum = 1000;
31 | coef.thDist = 5;
32 | coef.thInlrRatio = .1;
33 |
34 | [~,corrPtIdx1] = ransacx(pts2, pts1, coef); %, @DLT_Homo,@calcDist);
35 | matches1 = pts1(:, corrPtIdx1);
36 | matches2 = pts2(:, corrPtIdx1);
37 |
38 | end
--------------------------------------------------------------------------------
/maxflow-v3.03.src/CHANGES.TXT:
--------------------------------------------------------------------------------
1 | List of changes from version 3.02:
2 |
3 | - put under GPL license
4 |
5 | List of changes from version 3.01:
6 |
7 | - fixed a bug: using add_node() or add_edge() after the first maxflow() with the reuse_trees option
8 | could have caused segmentation fault (if nodes or arcs are reallocated). Thanks to Jan Lellmann for pointing out this bug.
9 | - updated block.h to suppress compilation warnings
10 |
11 | List of changes from version 3.0:
12 | - Moved line
13 | #include "instances.inc"
14 | to the end of cpp files to make it compile under GNU c++ compilers 4.2(?) and above
15 |
16 | List of changes from version 2.2:
17 |
18 | - Added functions for accessing graph structure, residual capacities, etc.
19 | (They are needed for implementing maxflow-based algorithms such as primal-dual algorithm for convex MRFs.)
20 | - Added option of reusing trees.
21 | - node_id's are now integers starting from 0. Thus, it is not necessary to store node_id's in a separate array.
22 | - Capacity types are now templated.
23 | - Fixed bug in block.h. (After Block::Reset, ScanFirst() and ScanNext() did not work properly).
24 | - 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.
25 | - Note: version 3.0 is released under a different license than version 2.2.
26 |
27 | List of changes from version 2.1:
28 |
29 | - Put the code under GPL license
30 |
31 | List of changes from version 2.02:
32 |
33 | - Fixed a bug in the implementation that uses forward star representation
34 |
35 | List of changes from version 2.01:
36 |
37 | - Added new interface function - Graph::add_tweights(Node_id, captype, captype)
38 | (necessary for the "ENERGY" software package)
39 |
40 |
--------------------------------------------------------------------------------
/maxflow-v3.03.src/GPL.TXT:
--------------------------------------------------------------------------------
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 |
635 | Copyright (C)
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 | Copyright (C)
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 |
--------------------------------------------------------------------------------
/maxflow-v3.03.src/README.TXT:
--------------------------------------------------------------------------------
1 | ###################################################################
2 | # #
3 | # MAXFLOW - software for computing mincut/maxflow in a graph #
4 | # Version 3.03 #
5 | # http://http://pub.ist.ac.at/~vnk/software.html #
6 | # #
7 | # Yuri Boykov (yuri@csd.uwo.ca) #
8 | # Vladimir Kolmogorov (vnk@ist.ac.at) #
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 (vnk@ist.ac.at), Yuri Boykov (yuri@csd.uwo.ca).
51 |
52 | This software is under the GPL license.
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 |
--------------------------------------------------------------------------------
/maxflow-v3.03.src/block.h:
--------------------------------------------------------------------------------
1 | /* block.h */
2 | /* Vladimir Kolmogorov vnk@ist.ac.at */
3 | /* Last modified 08/05/2012 */
4 | /*
5 | Template classes Block and DBlock
6 | Implement adding and deleting items of the same type in blocks.
7 |
8 | If there there are many items then using Block or DBlock
9 | is more efficient than using 'new' and 'delete' both in terms
10 | of memory and time since
11 | (1) On some systems there is some minimum amount of memory
12 | that 'new' can allocate (e.g., 64), so if items are
13 | small that a lot of memory is wasted.
14 | (2) 'new' and 'delete' are designed for items of varying size.
15 | If all items has the same size, then an algorithm for
16 | adding and deleting can be made more efficient.
17 | (3) All Block and DBlock functions are inline, so there are
18 | no extra function calls.
19 |
20 | Differences between Block and DBlock:
21 | (1) DBlock allows both adding and deleting items,
22 | whereas Block allows only adding items.
23 | (2) Block has an additional operation of scanning
24 | items added so far (in the order in which they were added).
25 | (3) Block allows to allocate several consecutive
26 | items at a time, whereas DBlock can add only a single item.
27 |
28 | Note that no constructors or destructors are called for items.
29 |
30 | Example usage for items of type 'MyType':
31 |
32 | ///////////////////////////////////////////////////
33 | #include "block.h"
34 | #define BLOCK_SIZE 1024
35 | typedef struct { int a, b; } MyType;
36 | MyType *ptr, *array[10000];
37 |
38 | ...
39 |
40 | Block *block = new Block(BLOCK_SIZE);
41 |
42 | // adding items
43 | for (int i=0; i New();
46 | ptr -> a = ptr -> b = rand();
47 | }
48 |
49 | // reading items
50 | for (ptr=block->ScanFirst(); ptr; ptr=block->ScanNext())
51 | {
52 | printf("%d %d\n", ptr->a, ptr->b);
53 | }
54 |
55 | delete block;
56 |
57 | ...
58 |
59 | DBlock *dblock = new DBlock(BLOCK_SIZE);
60 |
61 | // adding items
62 | for (int i=0; i New();
65 | }
66 |
67 | // deleting items
68 | for (int i=0; i Delete(array[i]);
71 | }
72 |
73 | // adding items
74 | for (int i=0; i New();
77 | }
78 |
79 | delete dblock;
80 |
81 | ///////////////////////////////////////////////////
82 |
83 | Note that DBlock deletes items by marking them as
84 | empty (i.e., by adding them to the list of free items),
85 | so that this memory could be used for subsequently
86 | added items. Thus, at each moment the memory allocated
87 | is determined by the maximum number of items allocated
88 | simultaneously at earlier moments. All memory is
89 | deallocated only when the destructor is called.
90 | */
91 |
92 | #ifndef __BLOCK_H__
93 | #define __BLOCK_H__
94 |
95 | #include
96 |
97 | /***********************************************************************/
98 | /***********************************************************************/
99 | /***********************************************************************/
100 |
101 | template class Block
102 | {
103 | public:
104 | /* Constructor. Arguments are the block size and
105 | (optionally) the pointer to the function which
106 | will be called if allocation failed; the message
107 | passed to this function is "Not enough memory!" */
108 | Block(int size, void (*err_function)(const char *) = NULL) { first = last = NULL; block_size = size; error_function = err_function; }
109 |
110 | /* Destructor. Deallocates all items added so far */
111 | ~Block() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } }
112 |
113 | /* Allocates 'num' consecutive items; returns pointer
114 | to the first item. 'num' cannot be greater than the
115 | block size since items must fit in one block */
116 | Type *New(int num = 1)
117 | {
118 | Type *t;
119 |
120 | if (!last || last->current + num > last->last)
121 | {
122 | if (last && last->next) last = last -> next;
123 | else
124 | {
125 | block *next = (block *) new char [sizeof(block) + (block_size-1)*sizeof(Type)];
126 | if (!next) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
127 | if (last) last -> next = next;
128 | else first = next;
129 | last = next;
130 | last -> current = & ( last -> data[0] );
131 | last -> last = last -> current + block_size;
132 | last -> next = NULL;
133 | }
134 | }
135 |
136 | t = last -> current;
137 | last -> current += num;
138 | return t;
139 | }
140 |
141 | /* Returns the first item (or NULL, if no items were added) */
142 | Type *ScanFirst()
143 | {
144 | for (scan_current_block=first; scan_current_block; scan_current_block = scan_current_block->next)
145 | {
146 | scan_current_data = & ( scan_current_block -> data[0] );
147 | if (scan_current_data < scan_current_block -> current) return scan_current_data ++;
148 | }
149 | return NULL;
150 | }
151 |
152 | /* Returns the next item (or NULL, if all items have been read)
153 | Can be called only if previous ScanFirst() or ScanNext()
154 | call returned not NULL. */
155 | Type *ScanNext()
156 | {
157 | while (scan_current_data >= scan_current_block -> current)
158 | {
159 | scan_current_block = scan_current_block -> next;
160 | if (!scan_current_block) return NULL;
161 | scan_current_data = & ( scan_current_block -> data[0] );
162 | }
163 | return scan_current_data ++;
164 | }
165 |
166 | struct iterator; // for overlapping scans
167 | Type *ScanFirst(iterator& i)
168 | {
169 | for (i.scan_current_block=first; i.scan_current_block; i.scan_current_block = i.scan_current_block->next)
170 | {
171 | i.scan_current_data = & ( i.scan_current_block -> data[0] );
172 | if (i.scan_current_data < i.scan_current_block -> current) return i.scan_current_data ++;
173 | }
174 | return NULL;
175 | }
176 | Type *ScanNext(iterator& i)
177 | {
178 | while (i.scan_current_data >= i.scan_current_block -> current)
179 | {
180 | i.scan_current_block = i.scan_current_block -> next;
181 | if (!i.scan_current_block) return NULL;
182 | i.scan_current_data = & ( i.scan_current_block -> data[0] );
183 | }
184 | return i.scan_current_data ++;
185 | }
186 |
187 | /* Marks all elements as empty */
188 | void Reset()
189 | {
190 | block *b;
191 | if (!first) return;
192 | for (b=first; ; b=b->next)
193 | {
194 | b -> current = & ( b -> data[0] );
195 | if (b == last) break;
196 | }
197 | last = first;
198 | }
199 |
200 | /***********************************************************************/
201 |
202 | private:
203 |
204 | typedef struct block_st
205 | {
206 | Type *current, *last;
207 | struct block_st *next;
208 | Type data[1];
209 | } block;
210 |
211 | int block_size;
212 | block *first;
213 | block *last;
214 | public:
215 | struct iterator
216 | {
217 | block *scan_current_block;
218 | Type *scan_current_data;
219 | };
220 | private:
221 | block *scan_current_block;
222 | Type *scan_current_data;
223 |
224 | void (*error_function)(const char *);
225 | };
226 |
227 | /***********************************************************************/
228 | /***********************************************************************/
229 | /***********************************************************************/
230 |
231 | template class DBlock
232 | {
233 | public:
234 | /* Constructor. Arguments are the block size and
235 | (optionally) the pointer to the function which
236 | will be called if allocation failed; the message
237 | passed to this function is "Not enough memory!" */
238 | DBlock(int size, void (*err_function)(const char *) = NULL) { first = NULL; first_free = NULL; block_size = size; error_function = err_function; }
239 |
240 | /* Destructor. Deallocates all items added so far */
241 | ~DBlock() { while (first) { block *next = first -> next; delete[] ((char*)first); first = next; } }
242 |
243 | /* Allocates one item */
244 | Type *New()
245 | {
246 | block_item *item;
247 |
248 | if (!first_free)
249 | {
250 | block *next = first;
251 | first = (block *) new char [sizeof(block) + (block_size-1)*sizeof(block_item)];
252 | if (!first) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
253 | first_free = & (first -> data[0] );
254 | for (item=first_free; item next_free = item + 1;
256 | item -> next_free = NULL;
257 | first -> next = next;
258 | }
259 |
260 | item = first_free;
261 | first_free = item -> next_free;
262 | return (Type *) item;
263 | }
264 |
265 | /* Deletes an item allocated previously */
266 | void Delete(Type *t)
267 | {
268 | ((block_item *) t) -> next_free = first_free;
269 | first_free = (block_item *) t;
270 | }
271 |
272 | /***********************************************************************/
273 |
274 | private:
275 |
276 | typedef union block_item_st
277 | {
278 | Type t;
279 | block_item_st *next_free;
280 | } block_item;
281 |
282 | typedef struct block_st
283 | {
284 | struct block_st *next;
285 | block_item data[1];
286 | } block;
287 |
288 | int block_size;
289 | block *first;
290 | block_item *first_free;
291 |
292 | void (*error_function)(const char *);
293 | };
294 |
295 |
296 | #endif
297 |
298 |
--------------------------------------------------------------------------------
/maxflow-v3.03.src/graph.cpp:
--------------------------------------------------------------------------------
1 | /* graph.cpp */
2 |
3 | #ifndef __GRAPH_CPP__
4 | #define __GRAPH_CPP__
5 |
6 | #include
7 | #include
8 | #include
9 | #include "graph.h"
10 |
11 | /*
12 | special constants for node->parent. Duplicated in maxflow.cpp, both should match!
13 | */
14 | #define TERMINAL ( (arc *) 1 ) /* to terminal */
15 | #define ORPHAN ( (arc *) 2 ) /* orphan */
16 |
17 | template
18 | Graph::Graph(int node_num_max, int edge_num_max, void (*err_function)(const char *))
19 | : node_num(0),
20 | nodeptr_block(NULL),
21 | error_function(err_function)
22 | {
23 | if (node_num_max < 16) node_num_max = 16;
24 | if (edge_num_max < 16) edge_num_max = 16;
25 |
26 | nodes = (node*) malloc(node_num_max*sizeof(node));
27 | arcs = (arc*) malloc(2*edge_num_max*sizeof(arc));
28 | if (!nodes || !arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
29 |
30 | node_last = nodes;
31 | node_max = nodes + node_num_max;
32 | arc_last = arcs;
33 | arc_max = arcs + 2*edge_num_max;
34 |
35 | maxflow_iteration = 0;
36 | flow = 0;
37 | }
38 |
39 | template
40 | Graph::~Graph()
41 | {
42 | if (nodeptr_block)
43 | {
44 | delete nodeptr_block;
45 | nodeptr_block = NULL;
46 | }
47 | free(nodes);
48 | free(arcs);
49 | }
50 |
51 | template
52 | void Graph::reset()
53 | {
54 | node_last = nodes;
55 | arc_last = arcs;
56 | node_num = 0;
57 |
58 | if (nodeptr_block)
59 | {
60 | delete nodeptr_block;
61 | nodeptr_block = NULL;
62 | }
63 |
64 | maxflow_iteration = 0;
65 | flow = 0;
66 | }
67 |
68 | template
69 | void Graph::reallocate_nodes(int num)
70 | {
71 | int node_num_max = (int)(node_max - nodes);
72 | node* nodes_old = nodes;
73 |
74 | node_num_max += node_num_max / 2;
75 | if (node_num_max < node_num + num) node_num_max = node_num + num;
76 | nodes = (node*) realloc(nodes_old, node_num_max*sizeof(node));
77 | if (!nodes) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
78 |
79 | node_last = nodes + node_num;
80 | node_max = nodes + node_num_max;
81 |
82 | if (nodes != nodes_old)
83 | {
84 | node* i;
85 | arc* a;
86 | for (i=nodes; inext) i->next = (node*) ((char*)i->next + (((char*) nodes) - ((char*) nodes_old)));
89 | }
90 | for (a=arcs; ahead = (node*) ((char*)a->head + (((char*) nodes) - ((char*) nodes_old)));
93 | }
94 | }
95 | }
96 |
97 | template
98 | void Graph::reallocate_arcs()
99 | {
100 | int arc_num_max = (int)(arc_max - arcs);
101 | int arc_num = (int)(arc_last - arcs);
102 | arc* arcs_old = arcs;
103 |
104 | arc_num_max += arc_num_max / 2; if (arc_num_max & 1) arc_num_max ++;
105 | arcs = (arc*) realloc(arcs_old, arc_num_max*sizeof(arc));
106 | if (!arcs) { if (error_function) (*error_function)("Not enough memory!"); exit(1); }
107 |
108 | arc_last = arcs + arc_num;
109 | arc_max = arcs + arc_num_max;
110 |
111 | if (arcs != arcs_old)
112 | {
113 | node* i;
114 | arc* a;
115 | for (i=nodes; ifirst) i->first = (arc*) ((char*)i->first + (((char*) arcs) - ((char*) arcs_old)));
118 | if (i->parent && i->parent != ORPHAN && i->parent != TERMINAL) i->parent = (arc*) ((char*)i->parent + (((char*) arcs) - ((char*) arcs_old)));
119 | }
120 | for (a=arcs; anext) a->next = (arc*) ((char*)a->next + (((char*) arcs) - ((char*) arcs_old)));
123 | a->sister = (arc*) ((char*)a->sister + (((char*) arcs) - ((char*) arcs_old)));
124 | }
125 | }
126 | }
127 |
128 | #ifndef __INSTANCES_INC__
129 | #define __INSTANCES_INC__
130 |
131 | #include "instances.inc"
132 |
133 | #endif
134 |
135 | #endif
136 |
--------------------------------------------------------------------------------
/maxflow-v3.03.src/graph.h:
--------------------------------------------------------------------------------
1 | /* graph.h */
2 | /*
3 | Copyright Vladimir Kolmogorov (vnk@ist.ac.at), Yuri Boykov (yuri@csd.uwo.ca)
4 |
5 | This file is part of MAXFLOW.
6 |
7 | MAXFLOW is free software: you can redistribute it and/or modify
8 | it under the terms of the GNU General Public License as published by
9 | the Free Software Foundation, either version 3 of the License, or
10 | (at your option) any later version.
11 |
12 | MAXFLOW is distributed in the hope that it will be useful,
13 | but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | GNU General Public License for more details.
16 |
17 | You should have received a copy of the GNU General Public License
18 | along with MAXFLOW. If not, see .
19 |
20 | ========================
21 |
22 | version 3.03
23 |
24 | This software library implements the maxflow algorithm
25 | described in
26 |
27 | "An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision."
28 | Yuri Boykov and Vladimir Kolmogorov.
29 | In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI),
30 | September 2004
31 |
32 | This algorithm was developed by Yuri Boykov and Vladimir Kolmogorov
33 | at Siemens Corporate Research. To make it available for public use,
34 | it was later reimplemented by Vladimir Kolmogorov based on open publications.
35 |
36 | If you use this software for research purposes, you should cite
37 | the aforementioned paper in any resulting publication.
38 |
39 | ----------------------------------------------------------------------
40 |
41 | REUSING TREES:
42 |
43 | Starting with version 3.0, there is a also an option of reusing search
44 | trees from one maxflow computation to the next, as described in
45 |
46 | "Efficiently Solving Dynamic Markov Random Fields Using Graph Cuts."
47 | Pushmeet Kohli and Philip H.S. Torr
48 | International Conference on Computer Vision (ICCV), 2005
49 |
50 | If you use this option, you should cite
51 | the aforementioned paper in any resulting publication.
52 | */
53 |
54 |
55 |
56 | /*
57 | For description, license, example usage see README.TXT.
58 | */
59 |
60 | #ifndef __GRAPH_H__
61 | #define __GRAPH_H__
62 |
63 | #include
64 | #include "block.h"
65 |
66 | #include
67 | // NOTE: in UNIX you need to use -DNDEBUG preprocessor option to supress assert's!!!
68 |
69 |
70 |
71 | // captype: type of edge capacities (excluding t-links)
72 | // tcaptype: type of t-links (edges between nodes and terminals)
73 | // flowtype: type of total flow
74 | //
75 | // Current instantiations are in instances.inc
76 | template class Graph
77 | {
78 | public:
79 | typedef enum
80 | {
81 | SOURCE = 0,
82 | SINK = 1
83 | } termtype; // terminals
84 | typedef int node_id;
85 |
86 | /////////////////////////////////////////////////////////////////////////
87 | // BASIC INTERFACE FUNCTIONS //
88 | // (should be enough for most applications) //
89 | /////////////////////////////////////////////////////////////////////////
90 |
91 | // Constructor.
92 | // The first argument gives an estimate of the maximum number of nodes that can be added
93 | // to the graph, and the second argument is an estimate of the maximum number of edges.
94 | // The last (optional) argument is the pointer to the function which will be called
95 | // if an error occurs; an error message is passed to this function.
96 | // If this argument is omitted, exit(1) will be called.
97 | //
98 | // IMPORTANT: It is possible to add more nodes to the graph than node_num_max
99 | // (and node_num_max can be zero). However, if the count is exceeded, then
100 | // the internal memory is reallocated (increased by 50%) which is expensive.
101 | // Also, temporarily the amount of allocated memory would be more than twice than needed.
102 | // Similarly for edges.
103 | // If you wish to avoid this overhead, you can download version 2.2, where nodes and edges are stored in blocks.
104 | Graph(int node_num_max, int edge_num_max, void (*err_function)(const char *) = NULL);
105 |
106 | // Destructor
107 | ~Graph();
108 |
109 | // 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.
110 | // If num>1, then several nodes are added, and node_id of the first one is returned.
111 | // IMPORTANT: see note about the constructor
112 | node_id add_node(int num = 1);
113 |
114 | // Adds a bidirectional edge between 'i' and 'j' with the weights 'cap' and 'rev_cap'.
115 | // IMPORTANT: see note about the constructor
116 | void add_edge(node_id i, node_id j, captype cap, captype rev_cap);
117 |
118 | // Adds new edges 'SOURCE->i' and 'i->SINK' with corresponding weights.
119 | // Can be called multiple times for each node.
120 | // Weights can be negative.
121 | // NOTE: the number of such edges is not counted in edge_num_max.
122 | // No internal memory is allocated by this call.
123 | void add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink);
124 |
125 |
126 | // Computes the maxflow. Can be called several times.
127 | // FOR DESCRIPTION OF reuse_trees, SEE mark_node().
128 | // FOR DESCRIPTION OF changed_list, SEE remove_from_changed_list().
129 | flowtype maxflow(bool reuse_trees = false, Block* changed_list = NULL);
130 |
131 | // After the maxflow is computed, this function returns to which
132 | // segment the node 'i' belongs (Graph::SOURCE or Graph::SINK).
133 | //
134 | // Occasionally there may be several minimum cuts. If a node can be assigned
135 | // to both the source and the sink, then default_segm is returned.
136 | termtype what_segment(node_id i, termtype default_segm = SOURCE);
137 |
138 |
139 |
140 | //////////////////////////////////////////////
141 | // ADVANCED INTERFACE FUNCTIONS //
142 | // (provide access to the graph) //
143 | //////////////////////////////////////////////
144 |
145 | private:
146 | struct node;
147 | struct arc;
148 |
149 | public:
150 |
151 | ////////////////////////////
152 | // 1. Reallocating graph. //
153 | ////////////////////////////
154 |
155 | // Removes all nodes and edges.
156 | // After that functions add_node() and add_edge() must be called again.
157 | //
158 | // Advantage compared to deleting Graph and allocating it again:
159 | // no calls to delete/new (which could be quite slow).
160 | //
161 | // If the graph structure stays the same, then an alternative
162 | // is to go through all nodes/edges and set new residual capacities
163 | // (see functions below).
164 | void reset();
165 |
166 | ////////////////////////////////////////////////////////////////////////////////
167 | // 2. Functions for getting pointers to arcs and for reading graph structure. //
168 | // NOTE: adding new arcs may invalidate these pointers (if reallocation //
169 | // happens). So it's best not to add arcs while reading graph structure. //
170 | ////////////////////////////////////////////////////////////////////////////////
171 |
172 | // The following two functions return arcs in the same order that they
173 | // were added to the graph. NOTE: for each call add_edge(i,j,cap,cap_rev)
174 | // the first arc returned will be i->j, and the second j->i.
175 | // If there are no more arcs, then the function can still be called, but
176 | // the returned arc_id is undetermined.
177 | typedef arc* arc_id;
178 | arc_id get_first_arc();
179 | arc_id get_next_arc(arc_id a);
180 |
181 | // other functions for reading graph structure
182 | int get_node_num() { return node_num; }
183 | int get_arc_num() { return (int)(arc_last - arcs); }
184 | void get_arc_ends(arc_id a, node_id& i, node_id& j); // returns i,j to that a = i->j
185 |
186 | ///////////////////////////////////////////////////
187 | // 3. Functions for reading residual capacities. //
188 | ///////////////////////////////////////////////////
189 |
190 | // returns residual capacity of SOURCE->i minus residual capacity of i->SINK
191 | tcaptype get_trcap(node_id i);
192 | // returns residual capacity of arc a
193 | captype get_rcap(arc* a);
194 |
195 | /////////////////////////////////////////////////////////////////
196 | // 4. Functions for setting residual capacities. //
197 | // NOTE: If these functions are used, the value of the flow //
198 | // returned by maxflow() will not be valid! //
199 | /////////////////////////////////////////////////////////////////
200 |
201 | void set_trcap(node_id i, tcaptype trcap);
202 | void set_rcap(arc* a, captype rcap);
203 |
204 | ////////////////////////////////////////////////////////////////////
205 | // 5. Functions related to reusing trees & list of changed nodes. //
206 | ////////////////////////////////////////////////////////////////////
207 |
208 | // If flag reuse_trees is true while calling maxflow(), then search trees
209 | // are reused from previous maxflow computation.
210 | // In this case before calling maxflow() the user must
211 | // specify which parts of the graph have changed by calling mark_node():
212 | // add_tweights(i),set_trcap(i) => call mark_node(i)
213 | // add_edge(i,j),set_rcap(a) => call mark_node(i); mark_node(j)
214 | //
215 | // This option makes sense only if a small part of the graph is changed.
216 | // The initialization procedure goes only through marked nodes then.
217 | //
218 | // mark_node(i) can either be called before or after graph modification.
219 | // Can be called more than once per node, but calls after the first one
220 | // do not have any effect.
221 | //
222 | // NOTE:
223 | // - This option cannot be used in the first call to maxflow().
224 | // - It is not necessary to call mark_node() if the change is ``not essential'',
225 | // i.e. sign(trcap) is preserved for a node and zero/nonzero status is preserved for an arc.
226 | // - To check that you marked all necessary nodes, you can call maxflow(false) after calling maxflow(true).
227 | // If everything is correct, the two calls must return the same value of flow. (Useful for debugging).
228 | void mark_node(node_id i);
229 |
230 | // If changed_list is not NULL while calling maxflow(), then the algorithm
231 | // keeps a list of nodes which could potentially have changed their segmentation label.
232 | // Nodes which are not in the list are guaranteed to keep their old segmentation label (SOURCE or SINK).
233 | // Example usage:
234 | //
235 | // typedef Graph G;
236 | // G* g = new Graph(nodeNum, edgeNum);
237 | // Block* changed_list = new Block(128);
238 | //
239 | // ... // add nodes and edges
240 | //
241 | // g->maxflow(); // first call should be without arguments
242 | // for (int iter=0; iter<10; iter++)
243 | // {
244 | // ... // change graph, call mark_node() accordingly
245 | //
246 | // g->maxflow(true, changed_list);
247 | // G::node_id* ptr;
248 | // for (ptr=changed_list->ScanFirst(); ptr; ptr=changed_list->ScanNext())
249 | // {
250 | // G::node_id i = *ptr; assert(i>=0 && iremove_from_changed_list(i);
252 | // // do something with node i...
253 | // if (g->what_segment(i) == G::SOURCE) { ... }
254 | // }
255 | // changed_list->Reset();
256 | // }
257 | // delete changed_list;
258 | //
259 | // NOTE:
260 | // - If changed_list option is used, then reuse_trees must be used as well.
261 | // - In the example above, the user may omit calls g->remove_from_changed_list(i) and changed_list->Reset() in a given iteration.
262 | // Then during the next call to maxflow(true, &changed_list) new nodes will be added to changed_list.
263 | // - If the next call to maxflow() does not use option reuse_trees, then calling remove_from_changed_list()
264 | // is not necessary. ("changed_list->Reset()" or "delete changed_list" should still be called, though).
265 | void remove_from_changed_list(node_id i)
266 | {
267 | assert(i>=0 && i 0 then tr_cap is residual capacity of the arc SOURCE->node
297 | // otherwise -tr_cap is residual capacity of the arc node->SINK
298 |
299 | };
300 |
301 | struct arc
302 | {
303 | node *head; // node the arc points to
304 | arc *next; // next arc with the same originating node
305 | arc *sister; // reverse arc
306 |
307 | captype r_cap; // residual capacity
308 | };
309 |
310 | struct nodeptr
311 | {
312 | node *ptr;
313 | nodeptr *next;
314 | };
315 | static const int NODEPTR_BLOCK_SIZE = 128;
316 |
317 | node *nodes, *node_last, *node_max; // node_last = nodes+node_num, node_max = nodes+node_num_max;
318 | arc *arcs, *arc_last, *arc_max; // arc_last = arcs+2*edge_num, arc_max = arcs+2*edge_num_max;
319 |
320 | int node_num;
321 |
322 | DBlock *nodeptr_block;
323 |
324 | void (*error_function)(const char *); // this function is called if a error occurs,
325 | // with a corresponding error message
326 | // (or exit(1) is called if it's NULL)
327 |
328 | flowtype flow; // total flow
329 |
330 | // reusing trees & list of changed pixels
331 | int maxflow_iteration; // counter
332 | Block *changed_list;
333 |
334 | /////////////////////////////////////////////////////////////////////////
335 |
336 | node *queue_first[2], *queue_last[2]; // list of active nodes
337 | nodeptr *orphan_first, *orphan_last; // list of pointers to orphans
338 | int TIME; // monotonically increasing global counter
339 |
340 | /////////////////////////////////////////////////////////////////////////
341 |
342 | void reallocate_nodes(int num); // num is the number of new nodes
343 | void reallocate_arcs();
344 |
345 | // functions for processing active list
346 | void set_active(node *i);
347 | node *next_active();
348 |
349 | // functions for processing orphans list
350 | void set_orphan_front(node* i); // add to the beginning of the list
351 | void set_orphan_rear(node* i); // add to the end of the list
352 |
353 | void add_to_changed_list(node* i);
354 |
355 | void maxflow_init(); // called if reuse_trees == false
356 | void maxflow_reuse_trees_init(); // called if reuse_trees == true
357 | void augment(arc *middle_arc);
358 | void process_source_orphan(node *i);
359 | void process_sink_orphan(node *i);
360 |
361 | void test_consistency(node* current_node=NULL); // debug function
362 | };
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 | ///////////////////////////////////////
375 | // Implementation - inline functions //
376 | ///////////////////////////////////////
377 |
378 |
379 |
380 | template
381 | inline typename Graph::node_id Graph::add_node(int num)
382 | {
383 | assert(num > 0);
384 |
385 | if (node_last + num > node_max) reallocate_nodes(num);
386 |
387 | memset(node_last, 0, num*sizeof(node));
388 |
389 | node_id i = node_num;
390 | node_num += num;
391 | node_last += num;
392 | return i;
393 | }
394 |
395 | template
396 | inline void Graph::add_tweights(node_id i, tcaptype cap_source, tcaptype cap_sink)
397 | {
398 | assert(i >= 0 && i < node_num);
399 |
400 | tcaptype delta = nodes[i].tr_cap;
401 | if (delta > 0) cap_source += delta;
402 | else cap_sink -= delta;
403 | flow += (cap_source < cap_sink) ? cap_source : cap_sink;
404 | nodes[i].tr_cap = cap_source - cap_sink;
405 | }
406 |
407 | template
408 | inline void Graph::add_edge(node_id _i, node_id _j, captype cap, captype rev_cap)
409 | {
410 | assert(_i >= 0 && _i < node_num);
411 | assert(_j >= 0 && _j < node_num);
412 | assert(_i != _j);
413 | assert(cap >= 0);
414 | assert(rev_cap >= 0);
415 |
416 | if (arc_last == arc_max) reallocate_arcs();
417 |
418 | arc *a = arc_last ++;
419 | arc *a_rev = arc_last ++;
420 |
421 | node* i = nodes + _i;
422 | node* j = nodes + _j;
423 |
424 | a -> sister = a_rev;
425 | a_rev -> sister = a;
426 | a -> next = i -> first;
427 | i -> first = a;
428 | a_rev -> next = j -> first;
429 | j -> first = a_rev;
430 | a -> head = j;
431 | a_rev -> head = i;
432 | a -> r_cap = cap;
433 | a_rev -> r_cap = rev_cap;
434 | }
435 |
436 | template
437 | inline typename Graph::arc* Graph::get_first_arc()
438 | {
439 | return arcs;
440 | }
441 |
442 | template
443 | inline typename Graph::arc* Graph::get_next_arc(arc* a)
444 | {
445 | return a + 1;
446 | }
447 |
448 | template
449 | inline void Graph::get_arc_ends(arc* a, node_id& i, node_id& j)
450 | {
451 | assert(a >= arcs && a < arc_last);
452 | i = (node_id) (a->sister->head - nodes);
453 | j = (node_id) (a->head - nodes);
454 | }
455 |
456 | template
457 | inline tcaptype Graph::get_trcap(node_id i)
458 | {
459 | assert(i>=0 && i
464 | inline captype Graph::get_rcap(arc* a)
465 | {
466 | assert(a >= arcs && a < arc_last);
467 | return a->r_cap;
468 | }
469 |
470 | template
471 | inline void Graph::set_trcap(node_id i, tcaptype trcap)
472 | {
473 | assert(i>=0 && i
478 | inline void Graph::set_rcap(arc* a, captype rcap)
479 | {
480 | assert(a >= arcs && a < arc_last);
481 | a->r_cap = rcap;
482 | }
483 |
484 |
485 | template
486 | inline typename Graph::termtype Graph::what_segment(node_id i, termtype default_segm)
487 | {
488 | if (nodes[i].parent)
489 | {
490 | return (nodes[i].is_sink) ? SINK : SOURCE;
491 | }
492 | else
493 | {
494 | return default_segm;
495 | }
496 | }
497 |
498 | template
499 | inline void Graph::mark_node(node_id _i)
500 | {
501 | node* i = nodes + _i;
502 | if (!i->next)
503 | {
504 | /* it's not in the list yet */
505 | if (queue_last[1]) queue_last[1] -> next = i;
506 | else queue_first[1] = i;
507 | queue_last[1] = i;
508 | i -> next = i;
509 | }
510 | i->is_marked = 1;
511 | }
512 |
513 |
514 | #endif
515 |
--------------------------------------------------------------------------------
/maxflow-v3.03.src/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 |
--------------------------------------------------------------------------------
/maxflow-v3.03.src/maxflow.cpp:
--------------------------------------------------------------------------------
1 | /* maxflow.cpp */
2 |
3 | #ifndef __MAXFLOW_CPP__
4 | #define __MAXFLOW_CPP__
5 |
6 |
7 | #include
8 | #include "graph.h"
9 |
10 |
11 | /*
12 | special constants for node->parent. Duplicated in graph.cpp, both should match!
13 | */
14 | #define TERMINAL ( (arc *) 1 ) /* to terminal */
15 | #define ORPHAN ( (arc *) 2 ) /* orphan */
16 |
17 |
18 | #define INFINITE_D ((int)(((unsigned)-1)/2)) /* infinite distance to the terminal */
19 |
20 | /***********************************************************************/
21 |
22 | /*
23 | Functions for processing active list.
24 | i->next points to the next node in the list
25 | (or to i, if i is the last node in the list).
26 | If i->next is NULL iff i is not in the list.
27 |
28 | There are two queues. Active nodes are added
29 | to the end of the second queue and read from
30 | the front of the first queue. If the first queue
31 | is empty, it is replaced by the second queue
32 | (and the second queue becomes empty).
33 | */
34 |
35 |
36 | template
37 | inline void Graph::set_active(node *i)
38 | {
39 | if (!i->next)
40 | {
41 | /* it's not in the list yet */
42 | if (queue_last[1]) queue_last[1] -> next = i;
43 | else queue_first[1] = i;
44 | queue_last[1] = i;
45 | i -> next = i;
46 | }
47 | }
48 |
49 | /*
50 | Returns the next active node.
51 | If it is connected to the sink, it stays in the list,
52 | otherwise it is removed from the list
53 | */
54 | template
55 | inline typename Graph::node* Graph::next_active()
56 | {
57 | node *i;
58 |
59 | while ( 1 )
60 | {
61 | if (!(i=queue_first[0]))
62 | {
63 | queue_first[0] = i = queue_first[1];
64 | queue_last[0] = queue_last[1];
65 | queue_first[1] = NULL;
66 | queue_last[1] = NULL;
67 | if (!i) return NULL;
68 | }
69 |
70 | /* remove it from the active list */
71 | if (i->next == i) queue_first[0] = queue_last[0] = NULL;
72 | else queue_first[0] = i -> next;
73 | i -> next = NULL;
74 |
75 | /* a node in the list is active iff it has a parent */
76 | if (i->parent) return i;
77 | }
78 | }
79 |
80 | /***********************************************************************/
81 |
82 | template
83 | inline void Graph::set_orphan_front(node *i)
84 | {
85 | nodeptr *np;
86 | i -> parent = ORPHAN;
87 | np = nodeptr_block -> New();
88 | np -> ptr = i;
89 | np -> next = orphan_first;
90 | orphan_first = np;
91 | }
92 |
93 | template
94 | inline void Graph::set_orphan_rear(node *i)
95 | {
96 | nodeptr *np;
97 | i -> parent = ORPHAN;
98 | np = nodeptr_block -> New();
99 | np -> ptr = i;
100 | if (orphan_last) orphan_last -> next = np;
101 | else orphan_first = np;
102 | orphan_last = np;
103 | np -> next = NULL;
104 | }
105 |
106 | /***********************************************************************/
107 |
108 | template
109 | inline void Graph::add_to_changed_list(node *i)
110 | {
111 | if (changed_list && !i->is_in_changed_list)
112 | {
113 | node_id* ptr = changed_list->New();
114 | *ptr = (node_id)(i - nodes);
115 | i->is_in_changed_list = true;
116 | }
117 | }
118 |
119 | /***********************************************************************/
120 |
121 | template
122 | void Graph::maxflow_init()
123 | {
124 | node *i;
125 |
126 | queue_first[0] = queue_last[0] = NULL;
127 | queue_first[1] = queue_last[1] = NULL;
128 | orphan_first = NULL;
129 |
130 | TIME = 0;
131 |
132 | for (i=nodes; i next = NULL;
135 | i -> is_marked = 0;
136 | i -> is_in_changed_list = 0;
137 | i -> TS = TIME;
138 | if (i->tr_cap > 0)
139 | {
140 | /* i is connected to the source */
141 | i -> is_sink = 0;
142 | i -> parent = TERMINAL;
143 | set_active(i);
144 | i -> DIST = 1;
145 | }
146 | else if (i->tr_cap < 0)
147 | {
148 | /* i is connected to the sink */
149 | i -> is_sink = 1;
150 | i -> parent = TERMINAL;
151 | set_active(i);
152 | i -> DIST = 1;
153 | }
154 | else
155 | {
156 | i -> parent = NULL;
157 | }
158 | }
159 | }
160 |
161 | template
162 | void Graph::maxflow_reuse_trees_init()
163 | {
164 | node* i;
165 | node* j;
166 | node* queue = queue_first[1];
167 | arc* a;
168 | nodeptr* np;
169 |
170 | queue_first[0] = queue_last[0] = NULL;
171 | queue_first[1] = queue_last[1] = NULL;
172 | orphan_first = orphan_last = NULL;
173 |
174 | TIME ++;
175 |
176 | while ((i=queue))
177 | {
178 | queue = i->next;
179 | if (queue == i) queue = NULL;
180 | i->next = NULL;
181 | i->is_marked = 0;
182 | set_active(i);
183 |
184 | if (i->tr_cap == 0)
185 | {
186 | if (i->parent) set_orphan_rear(i);
187 | continue;
188 | }
189 |
190 | if (i->tr_cap > 0)
191 | {
192 | if (!i->parent || i->is_sink)
193 | {
194 | i->is_sink = 0;
195 | for (a=i->first; a; a=a->next)
196 | {
197 | j = a->head;
198 | if (!j->is_marked)
199 | {
200 | if (j->parent == a->sister) set_orphan_rear(j);
201 | if (j->parent && j->is_sink && a->r_cap > 0) set_active(j);
202 | }
203 | }
204 | add_to_changed_list(i);
205 | }
206 | }
207 | else
208 | {
209 | if (!i->parent || !i->is_sink)
210 | {
211 | i->is_sink = 1;
212 | for (a=i->first; a; a=a->next)
213 | {
214 | j = a->head;
215 | if (!j->is_marked)
216 | {
217 | if (j->parent == a->sister) set_orphan_rear(j);
218 | if (j->parent && !j->is_sink && a->sister->r_cap > 0) set_active(j);
219 | }
220 | }
221 | add_to_changed_list(i);
222 | }
223 | }
224 | i->parent = TERMINAL;
225 | i -> TS = TIME;
226 | i -> DIST = 1;
227 | }
228 |
229 | //test_consistency();
230 |
231 | /* adoption */
232 | while ((np=orphan_first))
233 | {
234 | orphan_first = np -> next;
235 | i = np -> ptr;
236 | nodeptr_block -> Delete(np);
237 | if (!orphan_first) orphan_last = NULL;
238 | if (i->is_sink) process_sink_orphan(i);
239 | else process_source_orphan(i);
240 | }
241 | /* adoption end */
242 |
243 | //test_consistency();
244 | }
245 |
246 | template
247 | void Graph::augment(arc *middle_arc)
248 | {
249 | node *i;
250 | arc *a;
251 | tcaptype bottleneck;
252 |
253 |
254 | /* 1. Finding bottleneck capacity */
255 | /* 1a - the source tree */
256 | bottleneck = middle_arc -> r_cap;
257 | for (i=middle_arc->sister->head; ; i=a->head)
258 | {
259 | a = i -> parent;
260 | if (a == TERMINAL) break;
261 | if (bottleneck > a->sister->r_cap) bottleneck = a -> sister -> r_cap;
262 | }
263 | if (bottleneck > i->tr_cap) bottleneck = i -> tr_cap;
264 | /* 1b - the sink tree */
265 | for (i=middle_arc->head; ; i=a->head)
266 | {
267 | a = i -> parent;
268 | if (a == TERMINAL) break;
269 | if (bottleneck > a->r_cap) bottleneck = a -> r_cap;
270 | }
271 | if (bottleneck > - i->tr_cap) bottleneck = - i -> tr_cap;
272 |
273 |
274 | /* 2. Augmenting */
275 | /* 2a - the source tree */
276 | middle_arc -> sister -> r_cap += bottleneck;
277 | middle_arc -> r_cap -= bottleneck;
278 | for (i=middle_arc->sister->head; ; i=a->head)
279 | {
280 | a = i -> parent;
281 | if (a == TERMINAL) break;
282 | a -> r_cap += bottleneck;
283 | a -> sister -> r_cap -= bottleneck;
284 | if (!a->sister->r_cap)
285 | {
286 | set_orphan_front(i); // add i to the beginning of the adoption list
287 | }
288 | }
289 | i -> tr_cap -= bottleneck;
290 | if (!i->tr_cap)
291 | {
292 | set_orphan_front(i); // add i to the beginning of the adoption list
293 | }
294 | /* 2b - the sink tree */
295 | for (i=middle_arc->head; ; i=a->head)
296 | {
297 | a = i -> parent;
298 | if (a == TERMINAL) break;
299 | a -> sister -> r_cap += bottleneck;
300 | a -> r_cap -= bottleneck;
301 | if (!a->r_cap)
302 | {
303 | set_orphan_front(i); // add i to the beginning of the adoption list
304 | }
305 | }
306 | i -> tr_cap += bottleneck;
307 | if (!i->tr_cap)
308 | {
309 | set_orphan_front(i); // add i to the beginning of the adoption list
310 | }
311 |
312 |
313 | flow += bottleneck;
314 | }
315 |
316 | /***********************************************************************/
317 |
318 | template
319 | void Graph::process_source_orphan(node *i)
320 | {
321 | node *j;
322 | arc *a0, *a0_min = NULL, *a;
323 | int d, d_min = INFINITE_D;
324 |
325 | /* trying to find a new parent */
326 | for (a0=i->first; a0; a0=a0->next)
327 | if (a0->sister->r_cap)
328 | {
329 | j = a0 -> head;
330 | if (!j->is_sink && (a=j->parent))
331 | {
332 | /* checking the origin of j */
333 | d = 0;
334 | while ( 1 )
335 | {
336 | if (j->TS == TIME)
337 | {
338 | d += j -> DIST;
339 | break;
340 | }
341 | a = j -> parent;
342 | d ++;
343 | if (a==TERMINAL)
344 | {
345 | j -> TS = TIME;
346 | j -> DIST = 1;
347 | break;
348 | }
349 | if (a==ORPHAN) { d = INFINITE_D; break; }
350 | j = a -> head;
351 | }
352 | if (dhead; j->TS!=TIME; j=j->parent->head)
361 | {
362 | j -> TS = TIME;
363 | j -> DIST = d --;
364 | }
365 | }
366 | }
367 | }
368 |
369 | if (i->parent = a0_min)
370 | {
371 | i -> TS = TIME;
372 | i -> DIST = d_min + 1;
373 | }
374 | else
375 | {
376 | /* no parent is found */
377 | add_to_changed_list(i);
378 |
379 | /* process neighbors */
380 | for (a0=i->first; a0; a0=a0->next)
381 | {
382 | j = a0 -> head;
383 | if (!j->is_sink && (a=j->parent))
384 | {
385 | if (a0->sister->r_cap) set_active(j);
386 | if (a!=TERMINAL && a!=ORPHAN && a->head==i)
387 | {
388 | set_orphan_rear(j); // add j to the end of the adoption list
389 | }
390 | }
391 | }
392 | }
393 | }
394 |
395 | template
396 | void Graph::process_sink_orphan(node *i)
397 | {
398 | node *j;
399 | arc *a0, *a0_min = NULL, *a;
400 | int d, d_min = INFINITE_D;
401 |
402 | /* trying to find a new parent */
403 | for (a0=i->first; a0; a0=a0->next)
404 | if (a0->r_cap)
405 | {
406 | j = a0 -> head;
407 | if (j->is_sink && (a=j->parent))
408 | {
409 | /* checking the origin of j */
410 | d = 0;
411 | while ( 1 )
412 | {
413 | if (j->TS == TIME)
414 | {
415 | d += j -> DIST;
416 | break;
417 | }
418 | a = j -> parent;
419 | d ++;
420 | if (a==TERMINAL)
421 | {
422 | j -> TS = TIME;
423 | j -> DIST = 1;
424 | break;
425 | }
426 | if (a==ORPHAN) { d = INFINITE_D; break; }
427 | j = a -> head;
428 | }
429 | if (dhead; j->TS!=TIME; j=j->parent->head)
438 | {
439 | j -> TS = TIME;
440 | j -> DIST = d --;
441 | }
442 | }
443 | }
444 | }
445 |
446 | if (i->parent = a0_min)
447 | {
448 | i -> TS = TIME;
449 | i -> DIST = d_min + 1;
450 | }
451 | else
452 | {
453 | /* no parent is found */
454 | add_to_changed_list(i);
455 |
456 | /* process neighbors */
457 | for (a0=i->first; a0; a0=a0->next)
458 | {
459 | j = a0 -> head;
460 | if (j->is_sink && (a=j->parent))
461 | {
462 | if (a0->r_cap) set_active(j);
463 | if (a!=TERMINAL && a!=ORPHAN && a->head==i)
464 | {
465 | set_orphan_rear(j); // add j to the end of the adoption list
466 | }
467 | }
468 | }
469 | }
470 | }
471 |
472 | /***********************************************************************/
473 |
474 | template
475 | flowtype Graph::maxflow(bool reuse_trees, Block* _changed_list)
476 | {
477 | node *i, *j, *current_node = NULL;
478 | arc *a;
479 | nodeptr *np, *np_next;
480 |
481 | if (!nodeptr_block)
482 | {
483 | nodeptr_block = new DBlock(NODEPTR_BLOCK_SIZE, error_function);
484 | }
485 |
486 | changed_list = _changed_list;
487 | if (maxflow_iteration == 0 && reuse_trees) { if (error_function) (*error_function)("reuse_trees cannot be used in the first call to maxflow()!"); exit(1); }
488 | if (changed_list && !reuse_trees) { if (error_function) (*error_function)("changed_list cannot be used without reuse_trees!"); exit(1); }
489 |
490 | if (reuse_trees) maxflow_reuse_trees_init();
491 | else maxflow_init();
492 |
493 | // main loop
494 | while ( 1 )
495 | {
496 | // test_consistency(current_node);
497 |
498 | if ((i=current_node))
499 | {
500 | i -> next = NULL; /* remove active flag */
501 | if (!i->parent) i = NULL;
502 | }
503 | if (!i)
504 | {
505 | if (!(i = next_active())) break;
506 | }
507 |
508 | /* growth */
509 | if (!i->is_sink)
510 | {
511 | /* grow source tree */
512 | for (a=i->first; a; a=a->next)
513 | if (a->r_cap)
514 | {
515 | j = a -> head;
516 | if (!j->parent)
517 | {
518 | j -> is_sink = 0;
519 | j -> parent = a -> sister;
520 | j -> TS = i -> TS;
521 | j -> DIST = i -> DIST + 1;
522 | set_active(j);
523 | add_to_changed_list(j);
524 | }
525 | else if (j->is_sink) break;
526 | else if (j->TS <= i->TS &&
527 | j->DIST > i->DIST)
528 | {
529 | /* heuristic - trying to make the distance from j to the source shorter */
530 | j -> parent = a -> sister;
531 | j -> TS = i -> TS;
532 | j -> DIST = i -> DIST + 1;
533 | }
534 | }
535 | }
536 | else
537 | {
538 | /* grow sink tree */
539 | for (a=i->first; a; a=a->next)
540 | if (a->sister->r_cap)
541 | {
542 | j = a -> head;
543 | if (!j->parent)
544 | {
545 | j -> is_sink = 1;
546 | j -> parent = a -> sister;
547 | j -> TS = i -> TS;
548 | j -> DIST = i -> DIST + 1;
549 | set_active(j);
550 | add_to_changed_list(j);
551 | }
552 | else if (!j->is_sink) { a = a -> sister; break; }
553 | else if (j->TS <= i->TS &&
554 | j->DIST > i->DIST)
555 | {
556 | /* heuristic - trying to make the distance from j to the sink shorter */
557 | j -> parent = a -> sister;
558 | j -> TS = i -> TS;
559 | j -> DIST = i -> DIST + 1;
560 | }
561 | }
562 | }
563 |
564 | TIME ++;
565 |
566 | if (a)
567 | {
568 | i -> next = i; /* set active flag */
569 | current_node = i;
570 |
571 | /* augmentation */
572 | augment(a);
573 | /* augmentation end */
574 |
575 | /* adoption */
576 | while ((np=orphan_first))
577 | {
578 | np_next = np -> next;
579 | np -> next = NULL;
580 |
581 | while ((np=orphan_first))
582 | {
583 | orphan_first = np -> next;
584 | i = np -> ptr;
585 | nodeptr_block -> Delete(np);
586 | if (!orphan_first) orphan_last = NULL;
587 | if (i->is_sink) process_sink_orphan(i);
588 | else process_source_orphan(i);
589 | }
590 |
591 | orphan_first = np_next;
592 | }
593 | /* adoption end */
594 | }
595 | else current_node = NULL;
596 | }
597 | // test_consistency();
598 |
599 | if (!reuse_trees || (maxflow_iteration % 64) == 0)
600 | {
601 | delete nodeptr_block;
602 | nodeptr_block = NULL;
603 | }
604 |
605 | maxflow_iteration ++;
606 | return flow;
607 | }
608 |
609 | /***********************************************************************/
610 |
611 |
612 | template
613 | void Graph::test_consistency(node* current_node)
614 | {
615 | node *i;
616 | arc *a;
617 | int r;
618 | int num1 = 0, num2 = 0;
619 |
620 | // test whether all nodes i with i->next!=NULL are indeed in the queue
621 | for (i=nodes; inext || i==current_node) num1 ++;
624 | }
625 | for (r=0; r<3; r++)
626 | {
627 | i = (r == 2) ? current_node : queue_first[r];
628 | if (i)
629 | for ( ; ; i=i->next)
630 | {
631 | num2 ++;
632 | if (i->next == i)
633 | {
634 | if (r<2) assert(i == queue_last[r]);
635 | else assert(i == current_node);
636 | break;
637 | }
638 | }
639 | }
640 | assert(num1 == num2);
641 |
642 | for (i=nodes; iparent == NULL) {}
646 | else if (i->parent == ORPHAN) {}
647 | else if (i->parent == TERMINAL)
648 | {
649 | if (!i->is_sink) assert(i->tr_cap > 0);
650 | else assert(i->tr_cap < 0);
651 | }
652 | else
653 | {
654 | if (!i->is_sink) assert (i->parent->sister->r_cap > 0);
655 | else assert (i->parent->r_cap > 0);
656 | }
657 | // test whether passive nodes in search trees have neighbors in
658 | // a different tree through non-saturated edges
659 | if (i->parent && !i->next)
660 | {
661 | if (!i->is_sink)
662 | {
663 | assert(i->tr_cap >= 0);
664 | for (a=i->first; a; a=a->next)
665 | {
666 | if (a->r_cap > 0) assert(a->head->parent && !a->head->is_sink);
667 | }
668 | }
669 | else
670 | {
671 | assert(i->tr_cap <= 0);
672 | for (a=i->first; a; a=a->next)
673 | {
674 | if (a->sister->r_cap > 0) assert(a->head->parent && a->head->is_sink);
675 | }
676 | }
677 | }
678 | // test marking invariants
679 | if (i->parent && i->parent!=ORPHAN && i->parent!=TERMINAL)
680 | {
681 | assert(i->TS <= i->parent->head->TS);
682 | if (i->TS == i->parent->head->TS) assert(i->DIST > i->parent->head->DIST);
683 | }
684 | }
685 | }
686 |
687 | #ifndef __INSTANCES_INC__
688 | #define __INSTANCES_INC__
689 |
690 | #include "instances.inc"
691 |
692 | #endif
693 |
694 | #endif
695 |
696 |
--------------------------------------------------------------------------------
/mbs_saliency.m:
--------------------------------------------------------------------------------
1 | function [pMap] = mbs_saliency(img)
2 |
3 | % This is a matlab implementation of the method described in:
4 | %
5 | % "Minimum Barrier Salient Object Detection at 80 FPS", Jianming Zhang,
6 | % Stan Sclaroff, Zhe Lin, Xiaohui Shen, Brian Price, Radomir Mech, ICCV, 2015
7 | %
8 | % Contact: jimmie33@gmail.com
9 | %
10 | % Prerequisite: OpenCV 2.4+
11 | %
12 | % Usage:
13 | %
14 | % 1. Go to the folder "mex"
15 | % 2. modify the opencv include and lib paths in "compile.m/compile_win.m"
16 | % (for Linux/Windows)
17 | % 3. run "compile/compile_win" in matlab (for Linux/Windows)
18 | % 4. Go to the root folder
19 | % 5. run "demo"
20 | %
21 | %
22 | % This matlab implementation is provided for research purpose only. For fully
23 | % reproducing the results in our ICCV paper, please use the original Windows
24 | % executable program.
25 | %
26 | % The matlab implementation is slower than the window executable, mainly due
27 | % to the morphological post-processing step. We use the highly optimized IPP
28 | % library for the morphological operations in our C++ implementation, which
29 | % are much faster than the corresponding Matlab functions.
30 |
31 | % MB+
32 | paramMBplus = getParam();
33 | paramMBplus.verbose = true; % to show run time for each step
34 |
35 | % Geodesic
36 | % paramGeo = getParam();
37 | % paramGeo.use_backgroundness = false;
38 | % paramGeo.use_geodesic = true;
39 |
40 | I = img;
41 |
42 | % paramMBD.use_backgroudness = true;
43 | % [pMap1, dMap1] = doMBS(I, paramMB);
44 | % [pMapG, dMapG] = doMBS(I, paramGeo);
45 | pMap = doMBS(I, paramMBplus);
46 |
47 |
48 | end
--------------------------------------------------------------------------------
/modelspecific/hnormalise.m:
--------------------------------------------------------------------------------
1 | % HNORMALISE - Normalises array of homogeneous coordinates to a scale of 1
2 | %
3 | % Usage: nx = hnormalise(x)
4 | %
5 | % Argument:
6 | % x - an Nxnpts array of homogeneous coordinates.
7 | %
8 | % Returns:
9 | % nx - an Nxnpts array of homogeneous coordinates rescaled so
10 | % that the scale values nx(N,:) are all 1.
11 | %
12 | % Note that any homogeneous coordinates at infinity (having a scale value of
13 | % 0) are left unchanged.
14 |
15 | % Peter Kovesi
16 | % School of Computer Science & Software Engineering
17 | % The University of Western Australia
18 | % pk at csse uwa edu au
19 | % http://www.csse.uwa.edu.au/~pk
20 | %
21 | % February 2004
22 |
23 | function nx = hnormalise(x)
24 |
25 | [rows,npts] = size(x);
26 | nx = x;
27 |
28 | % Find the indices of the points that are not at infinity
29 | finiteind = find(abs(x(rows,:)) > eps);
30 |
31 | if length(finiteind) ~= npts
32 | warning('Some points are at infinity');
33 | end
34 |
35 | % Normalise points not at infinity
36 | for r = 1:rows-1
37 | nx(r,finiteind) = x(r,finiteind)./x(rows,finiteind);
38 | end
39 | nx(rows,finiteind) = 1;
40 |
41 |
--------------------------------------------------------------------------------
/modelspecific/homography_degen.m:
--------------------------------------------------------------------------------
1 | function r = homography_degen(X)
2 |
3 | x1 = X(1:3,:); % Extract x1 and x2 from x
4 | x2 = X(4:6,:);
5 |
6 | r = ...
7 | iscolinear(x1(:,1),x1(:,2),x1(:,3)) | ...
8 | iscolinear(x1(:,1),x1(:,2),x1(:,4)) | ...
9 | iscolinear(x1(:,1),x1(:,3),x1(:,4)) | ...
10 | iscolinear(x1(:,2),x1(:,3),x1(:,4)) | ...
11 | iscolinear(x2(:,1),x2(:,2),x2(:,3)) | ...
12 | iscolinear(x2(:,1),x2(:,2),x2(:,4)) | ...
13 | iscolinear(x2(:,1),x2(:,3),x2(:,4)) | ...
14 | iscolinear(x2(:,2),x2(:,3),x2(:,4));
15 |
16 | end
17 |
18 |
19 | % function r = homography_degen(X)
20 | %
21 | % r = any(pdist(X(1:2,:)') < eps);
22 | %
23 | % r = r + any(pdist(X(3:4,:)') < eps);
24 | %
25 | % end
26 |
--------------------------------------------------------------------------------
/modelspecific/homography_fit.m:
--------------------------------------------------------------------------------
1 | function [P A C1 C2] = homography_fit(X,A,W,C1,C2)
2 |
3 | x1 = X(1:3,:);
4 | x2 = X(4:6,:);
5 |
6 | if nargin == 5
7 | H = vgg_H_from_x_lin(x1,x2,A,W,C1,C2);
8 | else
9 | [H A C1 C2] = vgg_H_from_x_lin(x1,x2);
10 | end
11 |
12 | % % Denormalise
13 | % H = T2\H*T1;
14 |
15 | P = H(:);
16 |
17 |
18 | % % Note that it may have not been possible to normalise
19 | % % the points if one was at infinity so the following does not
20 | % % assume that scale parameter w = 1.
21 | %
22 | % Npts = length(x1);
23 | % A = zeros(3*Npts,9);
24 | %
25 | % O = [0 0 0];
26 | % for n = 1:Npts
27 | % X = x1(:,n)';
28 | % x = x2(1,n); y = x2(2,n); w = x2(3,n);
29 | % A(3*n-2,:) = [ O -w*X y*X];
30 | % A(3*n-1,:) = [ w*X O -x*X];
31 | % A(3*n ,:) = [-y*X x*X O ];
32 | % end
33 | %
34 | % [U,D,V] = svd(A,0); % 'Economy' decomposition for speed
35 | %
36 | % % Extract homography
37 | % % H = reshape(V(:,9),3,3)';
38 | % P = V(:,9);
39 |
40 | end
41 |
42 |
43 | % function P = homography_fit(X)
44 | % % Homography fitting function using Direct Linear Transformation (DLT) (see Hartley and Zisserman).
45 | % % X is a 5 by 4 matrix.
46 | % % X(1,i) is the x coordinate in the 1st image of the i-th correspondence.
47 | % % X(2,i) is the y coordinate in the 1st image of the i-th correspondence.
48 | % % X(3,i) is the x coordinate in the 2nd image of the i-th correspondence.
49 | % % X(4,i) is the y coordinate in the 2nd image of the i-th correspondence.
50 | % % X(5,i) is max(width_of_image,height_of_image) (for increasing stability via normalisation).
51 | % % P is the resulting homography relation (a matrix) reshaped to a vector.
52 | %
53 | % A = zeros(8,9);
54 | %
55 | % for i=1:4
56 | % x1 = X(1,i)/X(5,i);
57 | % y1 = X(2,i)/X(5,i);
58 | % x2 = X(3,i)/X(5,i);
59 | % y2 = X(4,i)/X(5,i);
60 | % A((i-1)*2+1,:) = [ 0 0 0 -x2 -y2 -1 y1*x2 y1*y2 y1 ];
61 | % A((i-1)*2+2,:) = [ x2 y2 1 0 0 0 -x1*x2 -x1*y2 -x1 ];
62 | % end
63 | %
64 | % [ u s v ] = svd(A);
65 | %
66 | % H = reshape(v(:,end),3,3)';
67 | %
68 | % N = [ 1/X(5,1) 0 0 ; 0 1/X(5,1) 0 ; 0 0 1 ];
69 | %
70 | % H = N\(H*N); % Equivalent to H = inv(N)*H*N;
71 | %
72 | % P = reshape(H',9,1);
73 | %
74 | % end
75 |
--------------------------------------------------------------------------------
/modelspecific/homography_res.m:
--------------------------------------------------------------------------------
1 | function [dist, H] = homography_res(H, X)
2 |
3 | H = reshape(H,3,3);
4 |
5 |
6 | x1 = X(1:3,:); % Extract x1 and x2 from x
7 | x2 = X(4:6,:);
8 | n = size(x1,2);
9 |
10 | % Calculate, in both directions, the transfered points
11 | Hx1 = H*x1;
12 | invHx2 = H\x2;
13 |
14 | % Normalise so that the homogeneous scale parameter for all coordinates
15 | % is 1.
16 |
17 | x1 = hnormalise(x1);
18 | x2 = hnormalise(x2);
19 | Hx1 = hnormalise(Hx1);
20 | invHx2 = hnormalise(invHx2);
21 |
22 | dist = sum((x1-invHx2).^2) + sum((x2-Hx1).^2);
23 |
24 | dist = reshape(dist,n,1);
25 |
26 | H = H(:);
27 |
28 | end
29 |
30 |
31 |
32 | % function [dist, P] = homography_res(P, X)
33 | % % Function to calculate distances between a homography and a set of point
34 | % % correspondences. Implmenents the symmetric transfer error. See
35 | % % [Harley and Zisserman 2nd ed., pg 94].
36 | % % X is a 4 by npts matrix.
37 | % % X(1,i) is the x coordinate in the 1st image of the i-th correspondence.
38 | % % X(2,i) is the y coordinate in the 1st image of the i-th correspondence.
39 | % % X(3,i) is the x coordinate in the 2nd image of the i-th correspondence.
40 | % % X(4,i) is the y coordinate in the 2nd image of the i-th correspondence.
41 | %
42 | % [dummy npts] = size(X);
43 | % dist = zeros(npts,1);
44 | %
45 | % % Forward.
46 | % H = reshape(P,3,3)';
47 | % hom = H*[ X(3:4,:) ; ones(1,size(X,2)) ];
48 | % inhom = [ hom(1,:)./hom(3,:) ; hom(2,:)./hom(3,:) ];
49 | % for i=1:npts
50 | % dist(i) = norm(X(1:2,i) - inhom(:,i))^2;
51 | % end
52 | %
53 | % % Reverse.
54 | % % invH = inv(H);
55 | % % hom = invH*[ X(1:2,:) ; ones(1,size(X,2)) ];
56 | %
57 | % hom = H\[ X(1:2,:) ; ones(1,size(X,2)) ];
58 | %
59 | % inhom = [ hom(1,:)./hom(3,:) ; hom(2,:)./hom(3,:) ];
60 | % for i=1:npts
61 | % dist(i) = dist(i) + norm(X(3:4,i) - inhom(:,i))^2;
62 | % end
63 | %
64 | % end
65 |
--------------------------------------------------------------------------------
/modelspecific/iscolinear.m:
--------------------------------------------------------------------------------
1 | % ISCOLINEAR - are 3 points colinear
2 | %
3 | % Usage: r = iscolinear(p1, p2, p3, flag)
4 | %
5 | % Arguments:
6 | % p1, p2, p3 - Points in 2D or 3D.
7 | % flag - An optional parameter set to 'h' or 'homog'
8 | % indicating that p1, p2, p3 are homogneeous
9 | % coordinates with arbitrary scale. If this is
10 | % omitted it is assumed that the points are
11 | % inhomogeneous, or that they are homogeneous with
12 | % equal scale.
13 | %
14 | % Returns:
15 | % r = 1 if points are co-linear, 0 otherwise
16 |
17 | % Copyright (c) 2004-2005 Peter Kovesi
18 | % School of Computer Science & Software Engineering
19 | % The University of Western Australia
20 | % http://www.csse.uwa.edu.au/
21 | %
22 | % Permission is hereby granted, free of charge, to any person obtaining a copy
23 | % of this software and associated documentation files (the "Software"), to deal
24 | % in the Software without restriction, subject to the following conditions:
25 | %
26 | % The above copyright notice and this permission notice shall be included in
27 | % all copies or substantial portions of the Software.
28 | %
29 | % The Software is provided "as is", without warranty of any kind.
30 |
31 | % February 2004
32 | % January 2005 - modified to allow for homogeneous points of arbitrary
33 | % scale (thanks to Michael Kirchhof)
34 |
35 |
36 | function r = iscolinear(p1, p2, p3, flag)
37 |
38 | if nargin == 3 % Assume inhomogeneous coords
39 | flag = 'inhomog';
40 | end
41 |
42 | if ~all(size(p1)==size(p2)) | ~all(size(p1)==size(p3)) | ...
43 | ~(length(p1)==2 | length(p1)==3)
44 | error('points must have the same dimension of 2 or 3');
45 | end
46 |
47 | % If data is 2D, assume they are 2D inhomogeneous coords. Make them
48 | % homogeneous with scale 1.
49 | if length(p1) == 2
50 | p1(3) = 1; p2(3) = 1; p3(3) = 1;
51 | end
52 |
53 | if flag(1) == 'h'
54 | % Apply test that allows for homogeneous coords with arbitrary
55 | % scale. p1 X p2 generates a normal vector to plane defined by
56 | % origin, p1 and p2. If the dot product of this normal with p3
57 | % is zero then p3 also lies in the plane, hence co-linear.
58 | r = abs(dot(cross(p1, p2),p3)) < eps;
59 | else
60 | % Assume inhomogeneous coords, or homogeneous coords with equal
61 | % scale.
62 | r = norm(cross(p2-p1, p3-p1)) < eps;
63 | end
64 |
65 |
--------------------------------------------------------------------------------
/modelspecific/normalise2dpts.m:
--------------------------------------------------------------------------------
1 | % NORMALISE2DPTS - normalises 2D homogeneous points
2 | %
3 | % Function translates and normalises a set of 2D homogeneous points
4 | % so that their centroid is at the origin and their mean distance from
5 | % the origin is sqrt(2). This process typically improves the
6 | % conditioning of any equations used to solve homographies, fundamental
7 | % matrices etc.
8 | %
9 | % Usage: [newpts, T] = normalise2dpts(pts)
10 | %
11 | % Argument:
12 | % pts - 3xN array of 2D homogeneous coordinates
13 | %
14 | % Returns:
15 | % newpts - 3xN array of transformed 2D homogeneous coordinates. The
16 | % scaling parameter is normalised to 1 unless the point is at
17 | % infinity.
18 | % T - The 3x3 transformation matrix, newpts = T*pts
19 | %
20 | % If there are some points at infinity the normalisation transform
21 | % is calculated using just the finite points. Being a scaling and
22 | % translating transform this will not affect the points at infinity.
23 |
24 | % Peter Kovesi
25 | % School of Computer Science & Software Engineering
26 | % The University of Western Australia
27 | % pk at csse uwa edu au
28 | % http://www.csse.uwa.edu.au/~pk
29 | %
30 | % May 2003 - Original version
31 | % February 2004 - Modified to deal with points at infinity.
32 | % December 2008 - meandist calculation modified to work with Octave 3.0.1
33 | % (thanks to Ron Parr)
34 |
35 |
36 | function [newpts, T] = normalise2dpts(pts)
37 |
38 | if size(pts,1) ~= 3
39 | error('pts must be 3xN');
40 | end
41 |
42 | % Find the indices of the points that are not at infinity
43 | finiteind = find(abs(pts(3,:)) > eps);
44 |
45 | if length(finiteind) ~= size(pts,2)
46 | disp('Some points are at infinity');
47 | end
48 |
49 | % For the finite points ensure homogeneous coords have scale of 1
50 | pts(1,finiteind) = pts(1,finiteind)./pts(3,finiteind);
51 | pts(2,finiteind) = pts(2,finiteind)./pts(3,finiteind);
52 | pts(3,finiteind) = 1;
53 |
54 | c = mean(pts(1:2,finiteind)')'; % Centroid of finite points
55 | newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid.
56 | newp(2,finiteind) = pts(2,finiteind)-c(2);
57 |
58 | dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2);
59 | meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1
60 |
61 | scale = sqrt(2)/meandist;
62 |
63 | T = [scale 0 -scale*c(1)
64 | 0 scale -scale*c(2)
65 | 0 0 1 ];
66 |
67 | newpts = T*pts;
68 |
69 | end
--------------------------------------------------------------------------------
/modelspecific/vgg_H_from_x_lin.m:
--------------------------------------------------------------------------------
1 | function [H, A, C1, C2] = x(xs1,xs2,A,W,C1,C2)
2 | % H = vgg_H_from_x_lin(xs1,xs2)
3 | %
4 | % Compute H using linear method (see Hartley & Zisserman Alg 3.2 page 92 in
5 | % 1st edition, Alg 4.2 page 109 in 2nd edition).
6 | % Point preconditioning is inside the function.
7 | %
8 | % The format of the xs [p1 p2 p3 ... pn], where each p is a 2 or 3
9 | % element column vector.
10 |
11 | [r,c] = size(xs1);
12 |
13 | if (size(xs1) ~= size(xs2))
14 | error ('Input point sets are different sizes!')
15 | end
16 |
17 | if (size(xs1,1) == 2)
18 | xs1 = [xs1 ; ones(1,size(xs1,2))];
19 | xs2 = [xs2 ; ones(1,size(xs2,2))];
20 | end
21 |
22 |
23 | % condition points
24 | if nargin == 2
25 | C1 = vgg_conditioner_from_pts(xs1);
26 | C2 = vgg_conditioner_from_pts(xs2);
27 | xs1 = vgg_condition_2d(xs1,C1);
28 | xs2 = vgg_condition_2d(xs2,C2);
29 | end
30 |
31 | if nargin == 6
32 | B = A;
33 | B(1:2:end,:)=W*A(1:2:end,:);
34 | B(2:2:end,:)=W*A(2:2:end,:);
35 |
36 | % Extract nullspace
37 | [u,s,v] = svd(B, 0); s = diag(s);
38 | else
39 | A = [];
40 | ooo = zeros(1,3);
41 | for k=1:c
42 | p1 = xs1(:,k);
43 | p2 = xs2(:,k);
44 | A = [ A;
45 | p1'*p2(3) ooo -p1'*p2(1)
46 | ooo p1'*p2(3) -p1'*p2(2)
47 | ];
48 | end
49 |
50 | % Extract nullspace
51 | [u,s,v] = svd(A, 0); s = diag(s);
52 | end
53 |
54 | nullspace_dimension = sum(s < eps * s(1) * 1e3);
55 | if nullspace_dimension > 1
56 | fprintf('Nullspace is a bit roomy...');
57 | end
58 |
59 | h = v(:,9);
60 |
61 | H = reshape(h,3,3)';
62 |
63 | %decondition
64 | H = C2\H*C1;
65 |
66 | H = H/H(3,3);
67 | end
68 |
--------------------------------------------------------------------------------
/modelspecific/vgg_condition_2d.m:
--------------------------------------------------------------------------------
1 | function pc = z(p,C)
2 | % function pc = vgg_condition_2d(p,C);
3 | %
4 | % Condition a set of 2D homogeneous or nonhomogeneous points using conditioner C
5 |
6 | [r,c] = size(p);
7 | if r == 2
8 | pc = vgg_get_nonhomg(C * vgg_get_homg(p));
9 | elseif r == 3
10 | pc = C * p;
11 | else
12 | error ('rows != 2 or 3');
13 | end
14 |
15 | end
--------------------------------------------------------------------------------
/modelspecific/vgg_conditioner_from_pts.m:
--------------------------------------------------------------------------------
1 | function T = y(Pts,isotropic)
2 |
3 | % VGG_CONDITIONER_FROM_PTS - Returns a conditioning matrix for points
4 | %
5 | % T = vgg_conditioner_from_pts(Pts [,isotropic])
6 | %
7 | % Returns a DxD matrix that normalizes Pts to have mean 0 and stddev sqrt(2)
8 | %
9 | %
10 | %IN:
11 | % Pts - DxK list of K projective points. Last row is ignored.
12 | % isotropic - optional; if present then T(1,1)==T(2,2)==...==T(D-1,D-1).
13 | %
14 | %
15 | %OUT:
16 | % T - DxD conditioning matrix
17 |
18 | % Yoni, Thu Feb 14 12:24:48 2002
19 |
20 | Dim=size(Pts,1);
21 |
22 | Pts=vgg_get_nonhomg(Pts);
23 | Pts=Pts(1:Dim-1,:);
24 |
25 | m=mean(Pts,2);
26 | s=std(Pts');
27 | s=s+(s==0);
28 |
29 | if nargin==1
30 | T=[ diag(sqrt(2)./s) -diag(sqrt(2)./s)*m];
31 | else % isotropic; added by TW
32 | T=[ diag(sqrt(2)./(ones(1,Dim-1)*mean(s))) -diag(sqrt(2)./s)*m];
33 | end
34 | T(Dim,:)=0;
35 | T(Dim,Dim)=1;
36 |
--------------------------------------------------------------------------------
/modelspecific/vgg_get_nonhomg.m:
--------------------------------------------------------------------------------
1 | function x = vgg_get_nonhomg(x)
2 | % p = vgg_get_nonhomg(h)
3 | %
4 | % Convert a set of homogeneous points to non-homogeneous form
5 | % Points are stored as column vectors, stacked horizontally, e.g.
6 | % [x0 x1 x2 ... xn ;
7 | % y0 y1 y2 ... yn ;
8 | % w0 w1 w2 ... wn ]
9 |
10 | % Modified by TW
11 |
12 | if isempty(x)
13 | x = [];
14 | return;
15 | end
16 |
17 | d = size(x,1) - 1;
18 | x = x(1:d,:)./(ones(d,1)*x(end,:));
19 |
20 | return
--------------------------------------------------------------------------------
/randIndex.m:
--------------------------------------------------------------------------------
1 | function index = randIndex(maxIndex,len)
2 | %INDEX = RANDINDEX(MAXINDEX,LEN)
3 | % randomly, non-repeatedly select LEN integers from 1:MAXINDEX
4 |
5 | if len > maxIndex
6 | index = [];
7 | return
8 | end
9 |
10 | index = zeros(1,len);
11 | available = 1:maxIndex;
12 | rs = ceil(rand(1,len).*(maxIndex:-1:maxIndex-len+1));
13 | for p = 1:len
14 | while rs(p) == 0
15 | rs(p) = ceil(rand(1)*(maxIndex-p+1));
16 | end
17 | index(p) = available(rs(p));
18 | available(rs(p)) = [];
19 | end
--------------------------------------------------------------------------------
/ransacx.m:
--------------------------------------------------------------------------------
1 | function [f,inlierIdx] = ransacx( x,y, ransacCoef )%, funcFindF, funcDist)
2 | %[f inlierIdx] = ransacx( x,y,ransacCoef,funcFindF,funcDist )
3 | % Use RANdom SAmple Consensus to find a fit from X to Y.
4 | % X is M*n matrix including n points with dim M, Y is N*n;
5 | % The fit, f, and the indices of inliers, are returned.
6 | %
7 | % RANSACCOEF is a struct with following fields:
8 | % minPtNum,iterNum,thDist,thInlrRatio
9 | % MINPTNUM is the minimum number of points with whom can we
10 | % find a fit. For line fitting, it's 2. For homography, it's 4.
11 | % ITERNUM is the number of iteration,
12 | % THDIST is the inlier distance threshold and
13 | % ROUND(THINLRRATIO*n) is the inlier number threshold.
14 | %
15 | % FUNCFINDF is a func handle, f1 = funcFindF(x1,y1)
16 | % x1 is M*n1 and y1 is N*n1, n1 >= ransacCoef.minPtNum
17 | % f1 can be of any type.
18 |
19 | % FUNCDIST is a func handle, d = funcDist(f,x1,y1)
20 | % It uses f returned by FUNCFINDF, and return the distance
21 | % between f and the points, d is 1*n1.
22 | % For line fitting, it should calculate the dist between the line and the
23 | % points [x1;y1]; for homography, it should project x1 to y2 then
24 | % calculate the dist between y1 and y2.
25 | % Yan Ke @ THUEE, 20110123, xjed09@gmail.com
26 |
27 |
28 | minPtNum = ransacCoef.minPtNum;
29 | iterNum = ransacCoef.iterNum;
30 | thInlrRatio = ransacCoef.thInlrRatio;
31 | thDist = ransacCoef.thDist;
32 | ptNum = size(x,2);
33 | thInlr = round(thInlrRatio*ptNum);
34 |
35 | inlrNum = zeros(1,iterNum);
36 | fLib = cell(1,iterNum);
37 |
38 | parfor p = 1:iterNum
39 | % 1. fit using random points
40 | sampleIdx = randIndex(ptNum,minPtNum);
41 | f1 = calcHomo(x(:,sampleIdx),y(:,sampleIdx));%funcFindF(x(:,sampleIdx),y(:,sampleIdx)); % For homography: f1 is H
42 |
43 | % 2. count the inliers, if more than thInlr, refit; else iterate
44 | dist = calcDist(f1,x,y);%funcDist(f1,x,y);
45 | inlier1 = find(dist < thDist); %caculate count of inlier
46 | % if size(distance,1)==0
47 | % inlrNum(p) = length(inlier1); %original RANSAC =func(inlier1,distance,para):para=0:length;para=1:distance
48 | % else
49 | % if length(inlier1)>=4
50 | % inlrNum(p) = length(inlier1); %sum(distance(:,inlier1)); %distance RANSAC
51 | % fLib{p} = inlier1; % re-caculate H
52 | % else
53 | % inlrNum(p) = 0;
54 | % end
55 | % end
56 | % inlrNum(p) = length(inlier1);
57 | if length(inlier1) < thInlr, continue; end
58 | inlrNum(p) = length(inlier1);
59 | fLib{p} = inlier1; % re-caculate H
60 | end
61 |
62 | % 3. choose the coef with the most inliers
63 | [max_inlier, idx] = max(inlrNum);
64 | if max_inlier==0
65 | inlierIdx = [];
66 | f = [];
67 | return;
68 | end
69 | f = calcHomo(x(:,fLib{idx}),y(:,fLib{idx})); %most inliers
70 | dist = calcDist(f,x,y); % find match point
71 | inlierIdx = find(dist < thDist);
72 | f = calcHomo(x(:,inlierIdx),y(:,inlierIdx));
73 | % fprintf('> Select %d matches in 2nd round.\n', length(inlierIdx));
74 |
75 | end
--------------------------------------------------------------------------------
/registerTexture.m:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tlliao/Perception-based-seam-cutting/f1a839e0b24214773b26905719a492e49d0aa5ec/registerTexture.m
--------------------------------------------------------------------------------
/siftMatch.m:
--------------------------------------------------------------------------------
1 | function [pts1, pts2] = siftMatch( img1, img2 )
2 | %--------------------------------------
3 | % SIFT keypoint detection and matching.
4 | %--------------------------------------
5 | fprintf(' Keypoint detection and matching...');tic;
6 | [ kp1,ds1 ] = vl_sift(single(rgb2gray(img1)),'PeakThresh', 0,'edgethresh',500);
7 | [ kp2,ds2 ] = vl_sift(single(rgb2gray(img2)),'PeakThresh', 0,'edgethresh',500);
8 | matches = vl_ubcmatch(ds1, ds2);
9 | fprintf('done (%fs)\n',toc);
10 |
11 | % extract match points' position
12 | pts1 = kp1(1:2,matches(1,:));
13 | pts2 = kp2(1:2,matches(2,:));
14 |
15 | end
16 |
17 |
--------------------------------------------------------------------------------
/vlfeat-0.9.21/README.txt:
--------------------------------------------------------------------------------
1 | VLFeat 0.9.21 binary package can be downloaded from:
2 | http://www.vlfeat.org/
--------------------------------------------------------------------------------