File: 3dsegment-ahmed.cc

package info (click to toggle)
mia 2.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 13,532 kB
  • ctags: 16,800
  • sloc: cpp: 137,909; python: 1,057; ansic: 998; sh: 146; xml: 127; csh: 24; makefile: 13
file content (491 lines) | stat: -rw-r--r-- 12,864 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/* -*- mia-c++  -*-
 *
 * This file is part of MIA - a toolbox for medical image analysis 
 * Copyright (c) Leipzig, Madrid 1999-2014 Gert Wollny
 *
 * MIA is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with MIA; if not, see <http://www.gnu.org/licenses/>.
 *
 */

/*
   This program implements and enhances the paper:
   Mohamed N. Ahmed et. al, "A Modified Fuzzy C-Means Algorithm for Bias Field 
   estimation and Segmentation of MRI Data", IEEE Trans. on Medical Imaging, 
   Vol. 21, No. 3, March 2002
   
   changes are: 
   - p = 2
   - exp
   - 
*/


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif


#include <mia/core/histogram.hh>
#include <mia/core/cmdlineparser.hh>
#include <mia/3d.hh>

#include <memory>
#include <vector>

using namespace mia;
using namespace std; 

typedef vector<C3DFImage> C3DFImageVec;

const SProgramDescription g_description = {
        {pdi_group, "Analysis, filtering, combining, and segmentation of 3D images"}, 
	{pdi_short, "Run a fuzzy c-means segmentation of a 3D image."}, 
	{pdi_description, "This program implements a variation of the paper:"
	 "Mohamed N. Ahmed et. al, \"A Modified Fuzzy C-Means Algorithm for Bias Field "
	 "estimation and Segmentation of MRI Data\", IEEE Trans. on Medical Imaging, "
	 "Vol. 21, No. 3, March 2002, changes are: p=2, and exp"}, 
	{pdi_example_descr, "Run a 5-class segmentation over input image input.v and store the class "
	 "probability images in cls.v." }, 
	{pdi_example_code, "-i input.v -a 5 -o cls.v"}
}; 


class CSegment3d  {
public: 
	typedef C3DImageVector result_type; 

	CSegment3d(bool bg_correct, int ncc,
		   const vector<float>& icc, float k); 
	
	template <class T> 
	CSegment3d::result_type operator()(const T3DImage<T>& image); 

private: 
	void process(const C3DFImage& image, 
		     vector<float>& class_centers, 
		     C3DFImageVec& prob)const; 

	float update_class_centers(C3DFImage& image, C3DFImageVec& prob, vector<float>& class_centers)const; 
	
	void evaluate_probabilities(C3DFImageVec& prob) const; 

	unsigned int _M_nClasses;
	bool         _M_bg_correct; 
	vector<float> _M_class_centers; 
	const float _M_k; 
	mutable float _M_minh; 
	mutable float _M_maxh; 
	
	
};



CSegment3d::CSegment3d(bool bg_correct, int ncc,
				 const vector<float>& icc, float k):
	_M_nClasses(ncc), 
	_M_bg_correct(bg_correct), 
	_M_class_centers(icc),
	_M_k(k), 
	_M_minh(0), 
	_M_maxh(0)
{
}	

struct CLogTransform {
	CLogTransform(float minh, float maxh):
		_M_minh(minh),  
		_M_div(maxh - minh + 1.0)
	{
	}

	float operator() (float x) const 
	{
		return (x - _M_minh) / _M_div;
	}
private: 
	float _M_minh;
	float _M_div; 

};

struct CExpTransform {
	CExpTransform(float minh, float maxh):
		_M_minh(minh), 
		_M_div(maxh - minh + 1.0)
	{
	}
	float operator() (float x) const 
	{
		return x *  _M_div + _M_minh;
	}
private: 
	float _M_minh;
	float _M_div; 

};

template <class T>
struct CThresholder {
	CThresholder(T thresh):_M_thresh(thresh){
	}
	
