1 /*
2  #
3  #  File        : curve_editor2d.cpp
4  #                ( C++ source file )
5  #
6  #  Description : A simple user interface to construct 2D spline curves.
7  #                This file is a part of the CImg Library project.
8  #                ( http://cimg.eu )
9  #
10  #  Copyright   : David Tschumperlé
11  #                ( http://tschumperle.users.greyc.fr/ )
12  #                Antonio Albiol Colomer
13  #                ( http://personales.upv.es/~aalbiol/index-english.html )
14  #
15  #  License     : CeCILL v2.0
16  #                ( http://www.cecill.info/licences/Licence_CeCILL_V2-en.html )
17  #
18  #  This software is governed by the CeCILL  license under French law and
19  #  abiding by the rules of distribution of free software.  You can  use,
20  #  modify and/ or redistribute the software under the terms of the CeCILL
21  #  license as circulated by CEA, CNRS and INRIA at the following URL
22  #  "http://www.cecill.info".
23  #
24  #  As a counterpart to the access to the source code and  rights to copy,
25  #  modify and redistribute granted by the license, users are provided only
26  #  with a limited warranty  and the software's author,  the holder of the
27  #  economic rights,  and the successive licensors  have only  limited
28  #  liability.
29  #
30  #  In this respect, the user's attention is drawn to the risks associated
31  #  with loading,  using,  modifying and/or developing or reproducing the
32  #  software by the user in light of its specific status of free software,
33  #  that may mean  that it is complicated to manipulate,  and  that  also
34  #  therefore means  that it is reserved for developers  and  experienced
35  #  professionals having in-depth computer knowledge. Users are therefore
36  #  encouraged to load and test the software's suitability as regards their
37  #  requirements in conditions enabling the security of their systems and/or
38  #  data to be ensured and,  more generally, to use and operate it in the
39  #  same conditions as regards security.
40  #
41  #  The fact that you are presently reading this means that you have had
42  #  knowledge of the CeCILL license and that you accept its terms.
43  #
44 */
45 
46 #include "CImg.h"
47 using namespace cimg_library;
48 #undef min
49 #undef max
50 
51 // Compute distance from a point to a segment.
52 //---------------------------------------------
dist_segment(const float x,const float y,const float x1,const float y1,const float x2,const float y2)53 float dist_segment(const float x, const float y, const float x1, const float y1, const float x2, const float y2) {
54   const float
55     dx = x2 - x1,
56     dy = y2 - y1,
57     long_segment = (float)std::sqrt(dx*dx + dy*dy);
58   if (long_segment==0) { const float ddx = x - x1, ddy = y - y1; return (float)std::sqrt(ddx*ddx + ddy*ddy); }
59   const float
60     unitx = dx/long_segment,
61     unity = dy/long_segment,
62     vx = x - x1,
63     vy = y - y1,
64     long_proy = vx*unitx + vy*unity,
65     proyx = x1 + long_proy*unitx,
66     proyy = y1 + long_proy*unity;
67   if (long_proy>long_segment) { const float ddx = x - x2, ddy = y - y2; return std::sqrt(ddx*ddx + ddy*ddy); }
68   else if (long_proy<0) { const float ddx = x - x1, ddy = y - y1; return std::sqrt(ddx*ddx + ddy*ddy); }
69   const float ddx = x - proyx, ddy = y - proyy;
70   return std::sqrt(ddx*ddx + ddy*ddy);
71 }
72 
73 // Main procedure
74 //---------------
main(int argc,char ** argv)75 int main(int argc, char **argv) {
76 
77   // Read command line parameters
78   //-----------------------------
79   cimg_usage("2D Spline Curve Editor");
80   const char *file_i = cimg_option("-i",(char*)0,"Input image");
81   const float contrast = cimg_option("-contrast",0.6f,"Image contrast");
82   const char *file_ip = cimg_option("-ip",(char*)0,"Input control points");
83   const char *file_oc = cimg_option("-oc",(char*)0,"Output curve points");
84   const char *file_op = cimg_option("-op",(char*)0,"Output control points");
85   const char *file_od = cimg_option("-od",(char*)0,"Output distance function");
86   bool interp = cimg_option("-poly",true,"Use polynomial interpolation");
87   bool closed = cimg_option("-closed",true,"Closed curve");
88   bool show_tangents = cimg_option("-tangents",false,"Show tangents");
89   bool show_points = cimg_option("-points",true,"Show control points");
90   bool show_outline = cimg_option("-outline",true,"Show polygon outline");
91   bool show_indices = cimg_option("-indices",true,"Show points indices");
92   bool show_coordinates = cimg_option("-coords",false,"Show points coordinates");
93   const float precision = cimg_option("-prec",0.05f,"Precision of curve discretization");
94 
95   // Init image data
96   //-----------------
97   const unsigned char yellow[] = { 255,255,0 }, white[] = { 255,255,255 }, green[] = { 0,255,0 },
98                       blue[] = { 120,200,255 }, purple[] = { 255,100,255 }, black[] = { 0,0,0 };
99   CImg<unsigned char> img0, img, help_img;
100   if (file_i) {
101     std::fprintf(stderr,"\n - Load input image '%s' : ",cimg::basename(file_i));
102     img0 = CImg<>(file_i).normalize(0,255.0f*contrast);
103     std::fprintf(stderr,"Size = %dx%dx%dx%d \n",img0.width(),img0.height(),img0.depth(),img0.spectrum());
104     img0.resize(-100,-100,1,3);
105   }
106   else {
107     std::fprintf(stderr,"\n - No input image specified, use default 512x512 image.\n");
108     img0.assign(512,512,1,3,0).draw_grid(32,32,0,0,false,false,green,0.4f,0xCCCCCCCC,0xCCCCCCCC);
109   }
110 
111   help_img.assign(220,210,1,3,0).
112     draw_text(5,5,
113               "------------------------------------------\n"
114               "2D Curve Editor\n"
115               "------------------------------------------\n"
116               "Left button : Create or move control point\n"
117               "Right button : Delete control point\n"
118               "Spacebar : Switch interpolation\n"
119               "Key 'C' : Switch open/closed mode\n"
120               "Key 'T' : Show/hide tangents\n"
121               "Key 'P' : Show/hide control points\n"
122               "Key 'O' : Show/hide polygon outline\n"
123               "Key 'N' : Show/hide points indices\n"
124               "Key 'X' : Show/hide points coordinates\n"
125               "Key 'H' : Show/hide this help\n"
126               "Key 'S' : Save control points\n"
127               "Key 'R' : Reset curve\n",
128               green);
129   CImgDisplay disp(img0,"2D Curve Editor",0);
130   CImgList<float> points, curve;
131   bool moving = false, help = !file_i;
132 
133   if (file_ip) {
134     std::fprintf(stderr," - Load input control points '%s' : ",cimg::basename(file_ip));
135     points = CImg<>(file_ip).transpose()<'x';
136     std::fprintf(stderr," %u points\n",points.size());
137   }
138 
139   // Enter interactive loop
140   //------------------------
141   while (!disp.is_closed() && !disp.is_keyESC() && !disp.is_keyQ()) {
142 
143     // Handle mouse manipulation
144     //---------------------------
145     const unsigned int button = disp.button();
146     const float
147       mx = disp.mouse_x()*(float)img0.width()/disp.width(),
148       my = disp.mouse_y()*(float)img0.height()/disp.height();
149 
150     if (points && button && mx>=0 && my>=0) {
151 
152       // Find nearest point and nearest segment
153       float dmin_pt = cimg::type<float>::max(), dmin_seg = dmin_pt;
154       unsigned int p_pt = 0, p_seg = 0;
155       cimglist_for(points,p) {
156         const unsigned int
157           pnext = closed?(p + 1)%points.size():(p + 1<(int)points.size()?p + 1:p);
158         const float
159           xp = points(p,0),
160           yp = points(p,1);
161         const float
162           d_pt  = (xp - mx)*(xp - mx) + (yp - my)*(yp - my),
163 	  d_seg = dist_segment(mx,my,xp,yp,points(pnext,0),points(pnext,1));
164         if (d_pt<dmin_pt)   { dmin_pt = d_pt; p_pt = p; }
165         if (d_seg<dmin_seg) { dmin_seg = d_seg; p_seg = p; }
166       }
167 
168       // Handle button
169       if (button&1) {
170         if (dmin_pt<100 || moving) { points(p_pt,0) = mx; points(p_pt,1) = my; }
171         else points.insert(CImg<>::vector(mx,my),p_seg + 1);
172         moving = true;
173       }
174       if (button&2 && dmin_pt<100) {
175         if (points.size()>3) points.remove(p_pt);
176         disp.set_button();
177       }
178     }
179     if (!button) moving = false;
180 
181     if (disp.key()) {
182       switch (disp.key()) {
183       case cimg::keySPACE : interp = !interp; break;
184       case cimg::keyC : closed = !closed; break;
185       case cimg::keyT : show_tangents = !show_tangents; break;
186       case cimg::keyP : show_points = !show_points; break;
187       case cimg::keyO : show_outline = !show_outline; break;
188       case cimg::keyN : show_indices = !show_indices; break;
189       case cimg::keyX : show_coordinates = !show_coordinates; break;
190       case cimg::keyR : points.assign(); break;
191       case cimg::keyH : help = !help; break;
192       case cimg::keyS : {
193         const char *filename = file_op?file_op:"curve_points.dlm";
194         std::fprintf(stderr," - Save control points in '%s'\n",filename);
195         (points>'x').transpose().save(filename);
196       } break;
197       }
198       disp.set_key();
199     }
200 
201     // Init list of points if empty
202     //------------------------------
203     if (!points) {
204       const float
205         x0 = img0.width()/4.0f,
206         y0 = img0.height()/4.0f,
207         x1 = img0.width() - x0,
208         y1 = img0.height() - y0;
209       points.insert(CImg<>::vector(x0,y0)).
210         insert(CImg<>::vector(x1,y0)).
211         insert(CImg<>::vector(x1,y1)).
212         insert(CImg<>::vector(x0,y1));
213     }
214 
215     // Estimate curve tangents
216     //-------------------------
217     CImg<> tangents(points.size(),2);
218     cimglist_for(points,p) {
219       const unsigned int
220         p0 = closed?(p + points.size() - 1)%points.size():(p?p - 1:0),
221         p1 = closed?(p + 1)%points.size():(p + 1<(int)points.size()?p + 1:p);
222       const float
223         x  = points(p,0),
224         y  = points(p,1),
225         x0 = points(p0,0),
226         y0 = points(p0,1),
227         x1 = points(p1,0),
228         y1 = points(p1,1),
229         u0 = x - x0,
230         v0 = y - y0,
231         n0 = 1e-8f + (float)std::sqrt(u0*u0 + v0*v0),
232         u1 = x1 - x,
233         v1 = y1 - y,
234         n1 = 1e-8f + (float)std::sqrt(u1*u1 + v1*v1),
235         u = u0/n0 + u1/n1,
236         v = v0/n0 + v1/n1,
237         n = 1e-8f + (float)std::sqrt(u*u + v*v),
238         fact = 0.5f*(n0 + n1);
239       tangents(p,0) = fact*u/n;
240       tangents(p,1) = fact*v/n;
241     }
242 
243     // Estimate 3th-order polynomial interpolation
244     //---------------------------------------------
245     curve.assign();
246     const unsigned int pmax = points.size() - (closed?0:1);
247     for (unsigned int p0 = 0; p0<pmax; p0++) {
248       const unsigned int
249         p1 = closed?(p0 + 1)%points.size():(p0 + 1<points.size()?p0 + 1:p0);
250       const float
251         x0 = points(p0,0),
252         y0 = points(p0,1),
253         x1 = points(p1,0),
254         y1 = points(p1,1);
255       float ax = 0, bx = 0, cx = 0, dx = 0, ay = 0, by = 0, cy = 0, dy = 0;
256       if (interp) {
257         const float
258           u0 = tangents(p0,0),
259           v0 = tangents(p0,1),
260           u1 = tangents(p1,0),
261           v1 = tangents(p1,1);
262         ax = 2*(x0 - x1) + u0 + u1;
263         bx = 3*(x1 - x0) - 2*u0 - u1;
264         cx = u0;
265         dx = x0;
266         ay = 2*(y0 - y1) + v0 + v1;
267         by = 3*(y1 - y0) - 2*v0 - v1;
268         cy = v0;
269         dy = y0;
270       } else {
271         ax = ay = bx = by = 0;
272         dx = x0;
273         dy = y0;
274         cx = x1 - x0;
275         cy = y1 - y0;
276       }
277       const float tmax = 1 + precision;
278       for (float t = 0; t<tmax; t+=precision) {
279         const float
280           xt = ax*t*t*t + bx*t*t + cx*t + dx,
281           yt = ay*t*t*t + by*t*t + cy*t + dy;
282         curve.insert(CImg<>::vector(xt,yt));
283       }
284     }
285 
286     // Draw curve and display image
287     //-------------------------------
288     const float
289       factx = (float)disp.width()/img0.width(),
290       facty = (float)disp.height()/img0.height();
291     img = img0.get_resize(disp.width(),disp.height());
292     if (help) img.draw_image(help_img,0.6f);
293     if (interp && show_outline) {
294       CImg<> npoints = points>'x';
295       npoints.get_shared_row(0)*=factx;
296       npoints.get_shared_row(1)*=facty;
297       img.draw_polygon(npoints,blue,0.4f);
298       if (closed) img.draw_polygon(npoints,yellow,0.8f,0x11111111);
299       else img.draw_line(npoints,yellow,0.8f,0x11111111);
300     }
301     CImg<> ncurve = curve>'x';
302     ncurve.get_shared_row(0)*=factx;
303     ncurve.get_shared_row(1)*=facty;
304     if (closed) img.draw_polygon(ncurve,white,1.0f,~0U);
305     else img.draw_line(ncurve,white);
306 
307     if (show_points) cimglist_for(points,p) {
308       const float
309         x = points(p,0)*factx,
310         y = points(p,1)*facty;
311       if (show_tangents) {
312         const float
313           u = tangents(p,0),
314           v = tangents(p,1),
315           n = 1e-8f + (float)std::sqrt(u*u + v*v),
316           nu = u/n,
317           nv = v/n;
318         img.draw_arrow((int)(x - 15*nu),(int)(y - 15*nv),(int)(x + 15*nu),(int)(y + 15*nv),green);
319       }
320       if (show_indices) img.draw_text((int)x,(int)(y - 16),"%d",purple,black,1,13,p);
321       if (show_coordinates)
322         img.draw_text((int)(x - 24),(int)(y + 8),"(%d,%d)",yellow,black,0.5f,13,(int)points(p,0),(int)points(p,1));
323       img.draw_circle((int)x,(int)y,3,blue,0.7f);
324     }
325 
326     img.display(disp);
327     disp.wait();
328 
329     if (disp.is_resized()) disp.resize(false);
330   }
331 
332   // Save output result and exit
333   //-----------------------------
334   if (file_op) {
335     std::fprintf(stderr," - Save control points in '%s'\n",cimg::basename(file_op));
336     (points>'x').transpose().save(file_op);
337   }
338   if (file_oc) {
339     std::fprintf(stderr," - Save curve points in '%s'\n",cimg::basename(file_oc));
340     (curve>'x').transpose().save(file_oc);
341   }
342   if (file_od) {
343     std::fprintf(stderr," - Computing distance function, please wait...."); std::fflush(stderr);
344     CImg<> ncurve = (closed?(+curve).insert(curve[0]):curve)>'x';
345     const float zero = 0.0f, one = 1.0f;
346     CImg<> distance =
347       CImg<>(img0.width(),img0.height(),1,1,-1.0f).draw_line(ncurve,&zero).draw_fill(0,0,&one).
348       distance(0);
349     std::fprintf(stderr,"\n - Save distance function in '%s'\n",cimg::basename(file_od));
350     distance.save(file_od);
351   }
352 
353   std::fprintf(stderr," - Exit.\n");
354   std::exit(0);
355   return 0;
356 }
357