Bsoft  2.1.0
Bernard's software package
bsupix.cpp
Go to the documentation of this file.
1 
9 #include "rwimg.h"
10 #include "options.h"
11 #include "utilities.h"
12 #include "timer.h"
13 
14 
15 // Declaration of global variables
16 extern int verbose; // Level of output to the screen
17 
18 vector<Bsuperpixel> superpixel_from_json(JSvalue& root);
19 JSvalue json_from_superpixel(vector<Bsuperpixel>& seg);
20 
21 /* Usage assistence */
22 const char* use[] = {
23 " ",
24 "Usage: bsupix [options] input.img output.img",
25 "--------------------------------------------",
26 "Segments an image into superpixels.",
27 " ",
28 "Actions:",
29 "-average 7,5,3 Averaging/smoothing filter: kernel size.",
30 "-variance 11 Calculate a local variance image using the given size kernel.",
31 "-superpixels 123 Segment into superpixels with the given step size.",
32 "-impose 3 Assign segment feature:",
33 " 1: segment average",
34 " 2: lowest neighboring segment average",
35 " 3: difference from lowest neighboring segment average",
36 " 4: highest neighboring segment average",
37 " 5: difference from highest neighboring segment average",
38 "-colorize Generate random segment colors.",
39 "-pattern neigbor Calculate local or neighbor binary pattern.",
40 " ",
41 "Parameters:",
42 "-verbose 7 Verbose output.",
43 "-datatype u Force writing of a new data type.",
44 " ",
45 "Parameters for superpixel segmentation:",
46 "-iterations 50 Number of segmentation iterations (default 10).",
47 "-bin 3 Number of binning levels (default 1).",
48 "-weight 0.5 Color weight (default 0.2).",
49 "-stop 1.5 Stopping condition (default 1%).",
50 " ",
51 //"Parameters for segmentation analysis:",
52 //" ",
53 "Input:",
54 "-maskin mask.mrc Multi-level input mask.",
55 "-input segfile.json Segmentation input file.",
56 " ",
57 "Output:",
58 "-maskout mask.mrc Multi-level output mask.",
59 "-output segfile.json Segmentation output file.",
60 " ",
61 NULL
62 };
63 
64 int main(int argc, char* argv[])
65 {
66  // Initialize variables
67  Vector3<long> average_kernel; // Average filter kernel size
68  long var_kernel(0); // Variance filter kernel size
69  long step(0); // Superpixel step size
70  double colorweight(0.2); // Color weighting
71  long iterations(10); // Segmentation iterations
72  long bin(1); // Number of binning levels
73  double stop(1); // Stopping condition
74  int impose(0); // Flag to impose segment colors
75  int colorize(0); // Generate color mask
76  DataType nudatatype(Unknown_Type); // Conversion to new type
77  Bstring maskin; // Multi-level input mask file name
78  Bstring maskout; // Multi-level output mask file name
79  Bstring segin; // Segmentation input file name
80  Bstring segout; // Segmentation output file name
81 
82  int i, optind;
83  Boption* option = get_option_list(use, argc, argv, optind);
84  Boption* curropt;
85  for ( curropt = option; curropt; curropt = curropt->next ) {
86  if ( curropt->tag == "average" ) {
87  if ( ( i = curropt->values(average_kernel[0],
88  average_kernel[1], average_kernel[2]) ) < 1 )
89  cerr << "-average: The kernel edge size must be specified!" << endl;
90  else
91  if ( i < 2 ) average_kernel[2] = average_kernel[1] = average_kernel[0];
92  }
93  if ( curropt->tag == "variance" )
94  if ( ( var_kernel = curropt->integer() ) < 2 )
95  cerr << "-variance: The kernel edge size must be specified!" << endl;
96  if ( curropt->tag == "superpixels" )
97  if ( ( step = curropt->integer() ) < 2 )
98  cerr << "-superpixels: A step size greater than 1 must be specified!" << endl;
99  if ( curropt->tag == "impose" )
100  if ( ( impose = curropt->integer() ) < 1 )
101  cerr << "-impose: One option must be specified!" << endl;
102  if ( curropt->tag == "colorize" )
103  colorize = 1;
104  if ( curropt->tag == "datatype" )
105  nudatatype = curropt->datatype();
106  if ( curropt->tag == "iterations" )
107  if ( ( iterations = curropt->integer() ) < 1 )
108  cerr << "-iterations: At least one iteration must be specified!" << endl;
109  if ( curropt->tag == "bin" )
110  if ( ( bin = curropt->integer() ) < 1 )
111  cerr << "-bin: At number of binning levels must be specified!" << endl;
112  if ( curropt->tag == "weight" )
113  if ( ( colorweight = curropt->real() ) < 0.001 )
114  cerr << "-weight: A color weight must be specified!" << endl;
115  if ( curropt->tag == "stop" )
116  if ( ( stop = curropt->real() ) < 0.001 )
117  cerr << "-stop: A stopping percentage must be specified!" << endl;
118  if ( curropt->tag == "maskin" )
119  maskin = curropt->filename();
120  if ( curropt->tag == "maskout" )
121  maskout = curropt->filename();
122  if ( curropt->tag == "input" )
123  segin = curropt->filename();
124  if ( curropt->tag == "output" )
125  segout = curropt->filename();
126  }
127  option_kill(option);
128 
129  double ti = timer_start();
130 
131  // Read the input files
132  int dataflag = 0;
133  if ( optind < argc - 1 || maskin.length() ) dataflag = 1;
134  Bimage* p = read_img(argv[optind++], dataflag, -1);
135 
136  if ( !p ) {
137  cerr << "Error: No input file read!" << endl;
138  bexit(-1);
139  }
140 
141  if ( !dataflag ) bexit(0);
142 
143  if ( p->standard_deviation() <= 0 ) p->statistics();
144 
145  if ( average_kernel[0] > 0 ) p->filter_average(average_kernel);
146 
147  if ( var_kernel > 1 ) p->variance(var_kernel);
148 
149  Bimage* pmask = NULL;
150 
151  if ( maskin.length() ) {
152  pmask = read_img(maskin, 1, -1);
153  if ( !p->check_if_same_size(pmask) ) {
154  cerr << "Error: The image and mask must be the same size!" << endl;
155  bexit(-1);
156  }
157  }
158 
159  vector<Bsuperpixel> seg;
160 
161  if ( segin.length() ) {
162  if ( verbose )
163  cout << "Reading " << segin << endl;
164  JSvalue sp = JSparser().parse(segin.c_str());
165  seg = superpixel_from_json(sp);
166 /* if ( pmask )
167  vector<long> vstep = {step,step,step};
168  vstep *= 2;
169  if ( vstep[2] > z ) vstep[2] = z;
170  p->superpixels_update(pmask, vstep, colorweight, seg);
171  }*/
172  } else if ( step ) {
173  if ( bin == 1 )
174  seg = p->superpixels(step, colorweight, iterations, stop);
175  else
176  seg = p->superpixels(step, colorweight, iterations, bin, stop);
177  pmask = p->next;
178  p->next = NULL;
179  }
180 
181  if ( segout.length() ) {
182  if ( verbose )
183  cout << "Writing " << segout << endl << endl;
184  JSvalue sp = json_from_superpixel(seg);
185  string fn(segout.c_str());
186  sp.write(fn);
187  }
188 
189  if ( impose ) {
190  if ( seg.size() )
191  p->impose_superpixels(pmask, seg, impose);
192  else if ( impose == 1 )
193  p->level_masked_stats(pmask);
194  }
195 
196  if ( colorize ) pmask->levelmask_colorize();
197 
198  if ( maskout.length() )
199  write_img(maskout, pmask, 0);
200 
201  // Write an output multilevel mask file if a file name is given
202  Bstring filename(argv[optind]);
203  if ( optind < argc ) {
204  p->change_type(nudatatype);
205  write_img(filename, p, 0);
206  if ( impose == 1 && p->next ) {
207  filename = filename.pre_rev('.') + "_var." + filename.post_rev('.');
208  p->next->change_type(nudatatype);
209  write_img(filename, p->next, 0);
210  }
211  }
212 
213  delete p;
214 
215  if ( verbose & VERB_TIME )
216  timer_report(ti);
217 
218  return 0;
219 }
220 
221 vector<Bsuperpixel> superpixel_from_json(JSvalue& root)
222 {
223  vector<Bsuperpixel> seg;
224 
225  vector<JSvalue> splist = root.array();
226 
227  for ( auto it = splist.begin(); it != splist.end(); ++it ) {
228  JSvalue& jv = *it;
229  Bsuperpixel sp;
230  vector<double> coor = jv["coordinates"].array_real();
231  vector<double> avg = jv["channel_averages"].array_real();
232  vector<double> var = jv["channel_variances"].array_real();
233  vector<long> nb = jv["neighbors"].array_integer();
234  sp.channels(avg.size());
235  sp.index(jv["id"].integer());
236  sp.count(jv["count"].integer());
237  sp.coordinates(coor);
238  sp.channels(avg);
239  sp.variances(var);
240  sp.weight(jv["weight"].real());
241  sp.neighbors(nb);
242  seg.push_back(sp);
243  }
244 
245  if ( verbose )
246  cout << "Superpixels: " << seg.size() << endl << endl;
247 
248  return seg;
249 }
250 
252 {
253  vector<JSvalue> vec;
254 
255  for ( long j=0; j<NNEIGHBOR && sp.neighbor(j) >= 0; ++j )
256  vec.push_back(sp.neighbor(j));
257 
258  return JSvalue(vec);
259 }
260 
261 
262 JSvalue json_from_superpixel(vector<Bsuperpixel>& seg)
263 {
264  vector<JSvalue> splist;
265 
266  for ( auto it = seg.begin(); it != seg.end(); ++it ) {
267  map<string, JSvalue> sp;
268  sp["id"] = it->index();
269  sp["count"] = it->count();
270  sp["coordinates"] = JSvalue(it->coordinates());
271  sp["channel_averages"] = JSvalue(it->channels());
272  sp["channel_variances"] = JSvalue(it->variances());
273  sp["weight"] = it->weight();
274  sp["neighbors"] = jsvalue_from_neighbors(*it);
275  splist.push_back(sp);
276  }
277 
278  return splist;
279 }
280 
Boption
A class for a command line input option.
Definition: options.h:26
Bimage::level_masked_stats
int level_masked_stats(Bimage *pmask)
Caclulates statistics for all the regions defined by a multi-level mask.
Definition: Bimage_mask.cpp:1800
Bstring
Definition: Bstring.h:29
Bsuperpixel::neighbor
void neighbor(long i, long j)
Definition: Bsuperpixel.h:59
Bsuperpixel::index
void index(long i)
Definition: Bsuperpixel.h:29
Bimage::next
Bimage * next
Definition: Bimage.h:179
Bstring::post_rev
Bstring post_rev(char c)
Definition: Bstring.cpp:436
Boption::datatype
DataType datatype()
Definition: options.h:93
Boption::next
Boption * next
Definition: options.h:28
Bimage::variance
int variance(long kernel_size, int flag=0)
Calculates the local variance within the given kernel.
Definition: Bimage_stats.cpp:625
Vector3< long >
bexit
int bexit(int value)
Exit function for cleanup and debugging.
Definition: utilities.cpp:280
Bsuperpixel
Definition: Bsuperpixel.h:15
get_option_list
Boption * get_option_list(const char *use[], int argc, char *argv[], int &optind)
Parses command line arguments based on a template.
Definition: options.cpp:40
options.h
Header file for option handlers.
Bsuperpixel::variances
void variances(vector< double > &v)
Definition: Bsuperpixel.h:46
JSparser::parse
JSvalue parse()
Definition: json.h:416
use
const char * use[]
Definition: bsupix.cpp:22
Bimage::standard_deviation
double standard_deviation()
Definition: Bimage.h:544
Bstring::c_str
const char * c_str()
Definition: Bstring.h:70
Bsuperpixel::count
void count(long i)
Definition: Bsuperpixel.h:31
JSvalue::array
vector< JSvalue > & array()
Definition: json.h:157
Boption::tag
Bstring tag
Definition: options.h:29
Boption::values
long values(T1 &v1, T2 &v2)
Definition: options.h:115
JSparser
Definition: json.h:386
read_img
Bimage * read_img(char *filename, int readdata, int img_select)
General driver function to read multiple image formats.
Definition: rwimg.cpp:77
superpixel_from_json
vector< Bsuperpixel > superpixel_from_json(JSvalue &root)
Definition: bsupix.cpp:221
write_img
int write_img(const char *filename, Bimage *p, int compression)
General driver function to write multiple image formats.
Definition: rwimg.cpp:281
Bsuperpixel::weight
void weight(double w)
Definition: Bsuperpixel.h:57
Boption::real
double real()
Definition: options.h:107
Bstring::pre_rev
Bstring pre_rev(char c)
Definition: Bstring.cpp:421
Bimage::superpixels
vector< Bsuperpixel > superpixels(long step, double colorweight=0.2, long iterations=10, double stop=1)
Segment the image into superpixels.
Definition: Bimage_segment.cpp:1872
json_from_superpixel
JSvalue json_from_superpixel(vector< Bsuperpixel > &seg)
Definition: bsupix.cpp:262
Bimage
General image parameter class.
Definition: Bimage.h:177
timer.h
Utilities for timing functions.
Bsuperpixel::coordinates
void coordinates(vector< double > &c)
Definition: Bsuperpixel.h:33
Unknown_Type
@ Unknown_Type
Definition: utilities.h:151
JSvalue
Definition: json.h:53
VERB_TIME
#define VERB_TIME
Definition: utilities.h:114
main
int main(int argc, char *argv[])
Definition: bsupix.cpp:64
JSvalue::push_back
void push_back(const JSvalue &val)
Definition: json.h:197
timer_start
double timer_start()
Starts timer and prints the time.
Definition: timer.cpp:61
NNEIGHBOR
#define NNEIGHBOR
Definition: Bsuperpixel.h:13
utilities.h
Header file for general utilities.
Bstring::length
long length() const
Definition: Bstring.cpp:263
JSvalue::array_real
vector< double > array_real()
Definition: json.h:172
Bimage::impose_superpixels
int impose_superpixels(Bimage *pmask, vector< Bsuperpixel > &seg, int impose)
Impose superpixel features onto an image.
Definition: Bimage_segment.cpp:2045
timer_report
double timer_report(double lasttime)
Reports the time elapsed since a given time.
Definition: timer.cpp:76
JSvalue::array_integer
vector< long > array_integer()
Definition: json.h:165
Bimage::change_type
void change_type(char letter)
Get the data type indicated by a single letter code.
Definition: Bimage.cpp:1765
rwimg.h
Header file for 2D and 3D image I/O.
Bimage::filter_average
int filter_average(long kernel_size)
Applies an averaging filter to an image.
Definition: Bimage_filter.cpp:207
Boption::filename
Bstring filename()
Definition: options.h:85
option_kill
int option_kill(Boption *option)
Deallocates a linked list of option structures.
Definition: options.cpp:111
Bsuperpixel::channels
void channels(long nc)
Definition: Bsuperpixel.h:35
jsvalue_from_neighbors
JSvalue jsvalue_from_neighbors(Bsuperpixel &sp)
Definition: bsupix.cpp:251
verbose
int verbose
DataType
DataType
Base data type specifier.
Definition: utilities.h:150
Bimage::levelmask_colorize
long levelmask_colorize()
Colorizes a multi-level mask with random color assignments.
Definition: Bimage_mask.cpp:2095
Bsuperpixel::neighbors
void neighbors(vector< long > &v)
Definition: Bsuperpixel.h:61
JSvalue::write
void write(string filename)
Definition: json.h:373
Bimage::statistics
long statistics()
Calculates the statistics for an image.
Definition: Bimage_stats.cpp:22
Bimage::check_if_same_size
bool check_if_same_size(Bimage *p)
Check if two images are the same size.
Definition: Bimage.cpp:566
Boption::integer
long integer()
Definition: options.h:100