	T operator ()(T x) {
		return x > _M_thresh ? x : 0; 
	}
private: 
	T _M_thresh; 
};

template <typename CI>
void get_min_max(CI begin, CI end, typename CI::value_type& minh, typename CI::value_type& maxh)
{
	auto minmax = minmax_element(begin, end); 
	minh = *minmax.first; 
	maxh = *minmax.second; 
}


template <class T> 
CSegment3d::result_type CSegment3d::operator()(const T3DImage<T>& image)
{
	// first evaluate the histogram borders and get the initial class centers
	T minh=0; 
	T maxh=numeric_limits<T>::max(); 
	

	get_min_max(image.begin(), image.end(), minh, maxh);  
	
	_M_minh = minh; 
	_M_maxh = maxh;
	
	cvdebug() << "Entering CSegment3d::operator()\n"; 
	
	if (_M_class_centers.empty()) {
		cvdebug() << "Estimate initial class centers from histogram\n"; 
		// estimate some classes
		_M_class_centers.resize(_M_nClasses); 
		_M_class_centers[0] = _M_minh; 
		
		float step = (_M_maxh - _M_minh) / 256.0; 
		THistogram<THistogramFeeder<T> > histogram(THistogramFeeder<T>(_M_minh, _M_maxh, 256)); 
		histogram.push_range(image.begin(), image.end());

		float thresh = static_cast<float>(image.size() - histogram[0]) / _M_nClasses;
		float hit = 0.0; 
		size_t i = 1; 
		float val = _M_minh + step; 
		
		auto hi = histogram.begin(); 
		auto he = histogram.end(); 
		++hi; 
		
		while (i < _M_nClasses && hi != he) {
			hit += *hi; 
			if (hit > thresh) {
				_M_class_centers[i++] = val; 
				hit -= thresh; 
			}
			++hi; 
			val += step; 
		}
		
		// print out the new class centers
	}
	cvmsg() << " initial classes ["; 
	for (size_t j = 0; j < _M_nClasses; ++j)
		cvmsg() << _M_class_centers[j] << " "; 
	cvmsg() << "]" << endl;
	
	C3DFImage log_image(image.get_size()); 	                                 // 4 Bpp
	vector<float> log_class_centers(_M_nClasses); 

	CLogTransform logt(_M_minh, _M_maxh); 
	
	// fill the logarithmic image with values
	transform(image.begin(), image.end(), log_image.begin(), logt);
	transform(_M_class_centers.begin(), _M_class_centers.end(), log_class_centers.begin(), logt);
	
	// initialise teporaries
	C3DFImageVec prob; 

	for (size_t i = 0; i < _M_nClasses; ++i) {
		prob.push_back(C3DFImage(image.get_size()));                    // 4 * _M_nClasses Bpp
	}

	
	process(log_image, log_class_centers, prob); 
	
	
	CExpTransform exptrans(minh, maxh); 
	transform(log_class_centers.begin(), log_class_centers.end(), 
		       _M_class_centers.begin(), exptrans); 

	C3DImageVector result;  

	for (size_t j = 0; j < _M_nClasses; ++j) {
		C3DFImage *r = new C3DFImage(image.get_size(), image); 
		transform(prob[j].begin(), prob[j].end(), r->begin(), 
			  [](float x){return sqrt(x);}); 
		result.push_back(P3DImage(r)); 
	}
	return result; 
}
		

