Skip to content

Commit 0ba8f77

Browse files
committed
Add SaliencyCut
1 parent 47d5265 commit 0ba8f77

2 files changed

Lines changed: 423 additions & 0 deletions

File tree

‎CmLib/Saliency/CmSalCut.cpp‎

Lines changed: 339 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,339 @@
1+
#include "StdAfx.h"
2+
#include "CmSalCut.h"
3+
4+
5+
CmSalCut::CmSalCut(CMat &img3f)
6+
:_fGMM(5), _bGMM(5), _w(img3f.cols), _h(img3f.rows), _lambda(50)
7+
{
8+
CV_Assert(img3f.data != NULL && img3f.type() == CV_32FC3);
9+
_imgBGR3f = img3f;
10+
cvtColor(_imgBGR3f, _imgLab3f, CV_BGR2Lab);
11+
_trimap1i = Mat::zeros(_h, _w, CV_32S);
12+
_segVal1f = Mat::zeros(_h, _w, CV_32F);
13+
_graph = NULL;
14+
15+
_L = 8 * _lambda + 1;// Compute L
16+
_beta = 0; {// compute beta
17+
int edges = 0;
18+
double result = 0;
19+
for (int y = 0; y < _h; ++y) {
20+
const Vec3f* img = _imgLab3f.ptr<Vec3f>(y);
21+
for (int x = 0; x < _w; ++x){
22+
Point pnt(x, y);
23+
for (int i = 0; i < 4; i++) {
24+
Point pntN = pnt + DIRECTION8[i];
25+
if (CHK_IND(pntN))
26+
result += vecSqrDist(_imgLab3f.at<Vec3f>(pntN), img[x]), edges++;
27+
}
28+
}
29+
}
30+
_beta = (float)(0.5 * edges/result);
31+
}
32+
_NLinks.create(_h, _w); {// computeNLinks
33+
static const float dW[4] = {1, (float)(1/SQRT2), 1, (float)(1/SQRT2)};
34+
for (int y = 0; y < _h; y++) {
35+
Vec4f *nLink = _NLinks.ptr<Vec4f>(y);
36+
const Vec3f* img = _imgLab3f.ptr<Vec3f>(y);
37+
for (int x = 0; x < _w; x++, nLink++) {
38+
Point pnt(x, y);
39+
const Vec3f& c1 = img[x];
40+
for (int i = 0; i < 4; i++) {
41+
Point pntN = pnt + DIRECTION8[i];
42+
if (CHK_IND(pntN))
43+
(*nLink)[i] = _lambda * dW[i] * exp(-_beta * vecSqrDist(_imgLab3f.at<Vec3f>(pntN), c1));
44+
}
45+
}
46+
}
47+
}
48+
49+
for (int i = 0; i < 4; i++)
50+
_directions[i] = DIRECTION8[i].x + DIRECTION8[i].y * _w;
51+
}
52+
53+
CmSalCut::~CmSalCut(void)
54+
{
55+
if (_graph)
56+
delete _graph;
57+
}
58+
59+
Mat CmSalCut::CutObjs(CMat &_img3f, CMat &_sal1f, float t1, float t2, CMat &_border1u, int wkSize)
60+
{
61+
Mat border1u = _border1u;
62+
if (border1u.data == NULL || border1u.size != _img3f.size){
63+
int bW = cvRound(0.02 * _img3f.cols), bH = cvRound(0.02 * _img3f.rows);
64+
border1u.create(_img3f.rows, _img3f.cols, CV_8U);
65+
border1u = 255;
66+
border1u(Rect(bW, bH, _img3f.cols - 2*bW, _img3f.rows - 2*bH)) = 0;
67+
}
68+
Mat sal1f, wkMask;
69+
_sal1f.copyTo(sal1f);
70+
sal1f.setTo(0, border1u);
71+
72+
cv::Rect rect(0, 0, _img3f.cols, _img3f.rows);
73+
if (wkSize > 0){
74+
threshold(sal1f, sal1f, t1, 1, THRESH_TOZERO);
75+
sal1f.convertTo(wkMask, CV_8U, 255);
76+
threshold(wkMask, wkMask, 70, 255, THRESH_TOZERO);
77+
wkMask = CmCv::GetNZRegionsLS(wkMask, 0.005);
78+
if (wkMask.data == NULL)
79+
return Mat();
80+
rect = CmCv::GetMaskRange(wkMask, wkSize);
81+
sal1f = sal1f(rect);
82+
border1u = border1u(rect);
83+
wkMask = wkMask(rect);
84+
}
85+
CMat img3f = _img3f(rect);
86+
87+
Mat fMask;
88+
CmSalCut salCut(img3f);
89+
salCut.initialize(sal1f, t1, t2);
90+
const int outerIter = 4;
91+
//salCut.showMedialResults("Ini");
92+
for (int j = 0; j < outerIter; j++) {
93+
salCut.fitGMMs();
94+
int changed = 1000, times = 8;
95+
while (changed > 50 && times--) {
96+
//salCut.showMedialResults("Medial results");
97+
changed = salCut.refineOnce();
98+
//waitKey(1);
99+
}
100+
//salCut.showMedialResults(format("It%d", j));
101+
//waitKey(0);
102+
salCut.drawResult(fMask);
103+
104+
fMask = CmCv::GetNZRegionsLS(fMask);
105+
if (fMask.data == NULL)
106+
return Mat();
107+
108+
if (j == outerIter - 1 || ExpandMask(fMask, wkMask, border1u, 5) < 10)
109+
break;
110+
111+
salCut.initialize(wkMask);
112+
fMask.copyTo(wkMask);
113+
}
114+
115+
Mat resMask = Mat::zeros(_img3f.size(), CV_8U);
116+
fMask.copyTo(resMask(rect));
117+
return resMask;
118+
}
119+
120+
// Initialize using saliency map. In the Trimap: background < t1, foreground > t2, others unknown.
121+
// Saliency values are in [0, 1], "sal1f" and "1-sal1f" are used as weight to train fore and back ground GMMs
122+
void CmSalCut::initialize(CMat &sal1f, float t1, float t2)
123+
{
124+
CV_Assert(sal1f.type() == CV_32F && sal1f.size == _imgBGR3f.size);
125+
sal1f.copyTo(_segVal1f);
126+
127+
for (int y = 0; y < _h; y++) {
128+
int* triVal = _trimap1i.ptr<int>(y);
129+
const float *segVal = _segVal1f.ptr<float>(y);
130+
for (int x = 0; x < _w; x++) {
131+
triVal[x] = segVal[x] < t1 ? TrimapBackground : TrimapUnknown;
132+
triVal[x] = segVal[x] > t2 ? TrimapForeground : triVal[x];
133+
}
134+
}
135+
}
136+
137+
void CmSalCut::initialize(CMat &sal1u) // Background = 0, unknown = 128, foreground = 255
138+
{
139+
CV_Assert(sal1u.type() == CV_8UC1 && sal1u.size == _imgBGR3f.size);
140+
for (int y = 0; y < _h; y++) {
141+
int* triVal = _trimap1i.ptr<int>(y);
142+
const byte *salVal = sal1u.ptr<byte>(y);
143+
float *segVal = _segVal1f.ptr<float>(y);
144+
for (int x = 0; x < _w; x++) {
145+
triVal[x] = salVal[x] < 70 ? TrimapBackground : TrimapUnknown;
146+
triVal[x] = salVal[x] > 200 ? TrimapForeground : triVal[x];
147+
segVal[x] = salVal[x] < 70 ? 0 : 1.f;
148+
}
149+
}
150+
}
151+
152+
// Initial rect region in between thr1 and thr2 and others below thr1 as the Grabcut paper
153+
void CmSalCut::initialize(const Rect &rect)
154+
{
155+
_trimap1i = TrimapBackground;
156+
_trimap1i(rect) = TrimapUnknown;
157+
_segVal1f = 0;
158+
_segVal1f(rect) = 1;
159+
}
160+
161+
void CmSalCut::fitGMMs()
162+
{
163+
_fGMM.BuildGMMs(_imgBGR3f, _fGMMidx1i, _segVal1f);
164+
_bGMM.BuildGMMs(_imgBGR3f, _bGMMidx1i, 1 - _segVal1f);
165+
}
166+
167+
int CmSalCut::refineOnce()
168+
{
169+
// Steps 4 and 5: Learn new GMMs from current segmentation
170+
if (_fGMM.GetSumWeight() < 50 || _bGMM.GetSumWeight() < 50)
171+
return 0;
172+
173+
_fGMM.RefineGMMs(_imgBGR3f, _fGMMidx1i, _segVal1f);
174+
_bGMM.BuildGMMs(_imgBGR3f, _bGMMidx1i, 1 - _segVal1f);
175+
176+
// Step 6: Run GraphCut and update segmentation
177+
initGraph();
178+
if (_graph)
179+
_graph->maxflow();
180+
181+
return updateHardSegmentation();
182+
}
183+
184+
int CmSalCut::updateHardSegmentation()
185+
{
186+
int changed = 0;
187+
for (int y = 0, id = 0; y < _h; ++y) {
188+
float* segVal = _segVal1f.ptr<float>(y);
189+
int* triMapD = _trimap1i.ptr<int>(y);
190+
for (int x = 0; x < _w; ++x, id++) {
191+
float oldValue = segVal[x];
192+
if (triMapD[x] == TrimapBackground)
193+
segVal[x] = 0.f; // SegmentationBackground
194+
else if (triMapD[x] == TrimapForeground)
195+
segVal[x] = 1.f; // SegmentationForeground
196+
else
197+
segVal[x] = _graph->what_segment(id) == GraphF::SOURCE ? 1.f : 0.f;
198+
changed += abs(segVal[x] - oldValue) > 0.1 ? 1 : 0;
199+
}
200+
}
201+
return changed;
202+
}
203+
204+
void CmSalCut::initGraph()
205+
{
206+
// Set up the graph (it can only be used once, so we have to recreate it each time the graph is updated)
207+
if (_graph == NULL)
208+
_graph = new GraphF(_w * _h, 4 * _w * _h);
209+
else
210+
_graph->reset();
211+
_graph->add_node(_w * _h);
212+
213+
for (int y = 0, id = 0; y < _h; ++y) {
214+
int* triMapD = _trimap1i.ptr<int>(y);
215+
const float* img = _imgBGR3f.ptr<float>(y);
216+
for(int x = 0; x < _w; x++, img += 3, id++) {
217+
float back, fore;
218+
if (triMapD[x] == TrimapUnknown ) {
219+
fore = -log(_bGMM.P(img));
220+
back = -log(_fGMM.P(img));
221+
}
222+
else if (triMapD[x] == TrimapBackground )
223+
fore = 0, back = _L;
224+
else // TrimapForeground
225+
fore = _L, back = 0;
226+
227+
// Set T-Link weights
228+
_graph->add_tweights(id, fore, back); // _graph->set_tweights(_nodes(y, x), fore, back);
229+
230+
// Set N-Link weights from precomputed values
231+
Point pnt(x, y);
232+
const Vec4f& nLink = _NLinks(pnt);
233+
for (int i = 0; i < 4; i++) {
234+
Point nPnt = pnt + DIRECTION8[i];
235+
if (CHK_IND(nPnt))
236+
_graph->add_edge(id, id + _directions[i], nLink[i], nLink[i]);
237+
}
238+
}
239+
}
240+
}
241+
242+
Mat CmSalCut::showMedialResults(CStr& title)
243+
{
244+
_show3u.create(_h, _w * 2, CV_8UC3);
245+
Mat showTri = _show3u(Rect(0, 0, _w, _h));
246+
Mat showSeg = _show3u(Rect(_w, 0, _w, _h));
247+
_imgBGR3f.convertTo(showTri, CV_8U, 255);
248+
showTri.copyTo(showSeg);
249+
250+
for (int y = 0; y < _h; y++){
251+
const int* triVal = _trimap1i.ptr<int>(y);
252+
const float* segVal = _segVal1f.ptr<float>(y);
253+
Vec3b* triD = showTri.ptr<Vec3b>(y);
254+
Vec3b* segD = showSeg.ptr<Vec3b>(y);
255+
for (int x = 0; x < _w; x++, triD++, segD++) {
256+
switch (triVal[x]){
257+
case TrimapForeground: (*triD)[2] = 255; break; // Red
258+
case TrimapBackground: (*triD)[1] = 255; break; // Green
259+
}
260+
if (segVal[x] > 0.5)
261+
(*segD)[0] = 255;
262+
else
263+
(*segD) /= 2;
264+
}
265+
}
266+
CmShow::SaveShow(_show3u, title);
267+
return _show3u;
268+
}
269+
270+
int CmSalCut::ExpandMask(CMat &fMask, Mat &mask1u, CMat &bdReg1u, int expandRatio)
271+
{
272+
compare(fMask, mask1u, mask1u, CMP_NE);
273+
int changed = cvRound(sum(mask1u).val[0] / 255.0);
274+
275+
Mat bigM, smalM;
276+
dilate(fMask, bigM, Mat(), Point(-1, -1), expandRatio);
277+
erode(fMask, smalM, Mat(), Point(-1, -1), expandRatio);
278+
static const double erodeSmall = 255 * 50;
279+
if (sum(smalM).val[0] < erodeSmall)
280+
smalM = fMask;
281+
mask1u = bigM * 0.5 + smalM * 0.5;
282+
mask1u.setTo(0, bdReg1u);
283+
return changed;
284+
}
285+
286+
int CmSalCut::Demo(CStr imgNameW, CStr gtImgW, CStr salDir)
287+
{
288+
//if (argc != 5){
289+
// printf("Usage: SalCut inImgs tImgs salDir result\n");
290+
// printf("\tinImgs:\tInput images. e.g. `D:/Src/*.jpg'\n");
291+
// printf("\ttImgs:\tGround truth results. e.g. `D:/Src/*.png'\n");
292+
// printf("\tsalDir:\tSaliency map saving directory. e.g. `D:/Sal'\n");
293+
// printf("\tresult:\tStatistic result show name. e.g. `D:/EvaluateShow.m'\n");
294+
// return 1;
295+
//}
296+
//string imgNameW = argv[1];
297+
//string gtImgW = argv[2];
298+
//string resultFileName = argv[4];
299+
//string salDir = string(argv[3]) + "/";
300+
301+
vecS names;
302+
string inDir, ext;
303+
int imgNum = CmFile::GetNamesNE(imgNameW, names, inDir, ext);
304+
CmFile::MkDir(salDir);
305+
printf("Get saliency maps for images `%s' and save results to `%s'\n", imgNameW.c_str(), salDir.c_str());
306+
307+
#pragma omp parallel for
308+
for (int i = 0; i < imgNum; i++){
309+
string name = names[i] + ext;
310+
if (CmFile::FileExist(salDir + names[i] + "_RCC.png"))
311+
continue;
312+
313+
printf("Processing %d/%dth image: %-70s\r", i, imgNum, _S(name));
314+
Mat sal, img3f = imread(inDir + name);
315+
CV_Assert_(img3f.data != NULL, ("Can't load image %s\n", _S(name)));
316+
img3f.convertTo(img3f, CV_32FC3, 1.0/255);
317+
sal = CmSaliencyRC::GetRC(img3f);
318+
imwrite(salDir + names[i] + "_RC.png", sal*255);
319+
320+
Mat cutMat;
321+
float t = 0.9f;
322+
int maxIt = 4;
323+
while (cutMat.empty() && maxIt--){
324+
cutMat = CmSalCut::CutObjs(img3f, sal, 0.1f, t);
325+
t -= 0.2f;
326+
}
327+
if (!cutMat.empty())
328+
imwrite(salDir + names[i] + "_RCC.png", cutMat);
329+
else
330+
printf("Image(.jpg): %s", _S(names[i] + "\n"));
331+
}
332+
printf("Get saliency finished%-40s\n", "");
333+
334+
printf("Evaluate saliency maps according to ground truth results `%s'\n", gtImgW.c_str());
335+
//CmEvaluation::Evaluate(gtImgW, salDir, resultFileName, "_RC");
336+
//CmEvaluation::EvalueMask(gtImgW, salDir, "RCC", CmFile::GetFatherFolder(salDir) + "CutRes.m");
337+
338+
return 0;
339+
}

0 commit comments

Comments
 (0)