void CSegment3d::evaluate_probabilities(C3DFImageVec& prob)const
{
	vector<C3DFImage::iterator> pi(_M_nClasses); 
	
	C3DFImage::iterator stopper =  prob[0].end(); 
	
	for (size_t i = 0; i < _M_nClasses; ++i)
		pi[i] = prob[i].begin(); 
		
	while (pi[0] != stopper) {
		float sum = 0.0; 
		for (size_t i = 0; i < _M_nClasses; ++i)
			sum += *pi[i];
		
		if (sum != 0.0)  
			for (size_t i = 0; i < _M_nClasses; ++i) {
				*pi[i] /= sum;
				*pi[i] *= *pi[i]; 
				++pi[i];
			}
		else {// must be a bright value, otherwise, class[0] would catch it
			for (size_t i = 0; i < _M_nClasses - 1; ++i)
				*pi[i]++ = 0.0;
			*pi[_M_nClasses - 1] = 1.0; 
		}
	}
}

float CSegment3d::update_class_centers(C3DFImage& image, C3DFImageVec& prob, vector<float>& class_centers) const 
{
	float residuum = 0.0; 
	
	for (size_t i = 0; i < _M_nClasses; ++i) {
		float cc = class_centers[i]; 
		float loc_res = 100; 

		// try a fix-point iteration for the new class center
		
		while (loc_res > 0.0001) {
			float cc_old = cc; 
			
			C3DFImage::const_iterator ihelp = image.begin(); 
			C3DFImage::const_iterator iprob = prob[i].begin(); 
			C3DFImage::const_iterator eprob = prob[i].end();
			
			double sum_prob = 0.0; 
			double sum_weight = 0.0; 
			
			while (iprob != eprob) {
				if (*iprob > 0.0f) {
					const double val = *ihelp - cc;
					const double val2 = val * val; 
					const double val2mexpval2 = val2 * exp(val2)  * *iprob;

					sum_prob += val2mexpval2; 
					sum_weight += val2mexpval2 * *ihelp; 
				}
				
				++ihelp; 
				++iprob; 
			}
			// how do i deal with the (very unprobable case sum_prob==0.0?)
			if (sum_prob  != 0.0) {
				cc += 0.1 * (sum_weight / sum_prob - cc); 
			} else {
				cvwarn() << "class[" << i << "] has no probable members, keeping old value:" << sum_prob << ":" <<sum_weight <<endl; 
			}
			loc_res = cc > cc_old ? cc - cc_old :  cc_old - cc; 
			cvdebug() << "res = " << loc_res << " : cc = "<< cc <<"\n"; 
			
		}// end while (loc_res > 0.01)
		cverb << "\n"; 

		float delta = cc - class_centers[i]; 
		residuum += delta * delta; 
		class_centers[i] =  cc; 
		
	}// end update class centers
	return residuum; 
}



void
CSegment3d::process(const C3DFImage& image, 
			 vector<float>& class_centers, 
			 C3DFImageVec& prob)const
{
	
	int n_iterations = 0; 

	CExpTransform exptrans(_M_minh, _M_maxh); 
	
	C3DFImage tmp(image.get_size());                                        // 4Bpp

	unique_ptr<C3DFImage> bg_image;

	
	if (_M_bg_correct) {
		bg_image.reset(new C3DFImage(image.get_size())); 
		fill(bg_image->begin(), bg_image->end(), 1.0); 
	}

	
	float residuum = 100; 
	// these conditions have to be exported 
	while (residuum > 0.000001 && n_iterations < 100) {
		++n_iterations; 

		// distance evaluation 
		vector<float>::const_iterator icls = class_centers.begin(); 
		for (size_t i = 0; i < _M_nClasses; ++i, ++icls) {
			
			// evaluate D for class i 
			C3DFImage::iterator di = prob[i].begin(); 
			C3DFImage::iterator de = prob[i].end(); 
			C3DFImage::const_iterator ii = image.begin(); 
			
			if (_M_bg_correct) {
				C3DFImage::const_iterator ib = bg_image->begin(); 
				while (di != de) {
					float val = *ii++ * *ib++ - *icls; 
					*di++ = expf(-val * val * _M_k); 
				}
			}else
				while (di != de) {
					float val = *ii++ - *icls; 
					*di++ = expf(-val * val * _M_k); 
				}
			

		}// end D evaluation 

		// evaluate probabilities
		evaluate_probabilities(prob);

		if (_M_bg_correct)
			transform(image.begin(), image.end(), bg_image->begin(), tmp.begin(), minus<float>()); 
		else
			copy(image.begin(), image.end(), tmp.begin()); 
		
		residuum = update_class_centers(tmp, prob, class_centers);
		
		// print out the new class centers
		cvmsg() << n_iterations << ": classes ["; 
		for (size_t j = 0; j < _M_nClasses; ++j)
			cvmsg() << exptrans(class_centers[j]) << " "; 
		cvmsg() << "]" << endl; 
		
		// update field correction 
		// this certainly needs a methodological review
		if (_M_bg_correct){
			C3DFImage::const_iterator ii = image.begin(); 
			C3DFImage::iterator ib = bg_image->begin(); 
			C3DFImage::iterator eb = bg_image->begin(); 
			
			vector<C3DFImage::const_iterator> pi(_M_nClasses); 
			
			for (size_t j = 0; j < _M_nClasses; ++j)
				pi[j] = prob[j].begin();

			
			while (ib != eb) {
				float sum_prob = 0.0; 
				float sum_weight = 0.0; 
				
				for (size_t j = 0; j < _M_nClasses; ++j) {
					sum_weight += *pi[j] * class_centers[j]; 
					sum_prob   += *pi[j]; 
					++pi[j];
				}

				assert(sum_prob != 0.0); 
				
				*ib =*ii * (sum_prob / sum_weight); 
				++ib; 
				++ii; 
			}
			
		}// end update bg field

	} // end main while loop
}

int do_main(int argc, char *argv[])
{

	string in_filename; 
	string cls_filename; 
	string out_filename; 
	int n_classes = 3; 
	bool bg_correct = false; 
	string neighborhood_filter; 
	vector<float> initial_class_centres; 
	float spread = 64; 

	const auto& image3dio = C3DImageIOPluginHandler::instance();

	CCmdOptionList opts(g_description);
	opts.add(make_opt( in_filename, "in-file", 'i', "image to be segmented", CCmdOptionFlags::required_input, &image3dio )); 
	opts.add(make_opt( cls_filename, "out-file", 'o', "class probability images, the image type "
			   "must support multiple images and floating point values", CCmdOptionFlags::required_output, &image3dio )); 
	opts.add(make_opt( n_classes, "no-of-classes", 'a', "number of classes"));
	opts.add(make_opt( bg_correct, "bias-correct", 'b', "apply bias field correction"));
	opts.add(make_opt( initial_class_centres, "class-centres", 'c', "initial class centers"));
	opts.add(make_opt( spread, "spread", 's', "spread parameter describing the strength of mattar distinction")); 
	
	if (opts.parse(argc, argv) != CCmdOptionList::hr_no)
		return EXIT_SUCCESS; 
	
	
	if (initial_class_centres.empty()) {
		cvdebug() << "no class centers given at command line\n"; 
		if (n_classes < 2)
			throw invalid_argument("at least two classes need to be requested"); 
	}else {
		cvdebug() << "Initially classes: " << initial_class_centres.size() << "\n"; 
	}
	
	// initialize the functor
	CSegment3d Segment(bg_correct, n_classes, 
			   initial_class_centres, spread);
	
	
	auto in_image = load_image3d(in_filename); 
	
	auto seg_list = mia::accumulate (Segment, *in_image);
	C3DImageIOPluginHandler::Instance::Data out_image_list(seg_list);
	
	
		//CHistory::instance().append(argv[0], revision, opts);
	
	if ( !C3DImageIOPluginHandler::instance().save(cls_filename, seg_list) ){
		string not_save = ("unable to save result to ") + cls_filename;
		throw runtime_error(not_save);
	}
	
	return EXIT_SUCCESS; 
	
}

#include <mia/internal/main.hh>
MIA_MAIN(do_main);