Commit message: .
CVE: CVE-2019-13568
CWE: CWE-787
Vulnerability description: CImg through 2.6.7 has a heap-based buffer overflow in _load_bmp in CImg.h because of erroneous memory allocation for a malformed BMP image.

Project: CImg
File: CImg.h

    //! Fill sequentially all pixel values with specified values \overloading.
    CImg<T>& fill(const T& val0, const T& val1, const T& val2, const T& val3, const T& val4, const T& val5,
                  const T& val6, const T& val7, const T& val8, const T& val9, const T& val10, const T& val11,
                  const T& val12, const T& val13, const T& val14, const T& val15) {
      if (is_empty()) return *this;
      T *ptrd, *ptre = end() - 15;
      for (ptrd = _data; ptrd<ptre; ) {
        *(ptrd++) = val0; *(ptrd++) = val1; *(ptrd++) = val2; *(ptrd++) = val3; *(ptrd++) = val4; *(ptrd++) = val5;
        *(ptrd++) = val6; *(ptrd++) = val7; *(ptrd++) = val8; *(ptrd++) = val9; *(ptrd++) = val10; *(ptrd++) = val11;
        *(ptrd++) = val12; *(ptrd++) = val13; *(ptrd++) = val14; *(ptrd++) = val15;
      }
      ptre+=15;
      switch (ptre - ptrd) {
      case 15 : *(--ptre) = val14; // fallthrough
      case 14 : *(--ptre) = val13; // fallthrough
      case 13 : *(--ptre) = val12; // fallthrough
      case 12 : *(--ptre) = val11; // fallthrough
      case 11 : *(--ptre) = val10; // fallthrough
      case 10 : *(--ptre) = val9; // fallthrough
      case 9 : *(--ptre) = val8; // fallthrough
      case 8 : *(--ptre) = val7; // fallthrough
      case 7 : *(--ptre) = val6; // fallthrough
      case 6 : *(--ptre) = val5; // fallthrough
      case 5 : *(--ptre) = val4; // fallthrough
      case 4 : *(--ptre) = val3; // fallthrough
      case 3 : *(--ptre) = val2; // fallthrough
      case 2 : *(--ptre) = val1; // fallthrough
      case 1 : *(--ptre) = val0; // fallthrough
      }
      return *this;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T> get_fill(const CImg<t>& values, const bool repeat_values=true) const {
      return repeat_values?CImg<T>(_width,_height,_depth,_spectrum).fill(values,repeat_values):
        (+*this).fill(values,repeat_values);

Project: CImg
File: CImg.h

    **/
    Tfloat cubic_atXY(const float fx, const float fy, const int z=0, const int c=0) const {
      if (is_empty())
        throw CImgInstanceException(_cimg_instance
                                    "cubic_atXY(): Empty instance.",
                                    cimg_instance);
      return _cubic_atXY(fx,fy,z,c);

Project: CImg
File: CImg.h


      static double mp_argmin(_cimg_math_parser& mp) {
        const unsigned int i_end = (unsigned int)mp.opcode[2];
        double val = _mp_arg(3);
        unsigned int argval = 0;
        for (unsigned int i = 4; i<i_end; ++i) {
          const double _val = _mp_arg(i);
          if (_val<val) { val = _val; argval = i - 3; }
        }
        return (double)argval;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& resize(const CImg<t>& src,
                    const int interpolation_type=1, const unsigned int boundary_conditions=0,
                    const float centering_x = 0, const float centering_y = 0,
                    const float centering_z = 0, const float centering_c = 0) {
      return resize(src._width,src._height,src._depth,src._spectrum,interpolation_type,boundary_conditions,
                    centering_x,centering_y,centering_z,centering_c);

Project: CImg
File: CImg.h

    //! Autocrop image region, regarding the specified background value.
    CImg<T>& autocrop(const T& value, const char *const axes="czyx") {
      if (is_empty()) return *this;
      for (const char *s = axes; *s; ++s) {
        const char axis = cimg::lowercase(*s);
        const CImg<intT> coords = _autocrop(value,axis);
        if (coords[0]==-1 && coords[1]==-1) return assign(); // Image has only 'value' pixels
        else switch (axis) {
        case 'x' : {
	  const int x0 = coords[0], x1 = coords[1];
	  if (x0>=0 && x1>=0) crop(x0,x1);
	} break;
        case 'y' : {
	  const int y0 = coords[0], y1 = coords[1];
	  if (y0>=0 && y1>=0) crop(0,y0,_width - 1,y1);
	} break;
        case 'z' : {
	  const int z0 = coords[0], z1 = coords[1];
	  if (z0>=0 && z1>=0) crop(0,0,z0,_width - 1,_height - 1,z1);
	} break;
        default : {
	  const int c0 = coords[0], c1 = coords[1];
	  if (c0>=0 && c1>=0) crop(0,0,0,c0,_width - 1,_height - 1,_depth - 1,c1);
	}
        }
      }
      return *this;

Project: CImg
File: CImg.h

    //! Convert pixel values from HSV to RGB color spaces \newinstance.
    CImg<Tuchar> get_HSVtoRGB() const {
      return CImg<Tuchar>(*this,false).HSVtoRGB();

Project: CImg
File: CImg.h

    template<typename tp, typename tc, typename to>
    CImg<T> get_CImg3dtoobject3d(CImgList<tp>& primitives,
                                 CImgList<tc>& colors,
                                 CImgList<to>& opacities,
                                 const bool full_check=true) const {
      CImg<charT> error_message(1024);
      if (!is_CImg3d(full_check,error_message))
        throw CImgInstanceException(_cimg_instance
                                    "CImg3dtoobject3d(): image instance is not a CImg3d (%s).",
                                    cimg_instance,error_message.data());
      const T *ptrs = _data + 6;
      const unsigned int
        nb_points = cimg::float2uint((float)*(ptrs++)),
        nb_primitives = cimg::float2uint((float)*(ptrs++));
      const CImg<T> points = CImg<T>(ptrs,3,nb_points,1,1,true).get_transpose();
      ptrs+=3*nb_points;
      primitives.assign(nb_primitives);
      cimglist_for(primitives,p) {
        const unsigned int nb_inds = (unsigned int)*(ptrs++);
        primitives[p].assign(1,nb_inds);
        tp *ptrp = primitives[p]._data;
        for (unsigned int i = 0; i<nb_inds; ++i) *(ptrp++) = (tp)cimg::float2uint((float)*(ptrs++));
      }
      colors.assign(nb_primitives);
      cimglist_for(colors,c) {
        if (*ptrs==(T)-128) {
          ++ptrs;
          const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++);
          if (!h && !s) colors[c].assign(colors[w],true);
          else { colors[c].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; }
        } else { colors[c].assign(ptrs,1,1,1,3,false); ptrs+=3; }
      }
      opacities.assign(nb_primitives);
      cimglist_for(opacities,o) {
        if (*ptrs==(T)-128) {
          ++ptrs;
          const unsigned int w = (unsigned int)*(ptrs++), h = (unsigned int)*(ptrs++), s = (unsigned int)*(ptrs++);
          if (!h && !s) opacities[o].assign(opacities[w],true);
          else { opacities[o].assign(ptrs,w,h,1,s,false); ptrs+=w*h*s; }
        } else opacities[o].assign(1,1,1,1,*(ptrs++));
      }
      return points;

Project: CImg
File: CImg.h

    template<typename tp>
    const CImg<T>& display_object3d(const char *const title,
				    const CImg<tp>& vertices,
                                    const bool centering=true,
                                    const int render_static=4, const int render_motion=1,
                                    const bool is_double_sided=true, const float focale=700,
                                    const float light_x=0, const float light_y=0, const float light_z=-5e8f,
                                    const float specular_lightness=0.2f, const float specular_shininess=0.1f,
                                    const bool display_axes=true, float *const pose_matrix=0,
                                    const bool exit_on_anykey=false) const {
      return display_object3d(title,vertices,CImgList<uintT>(),centering,
                              render_static,render_motion,is_double_sided,focale,
                              light_x,light_y,light_z,specular_lightness,specular_shininess,
                              display_axes,pose_matrix,exit_on_anykey);

Project: CImg
File: CImg.h


    const CImg<T>& _save_dlm(std::FILE *const file, const char *const filename) const {
      if (!file && !filename)
        throw CImgArgumentException(_cimg_instance
                                    "save_dlm(): Specified filename is (null).",
                                    cimg_instance);
      if (is_empty()) { cimg::fempty(file,filename); return *this; }
      if (_depth>1)
        cimg::warn(_cimg_instance
                   "save_dlm(): Instance is volumetric, values along Z will be unrolled in file '%s'.",
                   cimg_instance,
                   filename?filename:"(FILE*)");
      if (_spectrum>1)
        cimg::warn(_cimg_instance
                   "save_dlm(): Instance is multispectral, values along C will be unrolled in file '%s'.",
                   cimg_instance,
                   filename?filename:"(FILE*)");

      std::FILE *const nfile = file?file:cimg::fopen(filename,"w");
      const T* ptrs = _data;
      cimg_forYZC(*this,y,z,c) {
        cimg_forX(*this,x) std::fprintf(nfile,"%.17g%s",(double)*(ptrs++),(x==width() - 1)?"":",");
        std::fputc('\n',nfile);
      }
      if (!file) cimg::fclose(nfile);
      return *this;

Project: CImg
File: CImg.h

    template<typename t>
    inline t min(const t& a, const t& b, const t& c, const t& d) {
      return std::min(std::min(a,b),std::min(c,d));

Project: CImg
File: CImg.h


      static double mp_permutations(_cimg_math_parser& mp) {
        return cimg::permutations((int)_mp_arg(2),(int)_mp_arg(3),(bool)_mp_arg(4));

Project: CImg
File: CImg.h

    //! Convert pixel values from XYZ to Lab color spaces.
    CImg<T>& XYZtoLab(const bool use_D65=true) {
#define _cimg_Labf(x) (24389*(x)>216?cimg::cbrt(x):(24389*(x)/27 + 16)/116)

      if (_spectrum!=3)
        throw CImgInstanceException(_cimg_instance
                                    "XYZtoLab(): Instance is not a XYZ image.",
                                    cimg_instance);
      const CImg<Tfloat> white = CImg<Tfloat>(1,1,1,3,255).RGBtoXYZ(use_D65);
      T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2);
      const longT whd = (longT)width()*height()*depth();
      cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,128))
      for (longT N = 0; N<whd; ++N) {
        const Tfloat
          X = (Tfloat)(p1[N]/white[0]),
          Y = (Tfloat)(p2[N]/white[1]),
          Z = (Tfloat)(p3[N]/white[2]),
          fX = (Tfloat)_cimg_Labf(X),
          fY = (Tfloat)_cimg_Labf(Y),
          fZ = (Tfloat)_cimg_Labf(Z);
        p1[N] = (T)cimg::cut(116*fY - 16,0,100);
        p2[N] = (T)(500*(fX - fY));
        p3[N] = (T)(200*(fY - fZ));
      }
      return *this;

Project: CImg
File: CImg.h


    const T& operator()(const unsigned int x) const {
      return _data[x];

Project: CImg
File: CImg.h

    template<typename t1, typename t2, typename t3>
    CImgList(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const bool is_shared=false):
      _width(0),_allocated_width(0),_data(0) {
      assign(3);
      _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared);

Project: CImg
File: CImg.h


    CImgDisplay& assign(const unsigned int dimw, const unsigned int dimh, const char *const title=0,
                        const unsigned int normalization_type=3,
                        const bool fullscreen_flag=false, const bool closed_flag=false) {
      if (!dimw || !dimh) return assign();
      _assign(dimw,dimh,title,normalization_type,fullscreen_flag,closed_flag);
      _min = _max = 0;
      std::memset(_data,0,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char):
                           (cimg::X11_attr().nb_bits==16?sizeof(unsigned short):sizeof(unsigned int)))*
                  (size_t)_width*_height);
      return paint();

Project: CImg
File: CImg.h

    //! Load image from a DLM file \newinstance.
    static CImg<T> get_load_dlm(std::FILE *const file) {
      return CImg<T>().load_dlm(file);

Project: CImg
File: CImg.h

    //! Sharpen image \newinstance.
    CImg<T> get_sharpen(const float amplitude, const bool sharpen_type=false, const float edge=1,
                        const float alpha=0, const float sigma=0) const {
      return (+*this).sharpen(amplitude,sharpen_type,edge,alpha,sigma);

Project: CImg
File: CImg.h

    **/
    CImg<T>& haar(const bool invert=false, const unsigned int nb_scales=1) {
      return get_haar(invert,nb_scales).move_to(*this);

Project: CImg
File: CImg.h

    **/
    bool operator!=(const char *const expression) const {
      return !((*this)==expression);

Project: CImg
File: CImg.h

     **/
    CImg<T>& tensor() {
      return get_tensor().move_to(*this);

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_gif_external(const char *const filename,
                               const char axis='z', const float align=0) {
      return get_load_gif_external(filename,axis,align).move_to(*this);

Project: CImg
File: CImg.h

    //! Load image from a JPEG file \newinstance.
    static CImg<T> get_load_jpeg(std::FILE *const file) {
      return CImg<T>().load_jpeg(file);

Project: CImg
File: CImg.h

    template<typename tc1, typename tc2, typename t>
    CImg<T>& draw_text(const int x0, const int y0,
                       const char *const text,
                       const tc1 *const foreground_color, const tc2 *const background_color,
                       const float opacity, const CImgList<t>& font, ...) {
      if (!font) return *this;
      CImg<charT> tmp(2048);
      std::va_list ap; va_start(ap,font);
      cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap);
      return _draw_text(x0,y0,tmp,foreground_color,background_color,opacity,font,false);

Project: CImg
File: CImg.h

    **/
    CImg<T>& min(const char *const expression) {
      return min((+*this)._fill(expression,true,1,0,0,"min",this));

Project: CImg
File: CImg.h

    **/
    CImgDisplay& show() {
      return assign();

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_cimg(const char *const filename, const char axis='z', const float align=0) {
      CImgList<T> list;
      list.load_cimg(filename);
      if (list._width==1) return list[0].move_to(*this);
      return assign(list.get_append(axis,align));

Project: CImg
File: CImg.h

     **/
    const CImg<T>& save_tiff(const char *const filename, const unsigned int compression_type=0,
                             const float *const voxel_size=0, const char *const description=0,
                             const bool use_bigtiff=true) const {
      if (!filename)
        throw CImgArgumentException(_cimg_instance
                                    "save_tiff(): Specified filename is (null).",
                                    cimg_instance);
      if (is_empty()) { cimg::fempty(0,filename); return *this; }

#ifdef cimg_use_tiff
      const bool
        _use_bigtiff = use_bigtiff && sizeof(ulongT)>=8 && size()*sizeof(T)>=1UL<<31; // No bigtiff for small images
      TIFF *tif = TIFFOpen(filename,_use_bigtiff?"w8":"w4");
      if (tif) {
        cimg_forZ(*this,z) _save_tiff(tif,z,z,compression_type,voxel_size,description);
        TIFFClose(tif);
      } else throw CImgIOException(_cimg_instance
                                   "save_tiff(): Failed to open file '%s' for writing.",
                                   cimg_instance,
                                   filename);
      return *this;
#else
      cimg::unused(compression_type,voxel_size,description,use_bigtiff);
      return save_other(filename);
#endif

Project: CImg
File: CImg.h

    **/
    CImgDisplay& set_button() {
      _button = 0;
      _is_event = true;
#if cimg_display==1
      pthread_cond_broadcast(&cimg::X11_attr().wait_event);
#elif cimg_display==2
      SetEvent(cimg::Win32_attr().wait_event);
#endif
      return *this;

Project: CImg
File: CImg.h

    //! Draw an image \specialization.
    CImg<T>& draw_image(const int x0, const int y0, const int z0, const int c0,
                        const CImg<T>& sprite, const float opacity=1) {
      if (is_empty() || !sprite) return *this;
      if (is_overlapped(sprite)) return draw_image(x0,y0,z0,c0,+sprite,opacity);
      if (x0==0 && y0==0 && z0==0 && c0==0 && is_sameXYZC(sprite) && opacity>=1 && !is_shared())
        return assign(sprite,false);
      const bool bx = (x0<0), by = (y0<0), bz = (z0<0), bc = (c0<0);
      const int
        lX = sprite.width() - (x0 + sprite.width()>width()?x0 + sprite.width() - width():0) + (bx?x0:0),
        lY = sprite.height() - (y0 + sprite.height()>height()?y0 + sprite.height() - height():0) + (by?y0:0),
        lZ = sprite.depth() - (z0 + sprite.depth()>depth()?z0 + sprite.depth() - depth():0) + (bz?z0:0),
        lC = sprite.spectrum() - (c0 + sprite.spectrum()>spectrum()?c0 + sprite.spectrum() - spectrum():0) + (bc?c0:0);
      const T
        *ptrs = sprite._data +
        (bx?-x0:0) +
        (by?-y0*(ulongT)sprite.width():0) +
        (bz?-z0*(ulongT)sprite.width()*sprite.height():0) +
        (bc?-c0*(ulongT)sprite.width()*sprite.height()*sprite.depth():0);
      const ulongT
        offX = (ulongT)_width - lX,
        soffX = (ulongT)sprite._width - lX,
        offY = (ulongT)_width*(_height - lY),
        soffY = (ulongT)sprite._width*(sprite._height - lY),
        offZ = (ulongT)_width*_height*(_depth - lZ),
        soffZ = (ulongT)sprite._width*sprite._height*(sprite._depth - lZ),
        slX = lX*sizeof(T);
      const float nopacity = cimg::abs(opacity), copacity = 1 - std::max(opacity,0.f);
      if (lX>0 && lY>0 && lZ>0 && lC>0) {
        T *ptrd = data(x0<0?0:x0,y0<0?0:y0,z0<0?0:z0,c0<0?0:c0);
        for (int v = 0; v<lC; ++v) {
          for (int z = 0; z<lZ; ++z) {
            if (opacity>=1)
              for (int y = 0; y<lY; ++y) { std::memcpy(ptrd,ptrs,slX); ptrd+=_width; ptrs+=sprite._width; }
            else for (int y = 0; y<lY; ++y) {
                for (int x = 0; x<lX; ++x) { *ptrd = (T)(nopacity*(*(ptrs++)) + *ptrd*copacity); ++ptrd; }
                ptrd+=offX; ptrs+=soffX;
              }
            ptrd+=offY; ptrs+=soffY;
          }
          ptrd+=offZ; ptrs+=soffZ;
        }
      }
      return *this;

Project: CImg
File: CImg.h

    template<typename tf>
    static CImg<floatT> torus3d(CImgList<tf>& primitives,
                                const float radius1=100, const float radius2=30,
                                const unsigned int subdivisions1=24, const unsigned int subdivisions2=12) {
      primitives.assign();
      if (!subdivisions1 || !subdivisions2) return CImg<floatT>();
      CImgList<floatT> vertices;
      for (unsigned int v = 0; v<subdivisions1; ++v) {
	const float
	  beta = (float)(v*2*cimg::PI/subdivisions1),
	  xc = radius1*(float)std::cos(beta),
	  yc = radius1*(float)std::sin(beta);
        for (unsigned int u = 0; u<subdivisions2; ++u) {
          const float
            alpha = (float)(u*2*cimg::PI/subdivisions2),
            x = xc + radius2*(float)(std::cos(alpha)*std::cos(beta)),
	    y = yc + radius2*(float)(std::cos(alpha)*std::sin(beta)),
	    z = radius2*(float)std::sin(alpha);
          CImg<floatT>::vector(x,y,z).move_to(vertices);
        }
      }
      for (unsigned int vv = 0; vv<subdivisions1; ++vv) {
	const unsigned int nv = (vv + 1)%subdivisions1;
        for (unsigned int uu = 0; uu<subdivisions2; ++uu) {
          const unsigned int nu = (uu + 1)%subdivisions2, svv = subdivisions2*vv, snv = subdivisions2*nv;
          CImg<tf>::vector(svv + nu,svv + uu,snv + uu,snv + nu).move_to(primitives);
        }
      }
      return vertices>'x';

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T> operator|(const t value) const {
      return (+*this)|=value;

Project: CImg
File: CImg.h

    **/
    inline std::FILE* output(std::FILE *file) {
      cimg::mutex(1);
      static std::FILE *res = cimg::_stderr();
      if (file) res = file;
      cimg::mutex(1,0);
      return res;

Project: CImg
File: CImg.h

    */
    static void _cimg_blur_box_apply(T *ptr, const float boxsize, const int N, const ulongT off,
                                     const int order, const bool boundary_conditions,
                                     const unsigned int nb_iter) {
      // Smooth.
      if (boxsize>1 && nb_iter) {
        const int w2 = (int)(boxsize - 1)/2;
        const unsigned int winsize = 2*w2 + 1U;
        const double frac = (boxsize - winsize)/2.;
        CImg<T> win(winsize);
        for (unsigned int iter = 0; iter<nb_iter; ++iter) {
          Tdouble sum = 0; // window sum
          for (int x = -w2; x<=w2; ++x) {
            win[x + w2] = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x);
            sum+=win[x + w2];
          }
          int ifirst = 0, ilast = 2*w2;
          T
            prev = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-w2 - 1),
            next = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,w2 + 1);
          for (int x = 0; x < N - 1; ++x) {
            const double sum2 = sum + frac * (prev + next);
            ptr[x*off] = (T)(sum2/boxsize);
            prev = win[ifirst];
            sum-=prev;
            ifirst = (int)((ifirst + 1)%winsize);
            ilast = (int)((ilast + 1)%winsize);
            win[ilast] = next;
            sum+=next;
            next = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + w2 + 2);
          }
          const double sum2 = sum + frac * (prev + next);
          ptr[(N - 1)*off] = (T)(sum2/boxsize);
        }
      }

      // Derive.
      switch (order) {
      case 0 :
        break;
      case 1 : {
        Tfloat
          p = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-1),
          c = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,0),
          n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,1);
        for (int x = 0; x<N - 1; ++x) {
          ptr[x*off] = (T)((n-p)/2.);
          p = c;
          c = n;
          n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + 2);
        }
        ptr[(N - 1)*off] = (T)((n-p)/2.);
      } break;
      case 2: {
        Tfloat
          p = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,-1),
          c = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,0),
          n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,1);
        for (int x = 0; x<N - 1; ++x) {
          ptr[x*off] = (T)(n - 2*c + p);
          p = c;
          c = n;
          n = __cimg_blur_box_apply(ptr,N,off,boundary_conditions,x + 2);
        }
        ptr[(N - 1)*off] = (T)(n - 2*c + p);
      } break;
      }

Project: CImg
File: CImg.h


    inline float uint2float(const unsigned int u) {
      if (u<(1U<<19)) return (float)u;  // Consider safe storage of unsigned int as floats until 19bits (i.e 524287)
      float f;
      const unsigned int v = u|(1U<<(8*sizeof(unsigned int)-1)); // set sign bit to 1
      // use memcpy instead of simple assignment to avoid undesired optimizations by C++-compiler.
      std::memcpy(&f,&v,sizeof(float));
      return f;

Project: CImg
File: CImg.h

    //! Fill sequentially all pixel values with specified values \newinstance.
    CImg<T> get_fill(const T& val0, const T& val1, const T& val2, const T& val3) const {
      return CImg<T>(_width,_height,_depth,_spectrum).fill(val0,val1,val2,val3);

Project: CImg
File: CImg.h

    **/
    CImg<T> rotate(const float u, const float v, const float w, const float angle,
                   const float cx, const float cy, const float cz,
                   const unsigned int interpolation=1, const unsigned int boundary_conditions=0) {
      const float nangle = cimg::mod(angle,360.f);
      if (nangle==0.f) return *this;
      return get_rotate(u,v,w,nangle,cx,cy,cz,interpolation,boundary_conditions).move_to(*this);

Project: CImg
File: CImg.h

      static float cut(const double val) { return (float)val; }

Project: CImg
File: CImg.h

    // (Note: Most of this function has been written by Eric Fausett)
    CImg<T>& _load_png(std::FILE *const file, const char *const filename, unsigned int *const bits_per_pixel) {
      if (!file && !filename)
        throw CImgArgumentException(_cimg_instance
                                    "load_png(): Specified filename is (null).",
                                    cimg_instance);

#ifndef cimg_use_png
      cimg::unused(bits_per_pixel);
      if (file)
        throw CImgIOException(_cimg_instance
                              "load_png(): Unable to load data from '(FILE*)' unless libpng is enabled.",
                              cimg_instance);

      else return load_other(filename);
#else
      // Open file and check for PNG validity
#if defined __GNUC__
      const char *volatile nfilename = filename; // Use 'volatile' to avoid (wrong) g++ warning
      std::FILE *volatile nfile = file?file:cimg::fopen(nfilename,"rb");
#else
      const char *nfilename = filename;
      std::FILE *nfile = file?file:cimg::fopen(nfilename,"rb");
#endif
      unsigned char pngCheck[8] = { 0 };
      cimg::fread(pngCheck,8,(std::FILE*)nfile);
      if (png_sig_cmp(pngCheck,0,8)) {
        if (!file) cimg::fclose(nfile);
        throw CImgIOException(_cimg_instance
                              "load_png(): Invalid PNG file '%s'.",
                              cimg_instance,
                              nfilename?nfilename:"(FILE*)");
      }

      // Setup PNG structures for read
      png_voidp user_error_ptr = 0;
      png_error_ptr user_error_fn = 0, user_warning_fn = 0;
      png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING,user_error_ptr,user_error_fn,user_warning_fn);
      if (!png_ptr) {
        if (!file) cimg::fclose(nfile);
        throw CImgIOException(_cimg_instance
                              "load_png(): Failed to initialize 'png_ptr' structure for file '%s'.",
                              cimg_instance,
                              nfilename?nfilename:"(FILE*)");
      }
      png_infop info_ptr = png_create_info_struct(png_ptr);
      if (!info_ptr) {
        if (!file) cimg::fclose(nfile);
        png_destroy_read_struct(&png_ptr,(png_infopp)0,(png_infopp)0);
        throw CImgIOException(_cimg_instance
                              "load_png(): Failed to initialize 'info_ptr' structure for file '%s'.",
                              cimg_instance,
                              nfilename?nfilename:"(FILE*)");
      }
      png_infop end_info = png_create_info_struct(png_ptr);
      if (!end_info) {
        if (!file) cimg::fclose(nfile);
        png_destroy_read_struct(&png_ptr,&info_ptr,(png_infopp)0);
        throw CImgIOException(_cimg_instance
                              "load_png(): Failed to initialize 'end_info' structure for file '%s'.",
                              cimg_instance,
                              nfilename?nfilename:"(FILE*)");
      }

      // Error handling callback for png file reading
      if (setjmp(png_jmpbuf(png_ptr))) {
        if (!file) cimg::fclose((std::FILE*)nfile);
        png_destroy_read_struct(&png_ptr, &end_info, (png_infopp)0);
        throw CImgIOException(_cimg_instance
                              "load_png(): Encountered unknown fatal error in libpng for file '%s'.",
                              cimg_instance,
                              nfilename?nfilename:"(FILE*)");
      }
      png_init_io(png_ptr, nfile);
      png_set_sig_bytes(png_ptr, 8);

      // Get PNG Header Info up to data block
      png_read_info(png_ptr,info_ptr);
      png_uint_32 W, H;
      int bit_depth, color_type, interlace_type;
      bool is_gray = false;
      png_get_IHDR(png_ptr,info_ptr,&W,&H,&bit_depth,&color_type,&interlace_type,(int*)0,(int*)0);
      if (bits_per_pixel) *bits_per_pixel = (unsigned int)bit_depth;

      // Transforms to unify image data
      if (color_type==PNG_COLOR_TYPE_PALETTE) {
        png_set_palette_to_rgb(png_ptr);
        color_type = PNG_COLOR_TYPE_RGB;
        bit_depth = 8;
      }
      if (color_type==PNG_COLOR_TYPE_GRAY && bit_depth<8) {
        png_set_expand_gray_1_2_4_to_8(png_ptr);
        is_gray = true;
        bit_depth = 8;
      }
      if (png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS)) {
        png_set_tRNS_to_alpha(png_ptr);
        color_type |= PNG_COLOR_MASK_ALPHA;
      }
      if (color_type==PNG_COLOR_TYPE_GRAY || color_type==PNG_COLOR_TYPE_GRAY_ALPHA) {
        png_set_gray_to_rgb(png_ptr);
        color_type |= PNG_COLOR_MASK_COLOR;
        is_gray = true;
      }
      if (color_type==PNG_COLOR_TYPE_RGB)
        png_set_filler(png_ptr,0xffffU,PNG_FILLER_AFTER);

      png_read_update_info(png_ptr,info_ptr);
      if (bit_depth!=8 && bit_depth!=16) {
        if (!file) cimg::fclose(nfile);
        png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0);
        throw CImgIOException(_cimg_instance
                              "load_png(): Invalid bit depth %u in file '%s'.",
                              cimg_instance,
                              bit_depth,nfilename?nfilename:"(FILE*)");
      }
      const int byte_depth = bit_depth>>3;

      // Allocate memory for image reading
      png_bytep *const imgData = new png_bytep[H];
      for (unsigned int row = 0; row<H; ++row) imgData[row] = new png_byte[(size_t)byte_depth*4*W];
      png_read_image(png_ptr,imgData);
      png_read_end(png_ptr,end_info);

      // Read pixel data
      if (color_type!=PNG_COLOR_TYPE_RGB && color_type!=PNG_COLOR_TYPE_RGB_ALPHA) {
        if (!file) cimg::fclose(nfile);
        png_destroy_read_struct(&png_ptr,&end_info,(png_infopp)0);
        throw CImgIOException(_cimg_instance
                              "load_png(): Invalid color coding type %u in file '%s'.",
                              cimg_instance,
                              color_type,nfilename?nfilename:"(FILE*)");
      }
      const bool is_alpha = (color_type==PNG_COLOR_TYPE_RGBA);
      try { assign(W,H,1,(is_gray?1:3) + (is_alpha?1:0)); }
      catch (...) { if (!file) cimg::fclose(nfile); throw; }
      T
        *ptr_r = data(0,0,0,0),
        *ptr_g = is_gray?0:data(0,0,0,1),
        *ptr_b = is_gray?0:data(0,0,0,2),
        *ptr_a = !is_alpha?0:data(0,0,0,is_gray?1:3);
      switch (bit_depth) {
      case 8 : {
        cimg_forY(*this,y) {
          const unsigned char *ptrs = (unsigned char*)imgData[y];
          cimg_forX(*this,x) {
            *(ptr_r++) = (T)*(ptrs++);
            if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs;
            if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs;
            if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs;
          }
        }
      } break;
      case 16 : {
        cimg_forY(*this,y) {
          const unsigned short *ptrs = (unsigned short*)(imgData[y]);
          if (!cimg::endianness()) cimg::invert_endianness(ptrs,4*_width);
          cimg_forX(*this,x) {
            *(ptr_r++) = (T)*(ptrs++);
            if (ptr_g) *(ptr_g++) = (T)*(ptrs++); else ++ptrs;
            if (ptr_b) *(ptr_b++) = (T)*(ptrs++); else ++ptrs;
            if (ptr_a) *(ptr_a++) = (T)*(ptrs++); else ++ptrs;
          }
        }
      } break;
      }
      png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);

      // Deallocate image read memory
      cimg_forY(*this,n) delete[] imgData[n];
      delete[] imgData;
      if (!file) cimg::fclose(nfile);
      return *this;
#endif

Project: CImg
File: CImg.h

      \param align Appending alignment.
      \param[in,out] XYZ Contains the XYZ coordinates at start / exit of the function.
      \param exit_on_anykey Exit function when any key is pressed.
    **/
    const CImgList<T>& display(const char *const title=0, const bool display_info=true,
                               const char axis='x', const float align=0,
                               unsigned int *const XYZ=0, const bool exit_on_anykey=false) const {

Project: CImg
File: CImg.h

      // Return a string that defines the calling function + the user-defined function scope.
      CImg<charT> calling_function_s() const {
        CImg<charT> res;
        const unsigned int
          l1 = calling_function?(unsigned int)std::strlen(calling_function):0U,
          l2 = user_macro?(unsigned int)std::strlen(user_macro):0U;
        if (l2) {
          res.assign(l1 + l2 + 48);
          cimg_snprintf(res,res._width,"%s(): When substituting function '%s()'",calling_function,user_macro);
        } else {
          res.assign(l1 + l2 + 4);
          cimg_snprintf(res,res._width,"%s()",calling_function);
        }
        return res;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<Tfloat> get_atan2(const CImg<t>& img) const {
      return CImg<Tfloat>(*this,false).atan2(img);

Project: CImg
File: CImg.h

    **/
    CImg<T>& resize_tripleXY() {
      return get_resize_tripleXY().move_to(*this);

Project: CImg
File: CImg.h


      static double mp_self_mul(_cimg_math_parser& mp) {
        return _mp_arg(1)*=_mp_arg(2);

Project: CImg
File: CImg.h

    //! Save image as a PNK file \overloading.
    const CImg<T>& save_pnk(std::FILE *const file) const {
      return _save_pnk(file,0);

Project: CImg
File: CImg.h

      return get_split(axis,nb).move_to(*this);
    }

    //! Return a list where each image has been split along the specified axis \newinstance.
    CImgList<T> get_split(const char axis, const int nb=-1) const {

Project: CImg
File: CImg.h

    }
    inline int mod(const bool x, const bool m) {
      return m?(x?1:0):0;

Project: CImg
File: CImg.h

      \param y0 Starting Y-coordinates of image regions to write.
      \param z0 Starting Z-coordinates of image regions to write.
      \param c0 Starting C-coordinates of image regions to write.
    **/
    const CImgList<T>& save_cimg(std::FILE *const file,
                                 const unsigned int n0,

Project: CImg
File: CImg.h

     **/
    T& min() {
      if (is_empty())
        throw CImgInstanceException(_cimg_instance
                                    "min(): Empty instance.",
                                    cimg_instance);
      T *ptr_min = _data;
      T min_value = *ptr_min;
      cimg_for(*this,ptrs,T) if (*ptrs<min_value) min_value = *(ptr_min=ptrs);
      return *ptr_min;

Project: CImg
File: CImg.h

    **/
    iterator end() {
      return _data + _width;

Project: CImg
File: CImg.h


    static T __cimg_blur_box_apply(T *ptr, const int N, const ulongT off,
                                   const bool boundary_conditions, const int x) {
      if (x<0) return boundary_conditions?ptr[0]:T();
      if (x>=N) return boundary_conditions?ptr[(N - 1)*off]:T();
      return ptr[x*off];

Project: CImg
File: CImg.h


      static double mp_debug(_cimg_math_parser& mp) {
        CImg<charT> expr(mp.opcode[2] - 4);
        {
          const ulongT *ptrs = mp.opcode._data + 4;
          cimg_for(expr,ptrd,char) *ptrd = (char)*(ptrs++);
        }
        cimg::strellipsize(expr);
        const ulongT g_target = mp.opcode[1];

#if cimg_use_openmp==0
        const unsigned int n_thread = 0;
#else
        const unsigned int n_thread = omp_get_thread_num();
#endif
        cimg_pragma_openmp(critical(mp_debug))
        {
          std::fprintf(cimg::output(),
                       "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c"
                       "Start debugging expression '%s', code length %u -> mem[%u] (memsize: %u)",
                       (void*)&mp,n_thread,mp.debug_indent,' ',
                       expr._data,(unsigned int)mp.opcode[3],(unsigned int)g_target,mp.mem._width);
          std::fflush(cimg::output());
          mp.debug_indent+=3;
        }
        const CImg<ulongT> *const p_end = (++mp.p_code) + mp.opcode[3];
        CImg<ulongT> _op;
        for ( ; mp.p_code<p_end; ++mp.p_code) {
          const CImg<ulongT> &op = *mp.p_code;
          mp.opcode._data = op._data;

          _op.assign(1,op._height - 1);
          const ulongT *ptrs = op._data + 1;
          for (ulongT *ptrd = _op._data, *const ptrde = _op._data + _op._height; ptrd<ptrde; ++ptrd)
            *ptrd = *(ptrs++);

          const ulongT target = mp.opcode[1];
          mp.mem[target] = _cimg_mp_defunc(mp);
          cimg_pragma_openmp(critical(mp_debug))
          {
            std::fprintf(cimg::output(),
                         "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c"
                         "Opcode %p = [ %p,%s ] -> mem[%u] = %g",
                         (void*)&mp,n_thread,mp.debug_indent,' ',
                         (void*)mp.opcode._data,(void*)*mp.opcode,_op.value_string().data(),
                         (unsigned int)target,mp.mem[target]);
            std::fflush(cimg::output());
          }
        }
        cimg_pragma_openmp(critical(mp_debug))
        {
          mp.debug_indent-=3;
          std::fprintf(cimg::output(),
            "\n[" cimg_appname "_math_parser] %p[thread #%u]:%*c"
            "End debugging expression '%s' -> mem[%u] = %g (memsize: %u)",
            (void*)&mp,n_thread,mp.debug_indent,' ',
            expr._data,(unsigned int)g_target,mp.mem[g_target],mp.mem._width);
          std::fflush(cimg::output());
        }
        --mp.p_code;
        return mp.mem[g_target];

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_cimg(const char *const filename,
                       const unsigned int n0, const unsigned int n1,
                       const unsigned int x0, const unsigned int y0,
                       const unsigned int z0, const unsigned int c0,
                       const unsigned int x1, const unsigned int y1,
                       const unsigned int z1, const unsigned int c1,
                       const char axis='z', const float align=0) {
      CImgList<T> list;
      list.load_cimg(filename,n0,n1,x0,y0,z0,c0,x1,y1,z1,c1);
      if (list._width==1) return list[0].move_to(*this);
      return assign(list.get_append(axis,align));

Project: CImg
File: CImg.h

    // Return a random filename.
    inline const char* filenamerand() {
      cimg::mutex(6);
      static char randomid[9];
      for (unsigned int k = 0; k<8; ++k) {
        const int v = (int)cimg::rand(65535)%3;
        randomid[k] = (char)(v==0?('0' + ((int)cimg::rand(65535)%10)):
                             (v==1?('a' + ((int)cimg::rand(65535)%26)):
                              ('A' + ((int)cimg::rand(65535)%26))));
      }
      cimg::mutex(6,0);
      return randomid;

Project: CImg
File: CImg.h

     **/
    CImg(const unsigned int size_x, const unsigned int size_y, const unsigned int size_z, const unsigned int size_c,
	 const char *const values, const bool repeat_values):_is_shared(false) {
      const size_t siz = (size_t)size_x*size_y*size_z*size_c;
      if (siz) {
        _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c;
        try { _data = new T[siz]; } catch (...) {
          _width = _height = _depth = _spectrum = 0; _data = 0;
          throw CImgInstanceException(_cimg_instance
                                      "CImg(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).",
                                      cimg_instance,
                                      cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),
                                      size_x,size_y,size_z,size_c);
        }
        fill(values,repeat_values);
      } else { _width = _height = _depth = _spectrum = 0; _data = 0; }

Project: CImg
File: CImg.h

    //! Blur image isotropically \newinstance.
    CImg<Tfloat> get_blur(const float sigma, const bool boundary_conditions=true, const bool is_gaussian=false) const {
      return CImg<Tfloat>(*this,false).blur(sigma,boundary_conditions,is_gaussian);

Project: CImg
File: CImg.h

    **/
    CImgList<T>& assign() {
      delete[] _data;
      _width = _allocated_width = 0;
      _data = 0;
      return *this;

Project: CImg
File: CImg.h

    **/
    const CImg<T>& save_exr(const char *const filename) const {
      if (!filename)
        throw CImgArgumentException(_cimg_instance
                                    "save_exr(): Specified filename is (null).",
                                    cimg_instance);
      if (is_empty()) { cimg::fempty(0,filename); return *this; }
      if (_depth>1)
        cimg::warn(_cimg_instance
                   "save_exr(): Instance is volumetric, only the first slice will be saved in file '%s'.",
                   cimg_instance,
                   filename);

#ifndef cimg_use_openexr
      return save_other(filename);
#else
      Imf::Rgba *const ptrd0 = new Imf::Rgba[(size_t)_width*_height], *ptrd = ptrd0, rgba;
      switch (_spectrum) {
      case 1 : { // Grayscale image
        for (const T *ptr_r = data(), *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) {
          rgba.r = rgba.g = rgba.b = (half)(*(ptr_r++));
          rgba.a = (half)1;
          *(ptrd++) = rgba;
        }
      } break;
      case 2 : { // RG image
        for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1),
               *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e; ) {
          rgba.r = (half)(*(ptr_r++));
          rgba.g = (half)(*(ptr_g++));
          rgba.b = (half)0;
          rgba.a = (half)1;
          *(ptrd++) = rgba;
        }
      } break;
      case 3 : { // RGB image
        for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2),
               *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) {
          rgba.r = (half)(*(ptr_r++));
          rgba.g = (half)(*(ptr_g++));
          rgba.b = (half)(*(ptr_b++));
          rgba.a = (half)1;
          *(ptrd++) = rgba;
        }
      } break;
      default : { // RGBA image
        for (const T *ptr_r = data(), *ptr_g = data(0,0,0,1), *ptr_b = data(0,0,0,2), *ptr_a = data(0,0,0,3),
               *const ptr_e = ptr_r + (ulongT)_width*_height; ptr_r<ptr_e;) {
          rgba.r = (half)(*(ptr_r++));
          rgba.g = (half)(*(ptr_g++));
          rgba.b = (half)(*(ptr_b++));
          rgba.a = (half)(*(ptr_a++));
          *(ptrd++) = rgba;
        }
      } break;
      }
      Imf::RgbaOutputFile outFile(filename,_width,_height,
                                  _spectrum==1?Imf::WRITE_Y:_spectrum==2?Imf::WRITE_YA:_spectrum==3?
                                  Imf::WRITE_RGB:Imf::WRITE_RGBA);
      outFile.setFrameBuffer(ptrd0,1,_width);
      outFile.writePixels(_height);
      delete[] ptrd0;
      return *this;
#endif

Project: CImg
File: CImg.h

    }
    inline int mod(const char x, const char m) {
#if defined(CHAR_MAX) && CHAR_MAX==255
      return x%m;
#else
      return x>=0?x%m:(x%m?m + x%m:0);
#endif

Project: CImg
File: CImg.h


      static double mp_linear_sub_left(_cimg_math_parser& mp) {
        return _mp_arg(2)*_mp_arg(3) - _mp_arg(4);

Project: CImg
File: CImg.h

      static const char* string() { static const char *const s = "int64"; return s; }

Project: CImg
File: CImg.h

    template<typename t1, typename t2, typename t3, typename t4, typename t5, typename t6, typename t7>
    CImgList<T>& assign(const CImg<t1>& img1, const CImg<t2>& img2, const CImg<t3>& img3, const CImg<t4>& img4,
                        const CImg<t5>& img5, const CImg<t6>& img6, const CImg<t7>& img7, const bool is_shared=false) {
      assign(7);
      _data[0].assign(img1,is_shared); _data[1].assign(img2,is_shared); _data[2].assign(img3,is_shared);
      _data[3].assign(img4,is_shared); _data[4].assign(img5,is_shared); _data[5].assign(img6,is_shared);
      _data[6].assign(img7,is_shared);
      return *this;

Project: CImg
File: CImg.h


    Tfloat _cubic_atXYZ(const float fx, const float fy, const float fz, const int c=0) const {
      const float
        nfx = cimg::type<float>::is_nan(fx)?0:cimg::cut(fx,0,width() - 1),
        nfy = cimg::type<float>::is_nan(fy)?0:cimg::cut(fy,0,height() - 1),
        nfz = cimg::type<float>::is_nan(fz)?0:cimg::cut(fz,0,depth() - 1);
      const int x = (int)nfx, y = (int)nfy, z = (int)nfz;
      const float dx = nfx - x, dy = nfy - y, dz = nfz - z;
      const int
        px = x - 1<0?0:x - 1, nx = dx>0?x + 1:x, ax = x + 2>=width()?width() - 1:x + 2,
        py = y - 1<0?0:y - 1, ny = dy>0?y + 1:y, ay = y + 2>=height()?height() - 1:y + 2,
        pz = z - 1<0?0:z - 1, nz = dz>0?z + 1:z, az = z + 2>=depth()?depth() - 1:z + 2;
      const Tfloat
        Ippp = (Tfloat)(*this)(px,py,pz,c), Icpp = (Tfloat)(*this)(x,py,pz,c),
        Inpp = (Tfloat)(*this)(nx,py,pz,c), Iapp = (Tfloat)(*this)(ax,py,pz,c),
        Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) +
                           dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)),
        Ipcp = (Tfloat)(*this)(px,y,pz,c),  Iccp = (Tfloat)(*this)(x, y,pz,c),
        Incp = (Tfloat)(*this)(nx,y,pz,c),  Iacp = (Tfloat)(*this)(ax,y,pz,c),
        Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) +
                           dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)),
        Ipnp = (Tfloat)(*this)(px,ny,pz,c), Icnp = (Tfloat)(*this)(x,ny,pz,c),
        Innp = (Tfloat)(*this)(nx,ny,pz,c), Ianp = (Tfloat)(*this)(ax,ny,pz,c),
        Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) +
                           dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)),
        Ipap = (Tfloat)(*this)(px,ay,pz,c), Icap = (Tfloat)(*this)(x,ay,pz,c),
        Inap = (Tfloat)(*this)(nx,ay,pz,c), Iaap = (Tfloat)(*this)(ax,ay,pz,c),
        Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) +
                           dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)),
        Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) +
                         dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)),
        Ippc = (Tfloat)(*this)(px,py,z,c), Icpc = (Tfloat)(*this)(x,py,z,c),
        Inpc = (Tfloat)(*this)(nx,py,z,c), Iapc = (Tfloat)(*this)(ax,py,z,c),
        Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) +
                           dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)),
        Ipcc = (Tfloat)(*this)(px,y,z,c),  Iccc = (Tfloat)(*this)(x, y,z,c),
        Incc = (Tfloat)(*this)(nx,y,z,c),  Iacc = (Tfloat)(*this)(ax,y,z,c),
        Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) +
                           dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)),
        Ipnc = (Tfloat)(*this)(px,ny,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c),
        Innc = (Tfloat)(*this)(nx,ny,z,c), Ianc = (Tfloat)(*this)(ax,ny,z,c),
        Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) +
                           dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)),
        Ipac = (Tfloat)(*this)(px,ay,z,c), Icac = (Tfloat)(*this)(x,ay,z,c),
        Inac = (Tfloat)(*this)(nx,ay,z,c), Iaac = (Tfloat)(*this)(ax,ay,z,c),
        Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) +
                           dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)),
        Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) +
                         dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)),
        Ippn = (Tfloat)(*this)(px,py,nz,c), Icpn = (Tfloat)(*this)(x,py,nz,c),
        Inpn = (Tfloat)(*this)(nx,py,nz,c), Iapn = (Tfloat)(*this)(ax,py,nz,c),
        Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) +
                           dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)),
        Ipcn = (Tfloat)(*this)(px,y,nz,c),  Iccn = (Tfloat)(*this)(x, y,nz,c),
        Incn = (Tfloat)(*this)(nx,y,nz,c),  Iacn = (Tfloat)(*this)(ax,y,nz,c),
        Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) +
                           dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)),
        Ipnn = (Tfloat)(*this)(px,ny,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c),
        Innn = (Tfloat)(*this)(nx,ny,nz,c), Iann = (Tfloat)(*this)(ax,ny,nz,c),
        Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) +
                           dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)),
        Ipan = (Tfloat)(*this)(px,ay,nz,c), Ican = (Tfloat)(*this)(x,ay,nz,c),
        Inan = (Tfloat)(*this)(nx,ay,nz,c), Iaan = (Tfloat)(*this)(ax,ay,nz,c),
        Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) +
                           dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)),
        In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) +
                         dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)),
        Ippa = (Tfloat)(*this)(px,py,az,c), Icpa = (Tfloat)(*this)(x,py,az,c),
        Inpa = (Tfloat)(*this)(nx,py,az,c), Iapa = (Tfloat)(*this)(ax,py,az,c),
        Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) +
                           dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)),
        Ipca = (Tfloat)(*this)(px,y,az,c),  Icca = (Tfloat)(*this)(x, y,az,c),
        Inca = (Tfloat)(*this)(nx,y,az,c),  Iaca = (Tfloat)(*this)(ax,y,az,c),
        Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) +
                           dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)),
        Ipna = (Tfloat)(*this)(px,ny,az,c), Icna = (Tfloat)(*this)(x,ny,az,c),
        Inna = (Tfloat)(*this)(nx,ny,az,c), Iana = (Tfloat)(*this)(ax,ny,az,c),
        Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) +
                           dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)),
        Ipaa = (Tfloat)(*this)(px,ay,az,c), Icaa = (Tfloat)(*this)(x,ay,az,c),
        Inaa = (Tfloat)(*this)(nx,ay,az,c), Iaaa = (Tfloat)(*this)(ax,ay,az,c),
        Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) +
                           dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)),
        Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) +
                         dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa));
      return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia));

Project: CImg
File: CImg.h

    template<typename tc>
    CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0,
                         const int x1, const int y1, const float u1, const float v1,
                         const tc *const color, const float opacity=1,
                         const float precision=0.25, const unsigned int pattern=~0U,
                         const bool init_hatch=true) {
      if (is_empty()) return *this;
      if (!color)
        throw CImgArgumentException(_cimg_instance
                                    "draw_spline(): Specified color is (null).",
                                    cimg_instance);
      if (x0==x1 && y0==y1) return draw_point(x0,y0,color,opacity);
      bool ninit_hatch = init_hatch;
      const float
        ax = u0 + u1 + 2*(x0 - x1),
        bx = 3*(x1 - x0) - 2*u0 - u1,
        ay = v0 + v1 + 2*(y0 - y1),
        by = 3*(y1 - y0) - 2*v0 - v1,
        _precision = 1/(cimg::hypot((float)x0 - x1,(float)y0 - y1)*(precision>0?precision:1));
      int ox = x0, oy = y0;
      for (float t = 0; t<1; t+=_precision) {
        const float t2 = t*t, t3 = t2*t;
        const int
          nx = (int)(ax*t3 + bx*t2 + u0*t + x0),
          ny = (int)(ay*t3 + by*t2 + v0*t + y0);
        draw_line(ox,oy,nx,ny,color,opacity,pattern,ninit_hatch);
        ninit_hatch = false;
        ox = nx; oy = ny;
      }
      return draw_line(ox,oy,x1,y1,color,opacity,pattern,false);

Project: CImg
File: CImg.h

    template<typename tc>
    CImg<T>& _draw_triangle(int x0, int y0,
                            int x1, int y1,
                            int x2, int y2,
                            const tc *const color, const float opacity,
                            const float brightness) {
      if (y0>y1) cimg::swap(x0,x1,y0,y1);
      if (y0>y2) cimg::swap(x0,x2,y0,y2);
      if (y1>y2) cimg::swap(x1,x2,y1,y2);
      if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this;

      const int
        h1 = height() - 1,
        dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1,
        dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1),
        cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1),
        hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2;

      const float cbs = cimg::cut(brightness,0,2);
      cimg_init_scanline(opacity);

      for (int y = cy0; y<=cy2; ++y) {
        const int yy0 = y - y0, yy1 = y - y1;
        int
          xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12,
          xM = x0 + (dx02*yy0 + hdy02)/dy02;
        if (xm>xM) cimg::swap(xm,xM);
        cimg_draw_scanline(xm,xM,y,color,opacity,cbs);
      }
      return *this;

Project: CImg
File: CImg.h


    inline void syev(char &JOB, char &UPLO, int &N, float *lapA, float *lapW, float *WORK, int &LWORK, int &INFO) {
      ssyev_(&JOB,&UPLO,&N,lapA,&N,lapW,WORK,&LWORK,&INFO);

Project: CImg
File: CImg.h

    //! Erode the image by a square structuring element of specified size \newinstance.
    CImg<T> get_erode(const unsigned int s) const {
      return (+*this).erode(s);

Project: CImg
File: CImg.h

    //! Load image from a RAW Color Camera file, using external tool 'dcraw' \newinstance.
    static CImg<T> get_load_dcraw_external(const char *const filename) {
      return CImg<T>().load_dcraw_external(filename);

Project: CImg
File: CImg.h

    //                    2 = allow formula but do not fill image values }.
    CImg<T>& _fill(const char *const expression, const bool repeat_values, const unsigned int formula_mode,
                   const CImgList<T> *const list_inputs, CImgList<T> *const list_outputs,
                   const char *const calling_function, const CImg<T> *provides_copy) {
      if (is_empty() || !expression || !*expression) return *this;
      const unsigned int omode = cimg::exception_mode();
      cimg::exception_mode(0);
      CImg<charT> is_error;
      bool is_value_sequence = false;
      cimg_abort_init;

      if (formula_mode) {

        // Try to pre-detect regular value sequence to avoid exception thrown by _cimg_math_parser.
        double value;
        char sep;
        const int err = cimg_sscanf(expression,"%lf %c",&value,&sep);
        if (err==1 || (err==2 && sep==',')) {
          if (err==1) return fill((T)value);
          else is_value_sequence = true;
        }

        // Try to fill values according to a formula.
        _cimg_abort_init_omp;
        if (!is_value_sequence) try {
            CImg<T> base = provides_copy?provides_copy->get_shared():get_shared();
            _cimg_math_parser mp(expression + (*expression=='>' || *expression=='<' ||
                                               *expression=='*' || *expression==':'),
                                 calling_function,base,this,list_inputs,list_outputs,true);
            if (!provides_copy && expression && *expression!='>' && *expression!='<' && *expression!=':' &&
                mp.need_input_copy)
              base.assign().assign(*this,false); // Needs input copy

            bool do_in_parallel = false;

#if cimg_use_openmp!=0
            cimg_openmp_if(*expression=='*' || *expression==':' ||
                           (mp.is_parallelizable && _width>=(cimg_openmp_sizefactor)*320 &&
                            _height*_depth*_spectrum>=2))
              do_in_parallel = true;
#endif
            if (mp.result_dim) { // Vector-valued expression
              const unsigned int N = std::min(mp.result_dim,_spectrum);
              const ulongT whd = (ulongT)_width*_height*_depth;
              T *ptrd = *expression=='<'?_data + _width*_height*_depth - 1:_data;
              if (*expression=='<') {
                CImg<doubleT> res(1,mp.result_dim);
                cimg_rofYZ(*this,y,z) {
                  cimg_abort_test;
                  if (formula_mode==2) cimg_rofX(*this,x) mp(x,y,z,0);
                  else cimg_rofX(*this,x) {
                      mp(x,y,z,0,res._data);
                      const double *ptrs = res._data;
                      T *_ptrd = ptrd--; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; }
                    }
                }
              } else if (*expression=='>' || !do_in_parallel) {
                CImg<doubleT> res(1,mp.result_dim);
                cimg_forYZ(*this,y,z) {
                  cimg_abort_test;
                  if (formula_mode==2) cimg_forX(*this,x) mp(x,y,z,0);
                  else cimg_forX(*this,x) {
                      mp(x,y,z,0,res._data);
                      const double *ptrs = res._data;
                      T *_ptrd = ptrd++; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; }
                    }
                }
             } else {

#if cimg_use_openmp!=0
                cimg_pragma_openmp(parallel)
                {
                  _cimg_math_parser
                    _mp = omp_get_thread_num()?mp:_cimg_math_parser(),
                    &lmp = omp_get_thread_num()?_mp:mp;
                  lmp.is_fill = true;
                  cimg_pragma_openmp(for cimg_openmp_collapse(2))
                    cimg_forYZ(*this,y,z) _cimg_abort_try_omp {
                    cimg_abort_test;
                    if (formula_mode==2) cimg_forX(*this,x) lmp(x,y,z,0);
                    else {
                      CImg<doubleT> res(1,lmp.result_dim);
                      T *__ptrd = data(0,y,z,0);
                      cimg_forX(*this,x) {
                        lmp(x,y,z,0,res._data);
                        const double *ptrs = res._data;
                        T *_ptrd = __ptrd++; for (unsigned int n = N; n>0; --n) { *_ptrd = (T)(*ptrs++); _ptrd+=whd; }
                      }
                    }
                  } _cimg_abort_catch_omp _cimg_abort_catch_fill_omp
                }
#endif
              }

            } else { // Scalar-valued expression
              T *ptrd = *expression=='<'?end() - 1:_data;
              if (*expression=='<') {
                if (formula_mode==2) cimg_rofYZC(*this,y,z,c) { cimg_abort_test; cimg_rofX(*this,x) mp(x,y,z,c); }
                else cimg_rofYZC(*this,y,z,c) { cimg_abort_test; cimg_rofX(*this,x) *(ptrd--) = (T)mp(x,y,z,c); }
              } else if (*expression=='>' || !do_in_parallel) {
                if (formula_mode==2) cimg_forYZC(*this,y,z,c) { cimg_abort_test; cimg_forX(*this,x) mp(x,y,z,c); }
                else cimg_forYZC(*this,y,z,c) { cimg_abort_test; cimg_forX(*this,x) *(ptrd++) = (T)mp(x,y,z,c); }
              } else {

#if cimg_use_openmp!=0
                cimg_pragma_openmp(parallel)
                {
                  _cimg_math_parser
                    _mp = omp_get_thread_num()?mp:_cimg_math_parser(),
                    &lmp = omp_get_thread_num()?_mp:mp;
                  lmp.is_fill = true;
                  cimg_pragma_openmp(for cimg_openmp_collapse(3))
                    cimg_forYZC(*this,y,z,c) _cimg_abort_try_omp {
                    cimg_abort_test;
                    if (formula_mode==2) cimg_forX(*this,x) lmp(x,y,z,c);
                    else {
                      T *_ptrd = data(0,y,z,c);
                      cimg_forX(*this,x) *(_ptrd++) = (T)lmp(x,y,z,c);
                    }
                  } _cimg_abort_catch_omp _cimg_abort_catch_fill_omp
                }
#endif
              }
            }
            mp.end();
          } catch (CImgException& e) { CImg<charT>::string(e._message).move_to(is_error); }
      }

      // Try to fill values according to a value sequence.
      if (!formula_mode || is_value_sequence || is_error) {
        CImg<charT> item(256);
        char sep = 0;
        const char *nexpression = expression;
        ulongT nb = 0;
        const ulongT siz = size();
        T *ptrd = _data;
        for (double val = 0; *nexpression && nb<siz; ++nb) {
          sep = 0;
          const int err = cimg_sscanf(nexpression,"%255[ \n\t0-9.eEinfa+-]%c",item._data,&sep);
          if (err>0 && cimg_sscanf(item,"%lf",&val)==1 && (sep==',' || sep==';' || err==1)) {
            nexpression+=std::strlen(item) + (err>1);
            *(ptrd++) = (T)val;
          } else break;
        }
        cimg::exception_mode(omode);
        if (nb<siz && (sep || *nexpression)) {
          if (is_error) throw CImgArgumentException("%s",is_error._data);
          else throw CImgArgumentException(_cimg_instance
                                           "%s(): Invalid sequence of filling values '%s'.",
                                           cimg_instance,calling_function,expression);
        }
        if (repeat_values && nb && nb<siz)
          for (T *ptrs = _data, *const ptre = _data + siz; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs;
      }

      cimg::exception_mode(omode);
      cimg_abort_test;
      return *this;

Project: CImg
File: CImg.h


    void _handle_events(const XEvent *const pevent) {
      Display *const dpy = cimg::X11_attr().display;
      XEvent event = *pevent;
      switch (event.type) {
      case ClientMessage : {
        if ((int)event.xclient.message_type==(int)_wm_protocol_atom &&
            (int)event.xclient.data.l[0]==(int)_wm_window_atom) {
          XUnmapWindow(cimg::X11_attr().display,_window);
          _is_closed = _is_event = true;
          pthread_cond_broadcast(&cimg::X11_attr().wait_event);
        }
      } break;
      case ConfigureNotify : {
        while (XCheckWindowEvent(dpy,_window,StructureNotifyMask,&event)) {}
        const unsigned int nw = event.xconfigure.width, nh = event.xconfigure.height;
        const int nx = event.xconfigure.x, ny = event.xconfigure.y;
        if (nw && nh && (nw!=_window_width || nh!=_window_height)) {
          _window_width = nw; _window_height = nh; _mouse_x = _mouse_y = -1;
          XResizeWindow(dpy,_window,_window_width,_window_height);
          _is_resized = _is_event = true;
          pthread_cond_broadcast(&cimg::X11_attr().wait_event);
        }
        if (nx!=_window_x || ny!=_window_y) {
          _window_x = nx; _window_y = ny; _is_moved = _is_event = true;
          pthread_cond_broadcast(&cimg::X11_attr().wait_event);
        }
      } break;
      case Expose : {
        while (XCheckWindowEvent(dpy,_window,ExposureMask,&event)) {}
        _paint(false);
        if (_is_fullscreen) {
          XWindowAttributes attr;
          XGetWindowAttributes(dpy,_window,&attr);
          while (attr.map_state!=IsViewable) XSync(dpy,0);
          XSetInputFocus(dpy,_window,RevertToParent,CurrentTime);
        }
      } break;
      case ButtonPress : {
        do {
          _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y;
          if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1;
          switch (event.xbutton.button) {
          case 1 : set_button(1); break;
          case 3 : set_button(2); break;
          case 2 : set_button(3); break;
          }
        } while (XCheckWindowEvent(dpy,_window,ButtonPressMask,&event));
      } break;
      case ButtonRelease : {
        do {
          _mouse_x = event.xmotion.x; _mouse_y = event.xmotion.y;
          if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1;
          switch (event.xbutton.button) {
          case 1 : set_button(1,false); break;
          case 3 : set_button(2,false); break;
          case 2 : set_button(3,false); break;
          case 4 : set_wheel(1); break;
          case 5 : set_wheel(-1); break;
          }
        } while (XCheckWindowEvent(dpy,_window,ButtonReleaseMask,&event));
      } break;
      case KeyPress : {
        char tmp = 0; KeySym ksym;
        XLookupString(&event.xkey,&tmp,1,&ksym,0);
        set_key((unsigned int)ksym,true);
      } break;
      case KeyRelease : {
        char keys_return[32];  // Check that the key has been physically unpressed
        XQueryKeymap(dpy,keys_return);
        const unsigned int kc = event.xkey.keycode, kc1 = kc/8, kc2 = kc%8;
        const bool is_key_pressed = kc1>=32?false:(keys_return[kc1]>>kc2)&1;
        if (!is_key_pressed) {
          char tmp = 0; KeySym ksym;
          XLookupString(&event.xkey,&tmp,1,&ksym,0);
          set_key((unsigned int)ksym,false);
        }
      } break;
      case EnterNotify: {
        while (XCheckWindowEvent(dpy,_window,EnterWindowMask,&event)) {}
        _mouse_x = event.xmotion.x;
        _mouse_y = event.xmotion.y;
        if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1;
      } break;
      case LeaveNotify : {
        while (XCheckWindowEvent(dpy,_window,LeaveWindowMask,&event)) {}
        _mouse_x = _mouse_y = -1; _is_event = true;
        pthread_cond_broadcast(&cimg::X11_attr().wait_event);
      } break;
      case MotionNotify : {
        while (XCheckWindowEvent(dpy,_window,PointerMotionMask,&event)) {}
        _mouse_x = event.xmotion.x;
        _mouse_y = event.xmotion.y;
        if (_mouse_x<0 || _mouse_y<0 || _mouse_x>=width() || _mouse_y>=height()) _mouse_x = _mouse_y = -1;
        _is_event = true;
        pthread_cond_broadcast(&cimg::X11_attr().wait_event);
      } break;
      }

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& cross(const CImg<t>& img) {
      if (_width!=1 || _height<3 || img._width!=1 || img._height<3)
        throw CImgInstanceException(_cimg_instance
                                    "cross(): Instance and/or specified image (%u,%u,%u,%u,%p) are not 3D vectors.",
                                    cimg_instance,
                                    img._width,img._height,img._depth,img._spectrum,img._data);

      const T x = (*this)[0], y = (*this)[1], z = (*this)[2];
      (*this)[0] = (T)(y*img[2] - z*img[1]);
      (*this)[1] = (T)(z*img[0] - x*img[2]);
      (*this)[2] = (T)(x*img[1] - y*img[0]);
      return *this;

Project: CImg
File: CImg.h


    //! Reverse primitives orientations of a 3D object.
    /**
    **/
    CImgList<T>& reverse_object3d() {
      cimglist_for(*this,l) {
        CImg<T>& p = _data[l];
        switch (p.size()) {
        case 2 : case 3: cimg::swap(p[0],p[1]); break;
        case 6 : cimg::swap(p[0],p[1],p[2],p[4],p[3],p[5]); break;
        case 9 : cimg::swap(p[0],p[1],p[3],p[5],p[4],p[6]); break;
        case 4 : cimg::swap(p[0],p[1],p[2],p[3]); break;
        case 12 : cimg::swap(p[0],p[1],p[2],p[3],p[4],p[6],p[5],p[7],p[8],p[10],p[9],p[11]); break;

Project: CImg
File: CImg.h

    template<typename T>
    explicit CImgDisplay(const CImg<T>& img,
                         const char *const title=0, const unsigned int normalization=3,
                         const bool is_fullscreen=false, const bool is_closed=false):
      _width(0),_height(0),_normalization(0),
      _min(0),_max(0),
      _is_fullscreen(false),
      _title(0),
      _window_width(0),_window_height(0),_button(0),
      _keys(new unsigned int[128]),_released_keys(new unsigned int[128]),
      _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0),
      _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) {
      assign(img,title,normalization,is_fullscreen,is_closed);

Project: CImg
File: CImg.h


    Tfloat _cubic_atXYZ_p(const float fx, const float fy, const float fz, const int c=0) const {
      const float
        nfx = cimg::type<float>::is_nan(fx)?0:cimg::mod(fx,(float)_width),
        nfy = cimg::type<float>::is_nan(fy)?0:cimg::mod(fy,(float)_height),
        nfz = cimg::type<float>::is_nan(fz)?0:cimg::mod(fz,(float)_depth);
      const int x = (int)nfx, y = (int)nfy, z = (int)nfz;
      const float dx = nfx - x, dy = nfy - y, dz = nfz - z;
      const int
        px = cimg::mod(x - 1,width()), nx = cimg::mod(x + 1,width()), ax = cimg::mod(x + 2,width()),
        py = cimg::mod(y - 1,height()), ny = cimg::mod(y + 1,height()), ay = cimg::mod(y + 2,height()),
        pz = cimg::mod(z - 1,depth()), nz = cimg::mod(z + 1,depth()), az = cimg::mod(z + 2,depth());
      const Tfloat
        Ippp = (Tfloat)(*this)(px,py,pz,c), Icpp = (Tfloat)(*this)(x,py,pz,c),
        Inpp = (Tfloat)(*this)(nx,py,pz,c), Iapp = (Tfloat)(*this)(ax,py,pz,c),
        Ipp = Icpp + 0.5f*(dx*(-Ippp + Inpp) + dx*dx*(2*Ippp - 5*Icpp + 4*Inpp - Iapp) +
                           dx*dx*dx*(-Ippp + 3*Icpp - 3*Inpp + Iapp)),
        Ipcp = (Tfloat)(*this)(px,y,pz,c),  Iccp = (Tfloat)(*this)(x, y,pz,c),
        Incp = (Tfloat)(*this)(nx,y,pz,c),  Iacp = (Tfloat)(*this)(ax,y,pz,c),
        Icp = Iccp + 0.5f*(dx*(-Ipcp + Incp) + dx*dx*(2*Ipcp - 5*Iccp + 4*Incp - Iacp) +
                           dx*dx*dx*(-Ipcp + 3*Iccp - 3*Incp + Iacp)),
        Ipnp = (Tfloat)(*this)(px,ny,pz,c), Icnp = (Tfloat)(*this)(x,ny,pz,c),
        Innp = (Tfloat)(*this)(nx,ny,pz,c), Ianp = (Tfloat)(*this)(ax,ny,pz,c),
        Inp = Icnp + 0.5f*(dx*(-Ipnp + Innp) + dx*dx*(2*Ipnp - 5*Icnp + 4*Innp - Ianp) +
                           dx*dx*dx*(-Ipnp + 3*Icnp - 3*Innp + Ianp)),
        Ipap = (Tfloat)(*this)(px,ay,pz,c), Icap = (Tfloat)(*this)(x,ay,pz,c),
        Inap = (Tfloat)(*this)(nx,ay,pz,c), Iaap = (Tfloat)(*this)(ax,ay,pz,c),
        Iap = Icap + 0.5f*(dx*(-Ipap + Inap) + dx*dx*(2*Ipap - 5*Icap + 4*Inap - Iaap) +
                           dx*dx*dx*(-Ipap + 3*Icap - 3*Inap + Iaap)),
        Ip = Icp + 0.5f*(dy*(-Ipp + Inp) + dy*dy*(2*Ipp - 5*Icp + 4*Inp - Iap) +
                         dy*dy*dy*(-Ipp + 3*Icp - 3*Inp + Iap)),
        Ippc = (Tfloat)(*this)(px,py,z,c), Icpc = (Tfloat)(*this)(x,py,z,c),
        Inpc = (Tfloat)(*this)(nx,py,z,c), Iapc = (Tfloat)(*this)(ax,py,z,c),
        Ipc = Icpc + 0.5f*(dx*(-Ippc + Inpc) + dx*dx*(2*Ippc - 5*Icpc + 4*Inpc - Iapc) +
                           dx*dx*dx*(-Ippc + 3*Icpc - 3*Inpc + Iapc)),
        Ipcc = (Tfloat)(*this)(px,y,z,c),  Iccc = (Tfloat)(*this)(x, y,z,c),
        Incc = (Tfloat)(*this)(nx,y,z,c),  Iacc = (Tfloat)(*this)(ax,y,z,c),
        Icc = Iccc + 0.5f*(dx*(-Ipcc + Incc) + dx*dx*(2*Ipcc - 5*Iccc + 4*Incc - Iacc) +
                           dx*dx*dx*(-Ipcc + 3*Iccc - 3*Incc + Iacc)),
        Ipnc = (Tfloat)(*this)(px,ny,z,c), Icnc = (Tfloat)(*this)(x,ny,z,c),
        Innc = (Tfloat)(*this)(nx,ny,z,c), Ianc = (Tfloat)(*this)(ax,ny,z,c),
        Inc = Icnc + 0.5f*(dx*(-Ipnc + Innc) + dx*dx*(2*Ipnc - 5*Icnc + 4*Innc - Ianc) +
                           dx*dx*dx*(-Ipnc + 3*Icnc - 3*Innc + Ianc)),
        Ipac = (Tfloat)(*this)(px,ay,z,c), Icac = (Tfloat)(*this)(x,ay,z,c),
        Inac = (Tfloat)(*this)(nx,ay,z,c), Iaac = (Tfloat)(*this)(ax,ay,z,c),
        Iac = Icac + 0.5f*(dx*(-Ipac + Inac) + dx*dx*(2*Ipac - 5*Icac + 4*Inac - Iaac) +
                           dx*dx*dx*(-Ipac + 3*Icac - 3*Inac + Iaac)),
        Ic = Icc + 0.5f*(dy*(-Ipc + Inc) + dy*dy*(2*Ipc - 5*Icc + 4*Inc - Iac) +
                         dy*dy*dy*(-Ipc + 3*Icc - 3*Inc + Iac)),
        Ippn = (Tfloat)(*this)(px,py,nz,c), Icpn = (Tfloat)(*this)(x,py,nz,c),
        Inpn = (Tfloat)(*this)(nx,py,nz,c), Iapn = (Tfloat)(*this)(ax,py,nz,c),
        Ipn = Icpn + 0.5f*(dx*(-Ippn + Inpn) + dx*dx*(2*Ippn - 5*Icpn + 4*Inpn - Iapn) +
                           dx*dx*dx*(-Ippn + 3*Icpn - 3*Inpn + Iapn)),
        Ipcn = (Tfloat)(*this)(px,y,nz,c),  Iccn = (Tfloat)(*this)(x, y,nz,c),
        Incn = (Tfloat)(*this)(nx,y,nz,c),  Iacn = (Tfloat)(*this)(ax,y,nz,c),
        Icn = Iccn + 0.5f*(dx*(-Ipcn + Incn) + dx*dx*(2*Ipcn - 5*Iccn + 4*Incn - Iacn) +
                           dx*dx*dx*(-Ipcn + 3*Iccn - 3*Incn + Iacn)),
        Ipnn = (Tfloat)(*this)(px,ny,nz,c), Icnn = (Tfloat)(*this)(x,ny,nz,c),
        Innn = (Tfloat)(*this)(nx,ny,nz,c), Iann = (Tfloat)(*this)(ax,ny,nz,c),
        Inn = Icnn + 0.5f*(dx*(-Ipnn + Innn) + dx*dx*(2*Ipnn - 5*Icnn + 4*Innn - Iann) +
                           dx*dx*dx*(-Ipnn + 3*Icnn - 3*Innn + Iann)),
        Ipan = (Tfloat)(*this)(px,ay,nz,c), Ican = (Tfloat)(*this)(x,ay,nz,c),
        Inan = (Tfloat)(*this)(nx,ay,nz,c), Iaan = (Tfloat)(*this)(ax,ay,nz,c),
        Ian = Ican + 0.5f*(dx*(-Ipan + Inan) + dx*dx*(2*Ipan - 5*Ican + 4*Inan - Iaan) +
                           dx*dx*dx*(-Ipan + 3*Ican - 3*Inan + Iaan)),
        In = Icn + 0.5f*(dy*(-Ipn + Inn) + dy*dy*(2*Ipn - 5*Icn + 4*Inn - Ian) +
                         dy*dy*dy*(-Ipn + 3*Icn - 3*Inn + Ian)),
        Ippa = (Tfloat)(*this)(px,py,az,c), Icpa = (Tfloat)(*this)(x,py,az,c),
        Inpa = (Tfloat)(*this)(nx,py,az,c), Iapa = (Tfloat)(*this)(ax,py,az,c),
        Ipa = Icpa + 0.5f*(dx*(-Ippa + Inpa) + dx*dx*(2*Ippa - 5*Icpa + 4*Inpa - Iapa) +
                           dx*dx*dx*(-Ippa + 3*Icpa - 3*Inpa + Iapa)),
        Ipca = (Tfloat)(*this)(px,y,az,c),  Icca = (Tfloat)(*this)(x, y,az,c),
        Inca = (Tfloat)(*this)(nx,y,az,c),  Iaca = (Tfloat)(*this)(ax,y,az,c),
        Ica = Icca + 0.5f*(dx*(-Ipca + Inca) + dx*dx*(2*Ipca - 5*Icca + 4*Inca - Iaca) +
                           dx*dx*dx*(-Ipca + 3*Icca - 3*Inca + Iaca)),
        Ipna = (Tfloat)(*this)(px,ny,az,c), Icna = (Tfloat)(*this)(x,ny,az,c),
        Inna = (Tfloat)(*this)(nx,ny,az,c), Iana = (Tfloat)(*this)(ax,ny,az,c),
        Ina = Icna + 0.5f*(dx*(-Ipna + Inna) + dx*dx*(2*Ipna - 5*Icna + 4*Inna - Iana) +
                           dx*dx*dx*(-Ipna + 3*Icna - 3*Inna + Iana)),
        Ipaa = (Tfloat)(*this)(px,ay,az,c), Icaa = (Tfloat)(*this)(x,ay,az,c),
        Inaa = (Tfloat)(*this)(nx,ay,az,c), Iaaa = (Tfloat)(*this)(ax,ay,az,c),
        Iaa = Icaa + 0.5f*(dx*(-Ipaa + Inaa) + dx*dx*(2*Ipaa - 5*Icaa + 4*Inaa - Iaaa) +
                           dx*dx*dx*(-Ipaa + 3*Icaa - 3*Inaa + Iaaa)),
        Ia = Ica + 0.5f*(dy*(-Ipa + Ina) + dy*dy*(2*Ipa - 5*Ica + 4*Ina - Iaa) +
                         dy*dy*dy*(-Ipa + 3*Ica - 3*Ina + Iaa));
      return Ic + 0.5f*(dz*(-Ip + In) + dz*dz*(2*Ip - 5*Ic + 4*In - Ia) + dz*dz*dz*(-Ip + 3*Ic - 3*In + Ia));

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_pnm(const char *const filename) {
      return _load_pnm(0,filename);

Project: CImg
File: CImg.h

    //! Discard neighboring duplicates in the image buffer, along the specified axis.
    CImg<T>& discard(const char axis=0) {
      return get_discard(axis).move_to(*this);

Project: CImg
File: CImg.h

    **/
    T& atX(const int x, const int y, const int z, const int c, const T& out_value) {
      return (x<0 || x>=width())?(cimg::temporary(out_value)=out_value):(*this)(x,y,z,c);

Project: CImg
File: CImg.h

       \param user_path Specified path, or \c 0 to get the path currently used.
       \param reinit_path Force path to be recalculated (may take some time).
       \return Path where temporary files can be saved.
    **/
    inline const char* temporary_path(const char *const user_path, const bool reinit_path) {
#define _cimg_test_temporary_path(p) \
      if (!path_found) { \
        cimg_snprintf(s_path,s_path.width(),"%s",p); \
        cimg_snprintf(tmp,tmp._width,"%s%c%s",s_path.data(),cimg_file_separator,filename_tmp._data); \
        if ((file=cimg::std_fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; } \
      }
      static CImg<char> s_path;
      cimg::mutex(7);
      if (reinit_path) s_path.assign();
      if (user_path) {
        if (!s_path) s_path.assign(1024);
        std::strncpy(s_path,user_path,1023);
      } else if (!s_path) {
        s_path.assign(1024);
        bool path_found = false;
        CImg<char> tmp(1024), filename_tmp(256);
        std::FILE *file = 0;
        cimg_snprintf(filename_tmp,filename_tmp._width,"%s.tmp",cimg::filenamerand());
        char *tmpPath = std::getenv("TMP");
        if (!tmpPath) { tmpPath = std::getenv("TEMP"); winformat_string(tmpPath); }
        if (tmpPath) _cimg_test_temporary_path(tmpPath);
#if cimg_OS==2
        _cimg_test_temporary_path("C:\\WINNT\\Temp");
        _cimg_test_temporary_path("C:\\WINDOWS\\Temp");
        _cimg_test_temporary_path("C:\\Temp");
        _cimg_test_temporary_path("C:");
        _cimg_test_temporary_path("D:\\WINNT\\Temp");
        _cimg_test_temporary_path("D:\\WINDOWS\\Temp");
        _cimg_test_temporary_path("D:\\Temp");
        _cimg_test_temporary_path("D:");
#else
        _cimg_test_temporary_path("/tmp");
        _cimg_test_temporary_path("/var/tmp");
#endif
        if (!path_found) {
          *s_path = 0;
          std::strncpy(tmp,filename_tmp,tmp._width - 1);
          if ((file=cimg::std_fopen(tmp,"wb"))!=0) { cimg::fclose(file); std::remove(tmp); path_found = true; }
        }
        if (!path_found) {
          cimg::mutex(7,0);
          throw CImgIOException("cimg::temporary_path(): Failed to locate path for writing temporary files.\n");
        }

Project: CImg
File: CImg.h

    template<typename tp, typename tf, typename tc, typename to, typename tz>
    CImg<T>& draw_object3d(LibBoard::Board& board,
                           const float x0, const float y0, const float z0,
                           const CImg<tp>& vertices, const CImgList<tf>& primitives,
                           const CImgList<tc>& colors, const CImg<to>& opacities,
                           const unsigned int render_type,
                           const bool is_double_sided, const float focale,
                           const float lightx, const float lighty, const float lightz,
                           const float specular_lightness, const float specular_shininess,
                           const float g_opacity, CImg<tz>& zbuffer) {
      return _draw_object3d((void*)&board,zbuffer,x0,y0,z0,vertices,primitives,colors,opacities,
                            render_type,is_double_sided,focale,lightx,lighty,lightz,
                            specular_lightness,specular_shininess,g_opacity,1);

Project: CImg
File: CImg.h


    CImgDisplay& assign(const CImgDisplay& disp) {
      if (!disp) return assign();
      _assign(disp._width,disp._height,disp._title,disp._normalization,disp._is_fullscreen,disp._is_closed);
      std::memcpy(_data,disp._data,(cimg::X11_attr().nb_bits==8?sizeof(unsigned char):
                                    cimg::X11_attr().nb_bits==16?sizeof(unsigned short):
                                    sizeof(unsigned int))*(size_t)_width*_height);
      return paint();

Project: CImg
File: CImg.h

    //! Load image sequence from a YUV file \newinstance.
    static CImg<T> get_load_yuv(const char *const filename,
                                const unsigned int size_x, const unsigned int size_y=1,
                                const unsigned int chroma_subsampling=444,
                                const unsigned int first_frame=0, const unsigned int last_frame=~0U,
                                const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') {
      return CImgList<T>().load_yuv(filename,size_x,size_y,chroma_subsampling,
                                    first_frame,last_frame,step_frame,yuv2rgb).get_append(axis);

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& draw_spline(const int x0, const int y0, const float u0, const float v0,
                         const int x1, const int y1, const float u1, const float v1,
                         const CImg<t>& texture,
                         const int tx0, const int ty0, const int tx1, const int ty1,
                         const float opacity=1,
                         const float precision=4, const unsigned int pattern=~0U,
                         const bool init_hatch=true) {
      if (texture._depth>1 || texture._spectrum<_spectrum)
        throw CImgArgumentException(_cimg_instance
                                    "draw_spline(): Invalid specified texture (%u,%u,%u,%u,%p).",
                                    cimg_instance,
                                    texture._width,texture._height,texture._depth,texture._spectrum,texture._data);
      if (is_empty()) return *this;
      if (is_overlapped(texture))
        return draw_spline(x0,y0,u0,v0,x1,y1,u1,v1,+texture,tx0,ty0,tx1,ty1,precision,opacity,pattern,init_hatch);
      if (x0==x1 && y0==y1)
        return draw_point(x0,y0,texture.get_vector_at(x0<=0?0:x0>=texture.width()?texture.width() - 1:x0,
                                                      y0<=0?0:y0>=texture.height()?texture.height() - 1:y0).data(),
                          opacity);
      bool ninit_hatch = init_hatch;
      const float
        ax = u0 + u1 + 2*(x0 - x1),
        bx = 3*(x1 - x0) - 2*u0 - u1,
        ay = v0 + v1 + 2*(y0 - y1),
        by = 3*(y1 - y0) - 2*v0 - v1,
        _precision = 1/(cimg::hypot((float)x0 - x1,(float)y0 - y1)*(precision>0?precision:1));
      int ox = x0, oy = y0, otx = tx0, oty = ty0;
      for (float t1 = 0; t1<1; t1+=_precision) {
        const float t2 = t1*t1, t3 = t2*t1;
        const int
          nx = (int)(ax*t3 + bx*t2 + u0*t1 + x0),
          ny = (int)(ay*t3 + by*t2 + v0*t1 + y0),
          ntx = tx0 + (int)((tx1 - tx0)*t1),
          nty = ty0 + (int)((ty1 - ty0)*t1);
        draw_line(ox,oy,nx,ny,texture,otx,oty,ntx,nty,opacity,pattern,ninit_hatch);
        ninit_hatch = false;
        ox = nx; oy = ny; otx = ntx; oty = nty;
      }
      return draw_line(ox,oy,x1,y1,texture,otx,oty,tx1,ty1,opacity,pattern,false);

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& _LU(CImg<t>& indx, bool& d) {
      const int N = width();
      int imax = 0;
      CImg<Tfloat> vv(N);
      indx.assign(N);
      d = true;

      bool return0 = false;
      cimg_pragma_openmp(parallel for cimg_openmp_if(_width*_height>=512))
      cimg_forX(*this,i) {
        Tfloat vmax = 0;
        cimg_forX(*this,j) {
          const Tfloat tmp = cimg::abs((*this)(j,i));
          if (tmp>vmax) vmax = tmp;
        }
        if (vmax==0) return0 = true; else vv[i] = 1/vmax;
      }
      if (return0) { indx.fill(0); return fill(0); }

      cimg_forX(*this,j) {
        for (int i = 0; i<j; ++i) {
          Tfloat sum = (*this)(j,i);
          for (int k = 0; k<i; ++k) sum-=(*this)(k,i)*(*this)(j,k);
          (*this)(j,i) = (T)sum;
        }

        Tfloat vmax = 0;
        for (int i = j; i<width(); ++i) {
          Tfloat sum = (*this)(j,i);
          for (int k = 0; k<j; ++k) sum-=(*this)(k,i)*(*this)(j,k);
          (*this)(j,i) = (T)sum;
          const Tfloat tmp = vv[i]*cimg::abs(sum);
          if (tmp>=vmax) { vmax = tmp; imax = i; }
        }
        if (j!=imax) {
          cimg_forX(*this,k) cimg::swap((*this)(k,imax),(*this)(k,j));
          d = !d;
          vv[imax] = vv[j];
        }
        indx[j] = (t)imax;
        if ((*this)(j,j)==0) (*this)(j,j) = (T)1e-20;
        if (j<N) {
          const Tfloat tmp = 1/(Tfloat)(*this)(j,j);
          for (int i = j + 1; i<N; ++i) (*this)(j,i) = (T)((*this)(j,i)*tmp);
        }
      }

      return *this;

Project: CImg
File: CImg.h

#ifdef cimg_use_half
    inline half ror(const half a, const unsigned int n=1) {
      return (half)ror((int)a,n);

Project: CImg
File: CImg.h


      static double mp_decrement(_cimg_math_parser& mp) {
        return _mp_arg(2) - 1;

Project: CImg
File: CImg.h

    **/
    static const CImg<Tuchar>& cool_LUT256() {
      static CImg<Tuchar> colormap;
      cimg::mutex(8);
      if (!colormap) colormap.assign(1,2,1,3).fill((T)0,(T)255,(T)255,(T)0,(T)255,(T)255).resize(1,256,1,3,3);
      cimg::mutex(8,0);
      return colormap;

Project: CImg
File: CImg.h

    template<typename tc>
    CImg<T>& draw_triangle(int x0, int y0,
                           int x1, int y1,
                           int x2, int y2,
                           const CImg<tc>& texture,
                           int tx0, int ty0,
                           int tx1, int ty1,
                           int tx2, int ty2,
                           float bs0,
                           float bs1,
                           float bs2,
                           const float opacity=1) {
      if (is_empty()) return *this;
      if (texture._depth>1 || texture._spectrum<_spectrum)
        throw CImgArgumentException(_cimg_instance
                                    "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).",
                                    cimg_instance,
                                    texture._width,texture._height,texture._depth,texture._spectrum,texture._data);
      if (is_overlapped(texture))
        return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,
                             bs0,bs1,bs2,opacity);

      if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1,bs0,bs1);
      if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2,bs0,bs2);
      if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,tx2,ty1,ty2,bs1,bs2);
      if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this;

      const int
        w1 = width() - 1, h1 = height() - 1,
        dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1,
        dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1),
        cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1),
        hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2,
        dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1,
        dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1,
        hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2,
        hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2;
      const float dbs01 = bs1 - bs0, dbs02 = bs2 - bs0, dbs12 = bs2 - bs1;

      const ulongT twhd = (ulongT)texture._width*texture._height*texture._depth;
      cimg_init_scanline(opacity);

      for (int y = cy0; y<=cy2; ++y) {
        const int yy0 = y - y0, yy1 = y - y1;
        int
          xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12,
          xM = x0 + (dx02*yy0 + hdy02)/dy02,
          txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12,
          txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02,
          tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12,
          tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02;
        float
          bsm = y<y1?(bs0 + dbs01*yy0/dy01):(bs1 + dbs12*yy1/dy12),
          bsM = bs0 + dbs02*yy0/dy02;
        if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM,bsm,bsM);
        if (xM>=0 || xm<=w1) {
          const int
            cxm = cimg::cut(xm,0,w1),
            cxM = cimg::cut(xM,0,w1);
          T *ptrd = data(cxm,y);
          const int
            dxmM = std::max(1,xM - xm), hdxmM = dxmM/2,
            dtxmM = txM - txm, dtymM = tyM - tym;
          const float dbsmM = bsM - bsm;

          for (int x = cxm; x<cxM; ++x) {
            const int
              xxm = x - xm,
              tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM,
              ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM;
            const float cbs = cimg::cut(bsm + dbsmM*xxm/dxmM,0,2);
            const tc *const color = &texture._atXY(tx,ty);
            cimg_forC(*this,c) {
              const tc col = color[c*twhd];
              const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval;
              ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity);
            }
            ++ptrd;
          }
        }
      }
      return *this;

Project: CImg
File: CImg.h

      static int cut(const double val) { return val<(double)min()?min():val>(double)max()?max():(int)val; }

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_camera(const unsigned int camera_index=0,
                         const unsigned int capture_width=0, const unsigned int capture_height=0,
                         const unsigned int skip_frames=0, const bool release_camera=true) {
#ifdef cimg_use_opencv
      if (camera_index>=64)
        throw CImgArgumentException(_cimg_instance
                                    "load_camera(): Invalid request for camera #%u "
                                    "(no more than 100 cameras can be managed simultaneously).",
                                    cimg_instance,
                                    camera_index);
      static cv::VideoCapture *captures[64] = { 0 };
      static unsigned int captures_w[64], captures_h[64];
      if (release_camera) {
        cimg::mutex(9);
        if (captures[camera_index]) captures[camera_index]->release();
        delete captures[camera_index];
        captures[camera_index] = 0;
        captures_w[camera_index] = captures_h[camera_index] = 0;
        cimg::mutex(9,0);
        return *this;
      }
      if (!captures[camera_index]) {
        cimg::mutex(9);
        captures[camera_index] = new cv::VideoCapture(camera_index);
        captures_w[camera_index] = captures_h[camera_index] = 0;
        if (!captures[camera_index]->isOpened()) {
          delete captures[camera_index];
          captures[camera_index] = 0;
          cimg::mutex(9,0);
          throw CImgIOException(_cimg_instance
                                "load_camera(): Failed to initialize camera #%u.",
                                cimg_instance,
                                camera_index);
        }
        cimg::mutex(9,0);
      }
      cimg::mutex(9);
      if (capture_width!=captures_w[camera_index]) {
        captures[camera_index]->set(_cimg_cap_prop_frame_width,capture_width);
        captures_w[camera_index] = capture_width;
      }
      if (capture_height!=captures_h[camera_index]) {
        captures[camera_index]->set(_cimg_cap_prop_frame_height,capture_height);
        captures_h[camera_index] = capture_height;
      }
      for (unsigned int i = 0; i<skip_frames; ++i) captures[camera_index]->grab();
      cv::Mat cvimg;
      captures[camera_index]->read(cvimg);
      if (cvimg.empty()) assign(); else _cvmat2cimg(cvimg).move_to(*this);
      cimg::mutex(9,0);
      return *this;
#else
      cimg::unused(camera_index,skip_frames,release_camera,capture_width,capture_height);
      throw CImgIOException(_cimg_instance
                            "load_camera(): This function requires the OpenCV library to run "
                            "(macro 'cimg_use_opencv' must be defined).",
                            cimg_instance);
#endif

Project: CImg
File: CImg.h

    **/
    CImg<T>& invert(const bool use_LU=true) {
      if (_width!=_height || _depth!=1 || _spectrum!=1)
        throw CImgInstanceException(_cimg_instance
                                    "invert(): Instance is not a square matrix.",
                                    cimg_instance);
      const double dete = _width>3?-1.:det();
      if (dete!=0. && _width==2) {
        const double
          a = _data[0], c = _data[1],
          b = _data[2], d = _data[3];
        _data[0] = (T)(d/dete); _data[1] = (T)(-c/dete);
        _data[2] = (T)(-b/dete); _data[3] = (T)(a/dete);
      } else if (dete!=0. && _width==3) {
        const double
          a = _data[0], d = _data[1], g = _data[2],
          b = _data[3], e = _data[4], h = _data[5],
          c = _data[6], f = _data[7], i = _data[8];
        _data[0] = (T)((i*e - f*h)/dete), _data[1] = (T)((g*f - i*d)/dete), _data[2] = (T)((d*h - g*e)/dete);
        _data[3] = (T)((h*c - i*b)/dete), _data[4] = (T)((i*a - c*g)/dete), _data[5] = (T)((g*b - a*h)/dete);
        _data[6] = (T)((b*f - e*c)/dete), _data[7] = (T)((d*c - a*f)/dete), _data[8] = (T)((a*e - d*b)/dete);
      } else {

#ifdef cimg_use_lapack
        int INFO = (int)use_LU, N = _width, LWORK = 4*N, *const IPIV = new int[N];
        Tfloat
          *const lapA = new Tfloat[N*N],
          *const WORK = new Tfloat[LWORK];
        cimg_forXY(*this,k,l) lapA[k*N + l] = (Tfloat)((*this)(k,l));
        cimg::getrf(N,lapA,IPIV,INFO);
        if (INFO)
          cimg::warn(_cimg_instance
                     "invert(): LAPACK function dgetrf_() returned error code %d.",
                     cimg_instance,
                     INFO);
        else {
          cimg::getri(N,lapA,IPIV,WORK,LWORK,INFO);
          if (INFO)
            cimg::warn(_cimg_instance
                       "invert(): LAPACK function dgetri_() returned error code %d.",
                       cimg_instance,
                       INFO);
        }
        if (!INFO) cimg_forXY(*this,k,l) (*this)(k,l) = (T)(lapA[k*N + l]); else fill(0);
        delete[] IPIV; delete[] lapA; delete[] WORK;
#else
        if (use_LU) { // LU-based inverse computation
          CImg<Tfloat> A(*this,false), indx, col(1,_width);
          bool d;
          A._LU(indx,d);
          cimg_forX(*this,j) {
            col.fill(0);
            col(j) = 1;
            col._solve(A,indx);
            cimg_forX(*this,i) (*this)(j,i) = (T)col(i);
          }
        } else { // SVD-based inverse computation
          CImg<Tfloat> U(_width,_width), S(1,_width), V(_width,_width);
          SVD(U,S,V,false);
          U.transpose();
          cimg_forY(S,k) if (S[k]!=0) S[k]=1/S[k];
          S.diagonal();
          *this = V*S*U;
        }
#endif
      }
      return *this;

Project: CImg
File: CImg.h


      static double mp_diag(_cimg_math_parser& mp) {
        const unsigned int i_end = (unsigned int)mp.opcode[2], siz = mp.opcode[2] - 3;
        double *ptrd = &_mp_arg(1) + 1;
        std::memset(ptrd,0,siz*siz*sizeof(double));
        for (unsigned int i = 3; i<i_end; ++i) { *(ptrd++) = _mp_arg(i); ptrd+=siz; }
        return cimg::type<double>::nan();

Project: CImg
File: CImg.h

    template<typename tc>
    CImg<T>& draw_text(const int x0, const int y0,
                       const char *const text,
                       const tc *const foreground_color, const int background_color=0,
                       const float opacity=1, const unsigned int font_height=13, ...) {
      if (!font_height) return *this;
      cimg::unused(background_color);
      CImg<charT> tmp(2048);
      std::va_list ap; va_start(ap,font_height);
      cimg_vsnprintf(tmp,tmp._width,text,ap); va_end(ap);
      return draw_text(x0,y0,"%s",foreground_color,(const tc*)0,opacity,font_height,tmp._data);

Project: CImg
File: CImg.h

    template<typename t>
    CImg<intT> get_matchpatch(const CImg<T>& patch_image,
                              const unsigned int patch_width,
                              const unsigned int patch_height,
                              const unsigned int patch_depth,
                              const unsigned int nb_iterations=5,
                              const unsigned int nb_randoms=5,
                              const float occ_penalization=0,
                              const CImg<t> &guide=CImg<t>::const_empty()) const {
      CImg<T> matching_score;
      return _matchpatch(patch_image,patch_width,patch_height,patch_depth,
                         nb_iterations,nb_randoms,occ_penalization,guide,false,matching_score);

Project: CImg
File: CImg.h


    inline double rol(const double a, const unsigned int n=1) {
      return (double)rol((cimg_long)a,n);

Project: CImg
File: CImg.h

    **/
    CImg<T>& crop(const int x0, const int y0, const int z0, const int c0,
                  const int x1, const int y1, const int z1, const int c1,
                  const unsigned int boundary_conditions=0) {
      return get_crop(x0,y0,z0,c0,x1,y1,z1,c1,boundary_conditions).move_to(*this);

Project: CImg
File: CImg.h

    //! Discard neighboring duplicates in the image buffer, along the specified axis \newinstance.
    CImg<T> get_discard(const char axis=0) const {
      CImg<T> res;
      if (is_empty()) return res;
      const char _axis = cimg::lowercase(axis);
      T current = *_data?(T)0:(T)1;
      int j = 0;
      res.assign(width(),height(),depth(),spectrum());
      switch (_axis) {
      case 'x' : {
        cimg_forX(*this,i)
          if ((*this)(i)!=current) { res.draw_image(j++,get_column(i)); current = (*this)(i); }
        res.resize(j,-100,-100,-100,0);
      } break;
      case 'y' : {
        cimg_forY(*this,i)
          if ((*this)(0,i)!=current) { res.draw_image(0,j++,get_row(i)); current = (*this)(0,i); }
        res.resize(-100,j,-100,-100,0);
      } break;
      case 'z' : {
        cimg_forZ(*this,i)
          if ((*this)(0,0,i)!=current) { res.draw_image(0,0,j++,get_slice(i)); current = (*this)(0,0,i); }
        res.resize(-100,-100,j,-100,0);
      } break;
      case 'c' : {
        cimg_forC(*this,i)
          if ((*this)(0,0,0,i)!=current) { res.draw_image(0,0,0,j++,get_channel(i)); current = (*this)(0,0,0,i); }
        res.resize(-100,-100,-100,j,0);
      } break;
      default : {
        res.unroll('y');
        cimg_foroff(*this,i)
          if ((*this)[i]!=current) res[j++] = current = (*this)[i];
        res.resize(-100,j,-100,-100,0);
      }
      }
      return res;

Project: CImg
File: CImg.h

    **/
    CImgDisplay(const unsigned int width, const unsigned int height,
                const char *const title=0, const unsigned int normalization=3,
                const bool is_fullscreen=false, const bool is_closed=false):
      _width(0),_height(0),_normalization(0),
      _min(0),_max(0),
      _is_fullscreen(false),
      _title(0),
      _window_width(0),_window_height(0),_button(0),
      _keys(new unsigned int[128]),_released_keys(new unsigned int[128]),
      _window_x(0),_window_y(0),_mouse_x(-1),_mouse_y(-1),_wheel(0),
      _is_closed(true),_is_resized(false),_is_moved(false),_is_event(false) {
      assign(width,height,title,normalization,is_fullscreen,is_closed);

Project: CImg
File: CImg.h

    //! Construct image with specified size and initialize pixel values from a memory buffer \specialization.
    CImg<T>& assign(const T *const values, const unsigned int size_x, const unsigned int size_y=1,
                    const unsigned int size_z=1, const unsigned int size_c=1) {
      const size_t siz = (size_t)size_x*size_y*size_z*size_c;
      if (!values || !siz) return assign();
      const size_t curr_siz = (size_t)size();
      if (values==_data && siz==curr_siz) return assign(size_x,size_y,size_z,size_c);
      if (_is_shared || values + siz<_data || values>=_data + size()) {
        assign(size_x,size_y,size_z,size_c);
        if (_is_shared) std::memmove((void*)_data,(void*)values,siz*sizeof(T));
        else std::memcpy((void*)_data,(void*)values,siz*sizeof(T));
      } else {
        T *new_data = 0;
        try { new_data = new T[siz]; } catch (...) {
          _width = _height = _depth = _spectrum = 0; _data = 0;
          throw CImgInstanceException(_cimg_instance
                                      "assign(): Failed to allocate memory (%s) for image (%u,%u,%u,%u).",
                                      cimg_instance,
                                      cimg::strbuffersize(sizeof(T)*size_x*size_y*size_z*size_c),
                                      size_x,size_y,size_z,size_c);
        }
        std::memcpy((void*)new_data,(void*)values,siz*sizeof(T));
        delete[] _data; _data = new_data; _width = size_x; _height = size_y; _depth = size_z; _spectrum = size_c;
      }
      return *this;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& div(const CImg<t>& img) {
      const ulongT siz = size(), isiz = img.size();
      if (siz && isiz) {
        if (is_overlapped(img)) return div(+img);
        T *ptrd = _data, *const ptre = _data + siz;
        if (siz>isiz) for (ulongT n = siz/isiz; n; --n)
          for (const t *ptrs = img._data, *ptrs_end = ptrs + isiz; ptrs<ptrs_end; ++ptrd)
            *ptrd = (T)(*ptrd / *(ptrs++));
        for (const t *ptrs = img._data; ptrd<ptre; ++ptrd) *ptrd = (T)(*ptrd / *(ptrs++));
      }
      return *this;

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_yuv(const char *const filename,
                      const unsigned int size_x, const unsigned int size_y=1,
                      const unsigned int chroma_subsampling=444,
                      const unsigned int first_frame=0, const unsigned int last_frame=~0U,
                      const unsigned int step_frame=1, const bool yuv2rgb=true, const char axis='z') {
      return get_load_yuv(filename,size_x,size_y,chroma_subsampling,
                          first_frame,last_frame,step_frame,yuv2rgb,axis).move_to(*this);

Project: CImg
File: CImg.h


    CImgDisplay& hide_mouse() {
      if (is_empty()) return *this;
      Display *const dpy = cimg::X11_attr().display;
      cimg_lock_display();
      static const char pix_data[8] = { 0 };
      XColor col;
      col.red = col.green = col.blue = 0;
      Pixmap pix = XCreateBitmapFromData(dpy,_window,pix_data,8,8);
      Cursor cur = XCreatePixmapCursor(dpy,pix,pix,&col,&col,0,0);
      XFreePixmap(dpy,pix);
      XDefineCursor(dpy,_window,cur);
      cimg_unlock_display();
      return *this;

Project: CImg
File: CImg.h


      static double mp_set_Joff_s(_cimg_math_parser& mp) {
        CImg<T> &img = mp.imgout;
        const int
          ox = (int)mp.mem[_cimg_mp_slot_x], oy = (int)mp.mem[_cimg_mp_slot_y],
          oz = (int)mp.mem[_cimg_mp_slot_z], oc = (int)mp.mem[_cimg_mp_slot_c];
        const longT
          off = img.offset(ox,oy,oz,oc) + (longT)_mp_arg(2),
          whd = (longT)img.width()*img.height()*img.depth();
        const T val = (T)_mp_arg(1);
        if (off>=0 && off<whd) {
          T *ptrd = &img[off];
          cimg_forC(img,c) { *ptrd = val; ptrd+=whd; }
        }
        return _mp_arg(1);

Project: CImg
File: CImg.h


      static double mp_list_set_ioff(_cimg_math_parser& mp) {
        const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width());
        CImg<T> &img = mp.listout[ind];
        const longT
          off = (longT)_mp_arg(3),
          whds = (longT)img.size();
        const double val = _mp_arg(1);
        if (off>=0 && off<whds) img[off] = (T)val;
        return val;

Project: CImg
File: CImg.h


      static double mp_vector_print(_cimg_math_parser& mp) {
        const bool print_string = (bool)mp.opcode[4];
        cimg_pragma_openmp(critical(mp_vector_print))
        {
          CImg<charT> _expr(mp.opcode[2] - 5);
          const ulongT *ptrs = mp.opcode._data + 5;
          cimg_for(_expr,ptrd,char) *ptrd = (char)*(ptrs++);
          cimg::strellipsize(_expr);
          unsigned int
            ptr = (unsigned int)mp.opcode[1] + 1,
            siz0 = (unsigned int)mp.opcode[3],
            siz = siz0;
          cimg::mutex(6);
          std::fprintf(cimg::output(),"\n[" cimg_appname "_math_parser] %s = [ ",_expr._data);
          unsigned int count = 0;
          while (siz-->0) {
            if (count>=64 && siz>=64) {
              std::fprintf(cimg::output(),"...,");
              ptr = (unsigned int)mp.opcode[1] + 1 + siz0 - 64;
              siz = 64;
            } else std::fprintf(cimg::output(),"%g%s",mp.mem[ptr++],siz?",":"");
            ++count;
          }
          if (print_string) {
            CImg<charT> str(siz0 + 1);
            ptr = (unsigned int)mp.opcode[1] + 1;
            for (unsigned int k = 0; k<siz0; ++k) str[k] = (char)mp.mem[ptr++];
            str[siz0] = 0;
            cimg::strellipsize(str,1024,false);
            std::fprintf(cimg::output()," ] = '%s' (size: %u)",str._data,siz0);
          } else std::fprintf(cimg::output()," ] (size: %u)",siz0);
          std::fflush(cimg::output());
          cimg::mutex(6,0);
        }
        return cimg::type<double>::nan();

Project: CImg
File: CImg.h

    **/
    Tfloat linear_atXYZC(const float fx, const float fy, const float fz, const float fc, const T& out_value) const {
      const int
        x = (int)fx - (fx>=0?0:1), nx = x + 1,
        y = (int)fy - (fy>=0?0:1), ny = y + 1,
        z = (int)fz - (fz>=0?0:1), nz = z + 1,
        c = (int)fc - (fc>=0?0:1), nc = c + 1;
      const float
        dx = fx - x,
        dy = fy - y,
        dz = fz - z,
        dc = fc - c;
      const Tfloat
        Icccc = (Tfloat)atXYZC(x,y,z,c,out_value), Inccc = (Tfloat)atXYZC(nx,y,z,c,out_value),
        Icncc = (Tfloat)atXYZC(x,ny,z,c,out_value), Inncc = (Tfloat)atXYZC(nx,ny,z,c,out_value),
        Iccnc = (Tfloat)atXYZC(x,y,nz,c,out_value), Incnc = (Tfloat)atXYZC(nx,y,nz,c,out_value),
        Icnnc = (Tfloat)atXYZC(x,ny,nz,c,out_value), Innnc = (Tfloat)atXYZC(nx,ny,nz,c,out_value),
        Icccn = (Tfloat)atXYZC(x,y,z,nc,out_value), Inccn = (Tfloat)atXYZC(nx,y,z,nc,out_value),
        Icncn = (Tfloat)atXYZC(x,ny,z,nc,out_value), Inncn = (Tfloat)atXYZC(nx,ny,z,nc,out_value),
        Iccnn = (Tfloat)atXYZC(x,y,nz,nc,out_value), Incnn = (Tfloat)atXYZC(nx,y,nz,nc,out_value),
        Icnnn = (Tfloat)atXYZC(x,ny,nz,nc,out_value), Innnn = (Tfloat)atXYZC(nx,ny,nz,nc,out_value);
      return Icccc +
        dx*(Inccc - Icccc +
            dy*(Icccc + Inncc - Icncc - Inccc +
                dz*(Iccnc + Innnc + Icncc + Inccc - Icnnc - Incnc - Icccc - Inncc +
                    dc*(Iccnn + Innnn + Icncn + Inccn + Icnnc + Incnc + Icccc + Inncc -
                        Icnnn - Incnn - Icccn - Inncn - Iccnc - Innnc - Icncc - Inccc)) +
                dc*(Icccn + Inncn + Icncc + Inccc - Icncn - Inccn - Icccc - Inncc)) +
            dz*(Icccc + Incnc - Iccnc - Inccc +
                dc*(Icccn + Incnn + Iccnc + Inccc - Iccnn - Inccn - Icccc - Incnc)) +
            dc*(Icccc + Inccn - Inccc - Icccn)) +
        dy*(Icncc - Icccc +
            dz*(Icccc + Icnnc - Iccnc - Icncc +
                dc*(Icccn + Icnnn + Iccnc + Icncc - Iccnn - Icncn - Icccc - Icnnc)) +
            dc*(Icccc + Icncn - Icncc - Icccn)) +
        dz*(Iccnc - Icccc +
            dc*(Icccc + Iccnn - Iccnc - Icccn)) +
        dc*(Icccn  -Icccc);

Project: CImg
File: CImg.h


    T& _atX(const int x, const int y=0, const int z=0, const int c=0) {
      return (*this)(x<0?0:(x>=width()?width() - 1:x),y,z,c);

Project: CImg
File: CImg.h

#else
    CImg<T> *data(const unsigned int l) {
      return _data + l;

Project: CImg
File: CImg.h

    //! Return a \c 1x7 image containing specified values.
    static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3,
			  const T& a4, const T& a5, const T& a6) {
      CImg<T> r(1,7); T *ptr = r._data;
      *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3;
      *(ptr++) = a4; *(ptr++) = a5; *(ptr++) = a6;
      return r;

Project: CImg
File: CImg.h


      static double mp_transp(_cimg_math_parser& mp) {
        double *ptrd = &_mp_arg(1) + 1;
        const double *ptrs = &_mp_arg(2) + 1;
        const unsigned int
          k = (unsigned int)mp.opcode[3],
          l = (unsigned int)mp.opcode[4];
        CImg<doubleT>(ptrd,l,k,1,1,true) = CImg<doubleT>(ptrs,k,l,1,1,true).get_transpose();
        return cimg::type<double>::nan();

Project: CImg
File: CImg.h

    **/
    T cubic_atXYZ_c(const float fx, const float fy, const float fz, const int c, const T& out_value) const {
      return cimg::type<T>::cut(cubic_atXYZ(fx,fy,fz,c,out_value));

Project: CImg
File: CImg.h


      static double mp_set_jxyzc(_cimg_math_parser& mp) {
        CImg<T> &img = mp.imgout;
        const double
          ox = mp.mem[_cimg_mp_slot_x], oy = mp.mem[_cimg_mp_slot_y],
          oz = mp.mem[_cimg_mp_slot_z], oc = mp.mem[_cimg_mp_slot_c];
        const int
          x = (int)(ox + _mp_arg(2)), y = (int)(oy + _mp_arg(3)),
          z = (int)(oz + _mp_arg(4)), c = (int)(oc + _mp_arg(5));
        const double val = _mp_arg(1);
        if (x>=0 && x<img.width() && y>=0 && y<img.height() &&
            z>=0 && z<img.depth() && c>=0 && c<img.spectrum())
          img(x,y,z,c) = (T)val;
        return val;

Project: CImg
File: CImg.h

    //! Test if image width is equal to specified value.
    bool is_sameX(const unsigned int size_x) const {
      return _width==size_x;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<_cimg_Tt> operator-(const CImg<t>& img) const {
      return CImg<_cimg_Tt>(*this,false)-=img;

Project: CImg
File: CImg.h

    **/
    CImg<T>& front() {
      return *_data;

Project: CImg
File: CImg.h

    }
    inline int mod(const int x, const int m) {
      return x>=0?x%m:(x%m?m + x%m:0);

Project: CImg
File: CImg.h

    **/
    CImgDisplay& assign(const CImgDisplay &disp) {
      _no_display_exception();
      return assign(disp._width,disp._height);

Project: CImg
File: CImg.h

    //! Resize image to half-size along XY axes, using an optimized filter \newinstance.
    CImg<T> get_resize_halfXY() const {
      if (is_empty()) return *this;
      static const Tfloat kernel[9] = { 0.07842776544f, 0.1231940459f, 0.07842776544f,
                                        0.1231940459f,  0.1935127547f, 0.1231940459f,
                                        0.07842776544f, 0.1231940459f, 0.07842776544f };
      CImg<T> I(9), res(_width/2,_height/2,_depth,_spectrum);
      T *ptrd = res._data;
      cimg_forZC(*this,z,c) cimg_for3x3(*this,x,y,z,c,I,T)
        if (x%2 && y%2) *(ptrd++) = (T)
                          (I[0]*kernel[0] + I[1]*kernel[1] + I[2]*kernel[2] +
                           I[3]*kernel[3] + I[4]*kernel[4] + I[5]*kernel[5] +
                           I[6]*kernel[6] + I[7]*kernel[7] + I[8]*kernel[8]);
      return res;

Project: CImg
File: CImg.h

    template<typename tc, typename tl>
    CImg<T>& draw_triangle(int x0, int y0,
                           int x1, int y1,
                           int x2, int y2,
                           const CImg<tc>& texture,
                           int tx0, int ty0,
                           int tx1, int ty1,
                           int tx2, int ty2,
                           const CImg<tl>& light,
                           int lx0, int ly0,
                           int lx1, int ly1,
                           int lx2, int ly2,
                           const float opacity=1) {
      if (is_empty()) return *this;
      if (texture._depth>1 || texture._spectrum<_spectrum)
        throw CImgArgumentException(_cimg_instance
                                    "draw_triangle(): Invalid specified texture (%u,%u,%u,%u,%p).",
                                    cimg_instance,
                                    texture._width,texture._height,texture._depth,texture._spectrum,texture._data);
      if (light._depth>1 || light._spectrum<_spectrum)
        throw CImgArgumentException(_cimg_instance
                                    "draw_triangle(): Invalid specified light texture (%u,%u,%u,%u,%p).",
                                    cimg_instance,light._width,light._height,light._depth,light._spectrum,light._data);
      if (is_overlapped(texture))
        return draw_triangle(x0,y0,x1,y1,x2,y2,+texture,tx0,ty0,tx1,ty1,tx2,ty2,light,lx0,ly0,lx1,ly1,lx2,ly2,opacity);
      if (is_overlapped(light))
        return draw_triangle(x0,y0,x1,y1,x2,y2,texture,tx0,ty0,tx1,ty1,tx2,ty2,+light,lx0,ly0,lx1,ly1,lx2,ly2,opacity);

      if (y0>y1) cimg::swap(x0,x1,y0,y1,tx0,tx1,ty0,ty1,lx0,lx1,ly0,ly1);
      if (y0>y2) cimg::swap(x0,x2,y0,y2,tx0,tx2,ty0,ty2,lx0,lx2,ly0,ly2);
      if (y1>y2) cimg::swap(x1,x2,y1,y2,tx1,tx2,ty1,ty2,lx1,lx2,ly1,ly2);
      if (y2<0 || y0>=height() || cimg::min(x0,x1,x2)>=width() || cimg::max(x0,x1,x2)<0 || !opacity) return *this;

      const int
        w1 = width() - 1, h1 = height() - 1,
        dx01 = x1 - x0, dx02 = x2 - x0, dx12 = x2 - x1,
        dy01 = std::max(1,y1 - y0), dy02 = std::max(1,y2 - y0), dy12 = std::max(1,y2 - y1),
        cy0 = cimg::cut(y0,0,h1), cy2 = cimg::cut(y2,0,h1),
        hdy01 = dy01*cimg::sign(dx01)/2, hdy02 = dy02*cimg::sign(dx02)/2, hdy12 = dy12*cimg::sign(dx12)/2,
        dtx01 = tx1 - tx0, dtx02 = tx2 - tx0, dtx12 = tx2 - tx1,
        dty01 = ty1 - ty0, dty02 = ty2 - ty0, dty12 = ty2 - ty1,
        hdy01tx = dy01*cimg::sign(dtx01)/2, hdy02tx = dy02*cimg::sign(dtx02)/2, hdy12tx = dy12*cimg::sign(dtx12)/2,
        hdy01ty = dy01*cimg::sign(dty01)/2, hdy02ty = dy02*cimg::sign(dty02)/2, hdy12ty = dy12*cimg::sign(dty12)/2,
        dlx01 = lx1 - lx0, dlx02 = lx2 - lx0, dlx12 = lx2 - lx1,
        dly01 = ly1 - ly0, dly02 = ly2 - ly0, dly12 = ly2 - ly1,
        hdy01lx = dy01*cimg::sign(dlx01)/2, hdy02lx = dy02*cimg::sign(dlx02)/2, hdy12lx = dy12*cimg::sign(dlx12)/2,
        hdy01ly = dy01*cimg::sign(dly01)/2, hdy02ly = dy02*cimg::sign(dly02)/2, hdy12ly = dy12*cimg::sign(dly12)/2;

      const ulongT
        twhd = (ulongT)texture._width*texture._height*texture._depth,
        lwhd = (ulongT)light._width*light._height*light._depth;
      cimg_init_scanline(opacity);

      for (int y = cy0; y<=cy2; ++y) {
        const int yy0 = y - y0, yy1 = y - y1;
        int
          xm = y<y1?x0 + (dx01*yy0 + hdy01)/dy01:x1 + (dx12*yy1 + hdy12)/dy12,
          xM = x0 + (dx02*yy0 + hdy02)/dy02,
          txm = y<y1?tx0 + (dtx01*yy0 + hdy01tx)/dy01:tx1 + (dtx12*yy1 + hdy12tx)/dy12,
          txM = tx0 + (dtx02*yy0 + hdy02tx)/dy02,
          tym = y<y1?ty0 + (dty01*yy0 + hdy01ty)/dy01:ty1 + (dty12*yy1 + hdy12ty)/dy12,
          tyM = ty0 + (dty02*yy0 + hdy02ty)/dy02,
          lxm = y<y1?lx0 + (dlx01*yy0 + hdy01lx)/dy01:lx1 + (dlx12*yy1 + hdy12lx)/dy12,
          lxM = lx0 + (dlx02*yy0 + hdy02lx)/dy02,
          lym = y<y1?ly0 + (dly01*yy0 + hdy01ly)/dy01:ly1 + (dly12*yy1 + hdy12ly)/dy12,
          lyM = ly0 + (dly02*yy0 + hdy02ly)/dy02;
        if (xm>xM) cimg::swap(xm,xM,txm,txM,tym,tyM,lxm,lxM,lym,lyM);
        if (xM>=0 || xm<=w1) {
          const int
            cxm = cimg::cut(xm,0,w1),
            cxM = cimg::cut(xM,0,w1);
          T *ptrd = data(cxm,y);
          const int
            dxmM = std::max(1,xM - xm), hdxmM = dxmM/2,
            dtxmM = txM - txm, dtymM = tyM - tym,
            dlxmM = lxM - lxm, dlymM = lyM - lym;

          for (int x = cxm; x<cxM; ++x) {
            const int
              xxm = x - xm,
              tx = (txm*dxmM + dtxmM*xxm + hdxmM)/dxmM,
              ty = (tym*dxmM + dtymM*xxm + hdxmM)/dxmM,
              lx = (lxm*dxmM + dlxmM*xxm + hdxmM)/dxmM,
              ly = (lym*dxmM + dlymM*xxm + hdxmM)/dxmM;
            const tc *const color = &texture._atXY(tx,ty);
            const tl *const lig = &light._atXY(lx,ly);
            cimg_forC(*this,c) {
              const tc col = color[c*twhd];
              const float cbs = cimg::cut((float)lig[c*lwhd],0,2);
              const Tfloat val = cbs<=1?cbs*col:(2 - cbs)*col + (cbs - 1)*_sc_maxval;
              ptrd[c*_sc_whd] = (T)(opacity>=1?val:val*_sc_nopacity + ptrd[c*_sc_whd]*_sc_copacity);
            }
            ++ptrd;
          }
        }
      }
      return *this;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& operator/=(const t value) {
      if (is_empty()) return *this;
      cimg_openmp_for(*this,*ptr / value,32768);
      return *this;

Project: CImg
File: CImg.h

    template<typename t>
    CImgList<t>& move_to(CImgList<t>& list, const unsigned int pos) {
      if (is_empty()) return list;
      const unsigned int npos = pos>list._width?list._width:pos;
      list.insert(_width,npos);
      bool is_one_shared_element = false;
      cimglist_for(*this,l) is_one_shared_element|=_data[l]._is_shared;
      if (is_one_shared_element) cimglist_for(*this,l) list[npos + l].assign(_data[l]);
      else cimglist_for(*this,l) _data[l].move_to(list[npos + l]);
      assign();
      return list;

Project: CImg
File: CImg.h

      static bool is_float() { return false; }

Project: CImg
File: CImg.h

    **/
    const CImg<T>& save_pfm(const char *const filename) const {
      get_mirror('y')._save_pfm(0,filename);
      return *this;

Project: CImg
File: CImg.h


      static double mp_list_set_Ixyz_s(_cimg_math_parser& mp) {
        const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width());
        CImg<T> &img = mp.listout[ind];
        const int
          x = (int)_mp_arg(3),
          y = (int)_mp_arg(4),
          z = (int)_mp_arg(5);
        const T val = (T)_mp_arg(1);
        if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) {
          T *ptrd = &img(x,y,z);
          const ulongT whd = (ulongT)img._width*img._height*img._depth;
          cimg_forC(img,c) { *ptrd = val; ptrd+=whd; }
        }
        return _mp_arg(1);

Project: CImg
File: CImg.h

    //! Invert the instance image, viewed as a matrix \newinstance.
    CImg<Tfloat> get_invert(const bool use_LU=true) const {
      return CImg<Tfloat>(*this,false).invert(use_LU);

Project: CImg
File: CImg.h

    //! Autocrop image region, regarding the specified background color \newinstance.
    CImg<T> get_autocrop(const T *const color=0, const char *const axes="zyx") const {
      return (+*this).autocrop(color,axes);

Project: CImg
File: CImg.h

      static float min() { return -FLT_MAX; }

Project: CImg
File: CImg.h


      static double mp_srand(_cimg_math_parser& mp) {
        mp.rng = (ulongT)_mp_arg(2);
        return cimg::type<double>::nan();

Project: CImg
File: CImg.h

    /**
       \param[out] min_val Value of the minimum value found.
    **/
    template<typename t>
    T& max_min(t& min_val) {
      bool is_all_empty = true;
      T *ptr_max = 0;
      cimglist_for(*this,l) if (!_data[l].is_empty()) {
        ptr_max = _data[l]._data;
        is_all_empty = false;
        break;
      }
      if (is_all_empty)
        throw CImgInstanceException(_cimglist_instance
                                    "max_min(): %s.",
                                    _data?"List of empty images":"Empty instance",
                                    cimglist_instance);
      T min_value = *ptr_max, max_value = min_value;
      cimglist_for(*this,l) {
        const CImg<T>& img = _data[l];
        cimg_for(img,ptrs,T) {
          const T val = *ptrs;
          if (val>max_value) { max_value = val; ptr_max = ptrs; }
          if (val<min_value) min_value = val;
        }

Project: CImg
File: CImg.h


    void _set_colormap(Colormap& cmap, const unsigned int dim) {
      XColor *const colormap = new XColor[256];
      switch (dim) {
      case 1 : { // colormap for greyscale images
        for (unsigned int index = 0; index<256; ++index) {
          colormap[index].pixel = index;
          colormap[index].red = colormap[index].green = colormap[index].blue = (unsigned short)(index<<8);
          colormap[index].flags = DoRed | DoGreen | DoBlue;
        }
      } break;
      case 2 : { // colormap for RG images
        for (unsigned int index = 0, r = 8; r<256; r+=16)
          for (unsigned int g = 8; g<256; g+=16) {
            colormap[index].pixel = index;
            colormap[index].red = colormap[index].blue = (unsigned short)(r<<8);
            colormap[index].green = (unsigned short)(g<<8);
            colormap[index++].flags = DoRed | DoGreen | DoBlue;
          }
      } break;
      default : { // colormap for RGB images
        for (unsigned int index = 0, r = 16; r<256; r+=32)
          for (unsigned int g = 16; g<256; g+=32)
            for (unsigned int b = 32; b<256; b+=64) {
              colormap[index].pixel = index;
              colormap[index].red = (unsigned short)(r<<8);
              colormap[index].green = (unsigned short)(g<<8);
              colormap[index].blue = (unsigned short)(b<<8);
              colormap[index++].flags = DoRed | DoGreen | DoBlue;
            }
      }
      }
      XStoreColors(cimg::X11_attr().display,cmap,colormap,256);
      delete[] colormap;

Project: CImg
File: CImg.h

    **/
    inline cimg_long wait(const unsigned int milliseconds) {
      cimg::mutex(3);
      static cimg_ulong timer = cimg::time();
      cimg::mutex(3,0);
      return cimg::wait(milliseconds,&timer);

Project: CImg
File: CImg.h

    template<typename t>
    CImg<_cimg_Tt> get_max(const CImg<t>& img) const {
      return CImg<_cimg_Tt>(*this,false).max(img);

Project: CImg
File: CImg.h

    //! Load image from a RGB file \newinstance.
    static CImg<T> get_load_rgb(const char *const filename, const unsigned int dimw, const unsigned int dimh=1) {
      return CImg<T>().load_rgb(filename,dimw,dimh);

Project: CImg
File: CImg.h


      static double mp_pow(_cimg_math_parser& mp) {
        const double v = _mp_arg(2), p = _mp_arg(3);
        return std::pow(v,p);

Project: CImg
File: CImg.h

    template<typename t>
    CImg<doubleT> eval(const char *const expression, const CImg<t>& xyzc,
                       const CImgList<T> *const list_inputs=0, CImgList<T> *const list_outputs=0) {
      return _eval(this,expression,xyzc,list_inputs,list_outputs);

Project: CImg
File: CImg.h

    template<typename t>
    double variance_mean(const unsigned int variance_method, t& mean) const {
      if (is_empty())
        throw CImgInstanceException(_cimg_instance
                                    "variance_mean(): Empty instance.",
                                    cimg_instance);

      double variance = 0, average = 0;
      const ulongT siz = size();
      switch (variance_method) {
      case 0 : { // Least mean square (standard definition)
        double S = 0, S2 = 0;
        cimg_for(*this,ptrs,T) { const double val = (double)*ptrs; S+=val; S2+=val*val; }
        variance = (S2 - S*S/siz)/siz;
        average = S;
      } break;
      case 1 : { // Least mean square (robust definition)
        double S = 0, S2 = 0;
        cimg_for(*this,ptrs,T) { const double val = (double)*ptrs; S+=val; S2+=val*val; }
        variance = siz>1?(S2 - S*S/siz)/(siz - 1):0;
        average = S;
      } break;
      case 2 : { // Least Median of Squares (MAD)
        CImg<Tfloat> buf(*this,false);
        buf.sort();
        const ulongT siz2 = siz>>1;
        const double med_i = (double)buf[siz2];
        cimg_for(buf,ptrs,Tfloat) {
          const double val = (double)*ptrs; *ptrs = (Tfloat)cimg::abs(val - med_i); average+=val;
        }
        buf.sort();
        const double sig = (double)(1.4828*buf[siz2]);
        variance = sig*sig;
      } break;
      default : { // Least trimmed of Squares
        CImg<Tfloat> buf(*this,false);
        const ulongT siz2 = siz>>1;
        cimg_for(buf,ptrs,Tfloat) {
          const double val = (double)*ptrs; (*ptrs)=(Tfloat)((*ptrs)*val); average+=val;
        }
        buf.sort();
        double a = 0;
        const Tfloat *ptrs = buf._data;
        for (ulongT j = 0; j<siz2; ++j) a+=(double)*(ptrs++);
        const double sig = (double)(2.6477*std::sqrt(a/siz2));
        variance = sig*sig;
      }
      }
      mean = (t)(average/siz);
      return variance>0?variance:0;

Project: CImg
File: CImg.h

    //! Convert pixel values from RGB to CMY color spaces.
    CImg<T>& RGBtoCMY() {
      if (_spectrum!=3)
        throw CImgInstanceException(_cimg_instance
                                    "RGBtoCMY(): Instance is not a RGB image.",
                                    cimg_instance);

      T *p1 = data(0,0,0,0), *p2 = data(0,0,0,1), *p3 = data(0,0,0,2);
      const longT whd = (longT)width()*height()*depth();
      cimg_pragma_openmp(parallel for cimg_openmp_if_size(whd,2048))
      for (longT N = 0; N<whd; ++N) {
        const Tfloat
          R = (Tfloat)p1[N],
          G = (Tfloat)p2[N],
          B = (Tfloat)p3[N],
          C = 255 - R,
          M = 255 - G,
          Y = 255 - B;
        p1[N] = (T)cimg::cut(C,0,255),
        p2[N] = (T)cimg::cut(M,0,255),
        p3[N] = (T)cimg::cut(Y,0,255);
      }
      return *this;

Project: CImg
File: CImg.h

       \param user_path Specified path, or \c 0 to get the path currently used.
       \param reinit_path Force path to be recalculated (may take some time).
       \return Path containing the \c gm binary.
    **/
    inline const char* graphicsmagick_path(const char *const user_path, const bool reinit_path) {
      static CImg<char> s_path;
      cimg::mutex(7);
      if (reinit_path) s_path.assign();
      if (user_path) {
        if (!s_path) s_path.assign(1024);
        std::strncpy(s_path,user_path,1023);
      } else if (!s_path) {
        s_path.assign(1024);
        bool path_found = false;
        std::FILE *file = 0;
#if cimg_OS==2
        const char *const pf_path = programfiles_path();
        if (!path_found) {
          std::strcpy(s_path,".\\gm.exe");
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=10 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%.2d-\\gm.exe",pf_path,k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 9; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d-Q\\gm.exe",pf_path,k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d\\gm.exe",pf_path,k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=10 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",pf_path,k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 9; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",pf_path,k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"%s\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",pf_path,k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=10 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%.2d-\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 9; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d-Q\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=10 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 9; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"C:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=10 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%.2d-\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 9; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d-Q\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=10 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%.2d-\\VISUA~1\\BIN\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 9; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d-Q\\VISUA~1\\BIN\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        for (int k = 32; k>=0 && !path_found; --k) {
          cimg_snprintf(s_path,s_path._width,"D:\\GRAPHI~1.%d\\VISUA~1\\BIN\\gm.exe",k);
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        if (!path_found) std::strcpy(s_path,"gm.exe");
#else
        if (!path_found) {
          std::strcpy(s_path,"./gm");
          if ((file=cimg::std_fopen(s_path,"r"))!=0) { cimg::fclose(file); path_found = true; }
        }
        if (!path_found) std::strcpy(s_path,"gm");
#endif
        winformat_string(s_path);

Project: CImg
File: CImg.h

    //! Return specified image column \inplace.
    CImg<T>& column(const int x0) {
      return columns(x0,x0);

Project: CImg
File: CImg.h

  template<typename T>
  inline bool operator!=(const char *const expression, const CImg<T>& img) {
    return img!=expression;

Project: CImg
File: CImg.h

    **/
    const CImg<T>& save_jpeg(const char *const filename, const unsigned int quality=100) const {
      return _save_jpeg(0,filename,quality);

Project: CImg
File: CImg.h

    //! Convert pixel values from RGB to Lab color spaces.
    CImg<T>& RGBtoLab(const bool use_D65=true) {
      return RGBtoXYZ(use_D65).XYZtoLab(use_D65);

Project: CImg
File: CImg.h

    }
    inline double lowercase(const double x) {
      return (double)((x<'A'||x>'Z')?x:x - 'A' + 'a');

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& convolve(const CImg<t>& kernel, const bool boundary_conditions=true,
                      const bool is_normalized=false, const int dilation=1) {
      if (is_empty() || !kernel) return *this;
      return get_convolve(kernel,boundary_conditions,is_normalized,dilation).move_to(*this);

Project: CImg
File: CImg.h

    template<typename tc>
    CImg<T>& draw_fill(const int x0, const int y0,
                       const tc *const color, const float opacity=1,
                       const float tolerance=0, const bool is_high_connexity=false) {
      CImg<ucharT> tmp;
      return draw_fill(x0,y0,0,color,opacity,tmp,tolerance,is_high_connexity);

Project: CImg
File: CImg.h

    //! Shift image content \newinstance.
    CImg<T> get_shift(const int delta_x, const int delta_y=0, const int delta_z=0, const int delta_c=0,
                      const unsigned int boundary_conditions=0) const {
      return (+*this).shift(delta_x,delta_y,delta_z,delta_c,boundary_conditions);

Project: CImg
File: CImg.h

    //! Access to a pixel value, using Neumann boundary conditions for the X and Y-coordinates \const.
    const T& atXY(const int x, const int y, const int z=0, const int c=0) const {
      if (is_empty())
        throw CImgInstanceException(_cimg_instance
                                    "atXY(): Empty instance.",
                                    cimg_instance);
      return _atXY(x,y,z,c);

Project: CImg
File: CImg.h

    template<typename t>
    CImg<_cimg_Ttfloat> get_solve(const CImg<t>& A) const {
      typedef _cimg_Ttfloat Ttfloat;
      return CImg<Ttfloat>(*this,false).solve(A);

Project: CImg
File: CImg.h


    static longT _distance_dist_edt(const longT x, const longT i, const longT *const g) {
      return (x - i)*(x - i) + g[i];

Project: CImg
File: CImg.h

    **/
    CImgList<T>& clear() {
      return assign();

Project: CImg
File: CImg.h


    CImg<intT> _autocrop(const T& value, const char axis) const {
      CImg<intT> res;
      switch (cimg::lowercase(axis)) {
      case 'x' : {
        int x0 = -1, x1 = -1;
        cimg_forX(*this,x) cimg_forYZC(*this,y,z,c)
          if ((*this)(x,y,z,c)!=value) { x0 = x; x = width(); y = height(); z = depth(); c = spectrum(); }
	if (x0>=0) {
          for (int x = width() - 1; x>=0; --x) cimg_forYZC(*this,y,z,c)
            if ((*this)(x,y,z,c)!=value) { x1 = x; x = 0; y = height(); z = depth(); c = spectrum(); }
        }
	res = CImg<intT>::vector(x0,x1);
      } break;
      case 'y' : {
        int y0 = -1, y1 = -1;
        cimg_forY(*this,y) cimg_forXZC(*this,x,z,c)
          if ((*this)(x,y,z,c)!=value) { y0 = y; x = width(); y = height(); z = depth(); c = spectrum(); }
	if (y0>=0) {
          for (int y = height() - 1; y>=0; --y) cimg_forXZC(*this,x,z,c)
            if ((*this)(x,y,z,c)!=value) { y1 = y; x = width(); y = 0; z = depth(); c = spectrum(); }
        }
  	res = CImg<intT>::vector(y0,y1);
      } break;
      case 'z' : {
        int z0 = -1, z1 = -1;
        cimg_forZ(*this,z) cimg_forXYC(*this,x,y,c)
          if ((*this)(x,y,z,c)!=value) { z0 = z; x = width(); y = height(); z = depth(); c = spectrum(); }
	if (z0>=0) {
          for (int z = depth() - 1; z>=0; --z) cimg_forXYC(*this,x,y,c)
            if ((*this)(x,y,z,c)!=value) { z1 = z; x = width(); y = height(); z = 0; c = spectrum(); }
        }
  	res = CImg<intT>::vector(z0,z1);
      } break;
      default : {
        int c0 = -1, c1 = -1;
        cimg_forC(*this,c) cimg_forXYZ(*this,x,y,z)
          if ((*this)(x,y,z,c)!=value) { c0 = c; x = width(); y = height(); z = depth(); c = spectrum(); }
	if (c0>=0) {
          for (int c = spectrum() - 1; c>=0; --c) cimg_forXYZ(*this,x,y,z)
            if ((*this)(x,y,z,c)!=value) { c1 = c; x = width(); y = height(); z = depth(); c = 0; }
        }
  	res = CImg<intT>::vector(c0,c1);
      }
      }
      return res;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<_cimg_Tt> operator%(const t value) const {
      return CImg<_cimg_Tt>(*this,false)%=value;

Project: CImg
File: CImg.h


      static double mp_mul(_cimg_math_parser& mp) {
        return _mp_arg(2)*_mp_arg(3);

Project: CImg
File: CImg.h


    bool _draw_fill(const int x, const int y, const int z,
                    const CImg<T>& ref, const float tolerance2) const {
      const T *ptr1 = data(x,y,z), *ptr2 = ref._data;
      const unsigned long off = _width*_height*_depth;
      float diff = 0;
      cimg_forC(*this,c) { diff += cimg::sqr(*ptr1 - *(ptr2++)); ptr1+=off; }
      return diff<=tolerance2;

Project: CImg
File: CImg.h

    **/
    CImgDisplay& assign() {
      return flush();

Project: CImg
File: CImg.h

    template<typename tp, typename tc>
    CImg<T>& draw_polygon(const CImg<tp>& points,
                          const tc *const color, const float opacity=1) {
      if (is_empty() || !points) return *this;
      if (!color)
        throw CImgArgumentException(_cimg_instance
                                    "draw_polygon(): Specified color is (null).",
                                    cimg_instance);
      if (points.height()!=2)
        throw CImgArgumentException(_cimg_instance
                                    "draw_polygon(): Invalid specified point set (%u,%u,%u,%u).",
                                    cimg_instance,
                                    points._width,points._height,points._depth,points._spectrum);
      if (points._width==1) return draw_point(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)),color,opacity);
      if (points._width==2) return draw_line(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)),
                                             cimg::uiround(points(1,0)),cimg::uiround(points(1,1)),color,opacity);
      if (points._width==3) return draw_triangle(cimg::uiround(points(0,0)),cimg::uiround(points(0,1)),
                                                 cimg::uiround(points(1,0)),cimg::uiround(points(1,1)),
                                                 cimg::uiround(points(2,0)),cimg::uiround(points(2,1)),color,opacity);
      cimg_init_scanline(opacity);
      int
        xmin = 0, ymin = 0,
        xmax = points.get_shared_row(0).max_min(xmin),
        ymax = points.get_shared_row(1).max_min(ymin);
      if (xmax<0 || xmin>=width() || ymax<0 || ymin>=height()) return *this;
      if (ymin==ymax) return draw_line(xmin,ymin,xmax,ymax,color,opacity);

      ymin = std::max(0,ymin);
      ymax = std::min(height() - 1,ymax);
      CImg<intT> Xs(points._width,ymax - ymin + 1);
      CImg<uintT> count(Xs._height,1,1,1,0);
      unsigned int n = 0, nn = 1;
      bool go_on = true;

      while (go_on) {
        unsigned int an = (nn + 1)%points._width;
        const int
          x0 = cimg::uiround(points(n,0)),
          y0 = cimg::uiround(points(n,1));
        if (points(nn,1)==y0) while (points(an,1)==y0) { nn = an; (an+=1)%=points._width; }
        const int
          x1 = cimg::uiround(points(nn,0)),
          y1 = cimg::uiround(points(nn,1));
        unsigned int tn = an;
        while (points(tn,1)==y1) (tn+=1)%=points._width;

        if (y0!=y1) {
          const int
            y2 = cimg::uiround(points(tn,1)),
            x01 = x1 - x0, y01 = y1 - y0, y12 = y2 - y1,
            step = cimg::sign(y01),
            tmax = std::max(1,cimg::abs(y01)), htmax = tmax*cimg::sign(x01)/2,
            tend = tmax - (step==cimg::sign(y12));
          unsigned int y = (unsigned int)y0 - ymin;
          for (int t = 0; t<=tend; ++t, y+=step)
            if (y<Xs._height) Xs(count[y]++,y) = x0 + (t*x01 + htmax)/tmax;
        }
        go_on = nn>n;
        n = nn;
        nn = an;
      }

      cimg_pragma_openmp(parallel for cimg_openmp_if(Xs._height>=(cimg_openmp_sizefactor)*32))
      cimg_forY(Xs,y) {
        const CImg<intT> Xsy = Xs.get_shared_points(0,count[y] - 1,y).sort();
        int px = width();
        for (unsigned int k = 0; k<Xsy._width; k+=2) {
          int x0 = Xsy[k];
          const int x1 = Xsy[k + 1];
          x0+=x0==px;
          cimg_draw_scanline(x0,x1,y + ymin,color,opacity,1);
          px = x1;
        }
      }
      return *this;

Project: CImg
File: CImg.h

    //! Compute distance function to 0-valued isophotes, using the Eikonal PDE \newinstance.
    CImg<Tfloat> get_distance_eikonal(const unsigned int nb_iterations, const float band_size=0,
                                      const float time_step=0.5f) const {
      return CImg<Tfloat>(*this,false).distance_eikonal(nb_iterations,band_size,time_step);

Project: CImg
File: CImg.h

    **/
    unsigned int released_key(const unsigned int pos=0) const {
      return pos<128?_released_keys[pos]:0;

Project: CImg
File: CImg.h

      void unlock(const unsigned int n) { ReleaseMutex(mutex[n]); }

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_video(const char *const filename,
                        const unsigned int first_frame=0, const unsigned int last_frame=~0U,
                        const unsigned int step_frame=1,
                        const char axis='z', const float align=0) {
      return get_load_video(filename,first_frame,last_frame,step_frame,axis,align).move_to(*this);

Project: CImg
File: CImg.h

      Mutex_info() {}

Project: CImg
File: CImg.h

    //! Test if image height is equal to specified value.
    bool is_sameY(const unsigned int size_y) const {
      return _height==size_y;

Project: CImg
File: CImg.h


    void _desinit_fullscreen() {
      if (!_is_fullscreen) return;
      Display *const dpy = cimg::X11_attr().display;
      XUngrabKeyboard(dpy,CurrentTime);

#ifdef cimg_use_xrandr
      if (cimg::X11_attr().resolutions && cimg::X11_attr().curr_resolution) {
        XRRScreenConfiguration *config = XRRGetScreenInfo(dpy,DefaultRootWindow(dpy));
        XRRSetScreenConfig(dpy,config,DefaultRootWindow(dpy),0,cimg::X11_attr().curr_rotation,CurrentTime);
        XRRFreeScreenConfigInfo(config);
        XSync(dpy,0);
        cimg::X11_attr().curr_resolution = 0;
      }
#endif
      if (_background_window) XDestroyWindow(dpy,_background_window);
      _background_window = 0;
      _is_fullscreen = false;

Project: CImg
File: CImg.h

    //! Return a shared-memory image referencing one row of the image instance \const.
    const CImg<T> get_shared_row(const unsigned int y0, const unsigned int z0=0, const unsigned int c0=0) const {
      return get_shared_rows(y0,y0,z0,c0);

Project: CImg
File: CImg.h


      static double mp_list_set_Ixyz_v(_cimg_math_parser& mp) {
        const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width());
        CImg<T> &img = mp.listout[ind];
        const int
          x = (int)_mp_arg(3),
          y = (int)_mp_arg(4),
          z = (int)_mp_arg(5);
        const double *ptrs = &_mp_arg(1) + 1;
        if (x>=0 && x<img.width() && y>=0 && y<img.height() && z>=0 && z<img.depth()) {
          const unsigned int vsiz = (unsigned int)mp.opcode[6];
          T *ptrd = &img(x,y,z);
          const ulongT whd = (ulongT)img._width*img._height*img._depth;
          cimg_for_inC(img,0,vsiz - 1,c) { *ptrd = (T)*(ptrs++); ptrd+=whd; }
        }
        return cimg::type<double>::nan();

Project: CImg
File: CImg.h


    Tfloat _linear_atXY_p(const float fx, const float fy, const int z=0, const int c=0) const {
      const float
        nfx = cimg::mod(fx,(float)_width),
        nfy = cimg::mod(fy,(float)_height);
      const unsigned int
        x = (unsigned int)nfx,
        y = (unsigned int)nfy;
      const float
        dx = nfx - x,
        dy = nfy - y;
      const unsigned int
        nx = cimg::mod(x + 1,_width),
        ny = cimg::mod(y + 1,_height);
      const Tfloat
        Icc = (Tfloat)(*this)(x,y,z,c),  Inc = (Tfloat)(*this)(nx,y,z,c),
        Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c);
      return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc);

Project: CImg
File: CImg.h

    //! Compute Haar multiscale wavelet transform \newinstance.
    CImg<Tfloat> get_haar(const bool invert=false, const unsigned int nb_scales=1) const {
      CImg<Tfloat> res;
      if (nb_scales==1) { // Single scale transform
        if (_width>1) get_haar('x',invert,1).move_to(res);
        if (_height>1) { if (res) res.haar('y',invert,1); else get_haar('y',invert,1).move_to(res); }
        if (_depth>1) { if (res) res.haar('z',invert,1); else get_haar('z',invert,1).move_to(res); }
        if (res) return res;
      } else { // Multi-scale transform
        if (invert) { // Inverse transform
          res.assign(*this,false);
          if (_width>1) {
            if (_height>1) {
              if (_depth>1) {
                unsigned int w = _width, h = _height, d = _depth;
                for (unsigned int s = 1; w && h && d && s<nb_scales; ++s) { w/=2; h/=2; d/=2; }
                for (w = w?w:1, h = h?h:1, d = d?d:1; w<=_width && h<=_height && d<=_depth; w*=2, h*=2, d*=2)
                  res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,d - 1).get_haar(true,1));
              } else {
                unsigned int w = _width, h = _height;
                for (unsigned int s = 1; w && h && s<nb_scales; ++s) { w/=2; h/=2; }
                for (w = w?w:1, h = h?h:1; w<=_width && h<=_height; w*=2, h*=2)
                  res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,0).get_haar(true,1));
              }
            } else {
              if (_depth>1) {
                unsigned int w = _width, d = _depth;
                for (unsigned int s = 1; w && d && s<nb_scales; ++s) { w/=2; d/=2; }
                for (w = w?w:1, d = d?d:1; w<=_width && d<=_depth; w*=2, d*=2)
                  res.draw_image(res.get_crop(0,0,0,w - 1,0,d - 1).get_haar(true,1));
              } else {
                unsigned int w = _width;
                for (unsigned int s = 1; w && s<nb_scales; ++s) w/=2;
                for (w = w?w:1; w<=_width; w*=2)
                  res.draw_image(res.get_crop(0,0,0,w - 1,0,0).get_haar(true,1));
              }
            }
          } else {
            if (_height>1) {
              if (_depth>1) {
                unsigned int h = _height, d = _depth;
                for (unsigned int s = 1; h && d && s<nb_scales; ++s) { h/=2; d/=2; }
                for (h = h?h:1, d = d?d:1; h<=_height && d<=_depth; h*=2, d*=2)
                  res.draw_image(res.get_crop(0,0,0,0,h - 1,d - 1).get_haar(true,1));
              } else {
                unsigned int h = _height;
                for (unsigned int s = 1; h && s<nb_scales; ++s) h/=2;
                for (h = h?h:1; h<=_height; h*=2)
                  res.draw_image(res.get_crop(0,0,0,0,h - 1,0).get_haar(true,1));
              }
            } else {
              if (_depth>1) {
                unsigned int d = _depth;
                for (unsigned int s = 1; d && s<nb_scales; ++s) d/=2;
                for (d = d?d:1; d<=_depth; d*=2)
                  res.draw_image(res.get_crop(0,0,0,0,0,d - 1).get_haar(true,1));
              } else return *this;
            }
          }
        } else { // Direct transform
          res = get_haar(false,1);
          if (_width>1) {
            if (_height>1) {
              if (_depth>1)
                for (unsigned int s = 1, w = _width/2, h = _height/2, d = _depth/2; w && h && d && s<nb_scales;
                     ++s, w/=2, h/=2, d/=2)
                  res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,d - 1).haar(false,1));
              else for (unsigned int s = 1, w = _width/2, h = _height/2; w && h && s<nb_scales; ++s, w/=2, h/=2)
                     res.draw_image(res.get_crop(0,0,0,w - 1,h - 1,0).haar(false,1));
            } else {
              if (_depth>1) for (unsigned int s = 1, w = _width/2, d = _depth/2; w && d && s<nb_scales; ++s, w/=2, d/=2)
                              res.draw_image(res.get_crop(0,0,0,w - 1,0,d - 1).haar(false,1));
              else for (unsigned int s = 1, w = _width/2; w && s<nb_scales; ++s, w/=2)
                     res.draw_image(res.get_crop(0,0,0,w - 1,0,0).haar(false,1));
            }
          } else {
            if (_height>1) {
              if (_depth>1)
                for (unsigned int s = 1, h = _height/2, d = _depth/2; h && d && s<nb_scales; ++s, h/=2, d/=2)
                  res.draw_image(res.get_crop(0,0,0,0,h - 1,d - 1).haar(false,1));
              else for (unsigned int s = 1, h = _height/2; h && s<nb_scales; ++s, h/=2)
                     res.draw_image(res.get_crop(0,0,0,0,h - 1,0).haar(false,1));
            } else {
              if (_depth>1) for (unsigned int s = 1, d = _depth/2; d && s<nb_scales; ++s, d/=2)
                              res.draw_image(res.get_crop(0,0,0,0,0,d - 1).haar(false,1));
              else return *this;
            }
          }
        }
        return res;
      }
      return *this;

Project: CImg
File: CImg.h


      static double mp_memcopy(_cimg_math_parser& mp) {
        longT siz = (longT)_mp_arg(4);
        const longT inc_d = (longT)_mp_arg(5), inc_s = (longT)_mp_arg(6);
        const float
          _opacity = (float)_mp_arg(7),
          opacity = (float)cimg::abs(_opacity),
          omopacity = 1 - std::max(_opacity,0.f);
        if (siz>0) {
          const bool
            is_doubled = mp.opcode[8]<=1,
            is_doubles = mp.opcode[15]<=1;
          if (is_doubled && is_doubles) { // (double*) <- (double*)
            double *ptrd = _mp_memcopy_double(mp,(unsigned int)mp.opcode[2],&mp.opcode[8],siz,inc_d);
            const double *ptrs = _mp_memcopy_double(mp,(unsigned int)mp.opcode[3],&mp.opcode[15],siz,inc_s);
            if (inc_d==1 && inc_s==1 && _opacity>=1) {
              if (ptrs + siz - 1<ptrd || ptrs>ptrd + siz - 1) std::memcpy(ptrd,ptrs,siz*sizeof(double));
              else std::memmove(ptrd,ptrs,siz*sizeof(double));
            } else {
              if (ptrs + (siz - 1)*inc_s<ptrd || ptrs>ptrd + (siz - 1)*inc_d) {
                if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; }
                else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; }
              } else { // Overlapping buffers
                CImg<doubleT> buf((unsigned int)siz);
                cimg_for(buf,ptr,double) { *ptr = *ptrs; ptrs+=inc_s; }
                ptrs = buf;
                if (_opacity>=1) while (siz-->0) { *ptrd = *(ptrs++); ptrd+=inc_d; }
                else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**(ptrs++); ptrd+=inc_d; }
              }
            }
          } else if (is_doubled && !is_doubles) { // (double*) <- (float*)
            double *ptrd = _mp_memcopy_double(mp,(unsigned int)mp.opcode[2],&mp.opcode[8],siz,inc_d);
            const float *ptrs = _mp_memcopy_float(mp,&mp.opcode[15],siz,inc_s,false);
            if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; }
            else while (siz-->0) { *ptrd = omopacity**ptrd + _opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; }
          } else if (!is_doubled && is_doubles) { // (float*) <- (double*)
            float *ptrd = _mp_memcopy_float(mp,&mp.opcode[8],siz,inc_d,true);
            const double *ptrs = _mp_memcopy_double(mp,(unsigned int)mp.opcode[3],&mp.opcode[15],siz,inc_s);
            if (_opacity>=1) while (siz-->0) { *ptrd = (float)*ptrs; ptrd+=inc_d; ptrs+=inc_s; }
            else while (siz-->0) { *ptrd = (float)(omopacity**ptrd + opacity**ptrs); ptrd+=inc_d; ptrs+=inc_s; }
          } else { // (float*) <- (float*)
            float *ptrd = _mp_memcopy_float(mp,&mp.opcode[8],siz,inc_d,true);
            const float *ptrs = _mp_memcopy_float(mp,&mp.opcode[15],siz,inc_s,false);
            if (inc_d==1 && inc_s==1 && _opacity>=1) {
              if (ptrs + siz - 1<ptrd || ptrs>ptrd + siz - 1) std::memcpy(ptrd,ptrs,siz*sizeof(float));
              else std::memmove(ptrd,ptrs,siz*sizeof(float));
            } else {
              if (ptrs + (siz - 1)*inc_s<ptrd || ptrs>ptrd + (siz - 1)*inc_d) {
                if (_opacity>=1) while (siz-->0) { *ptrd = *ptrs; ptrd+=inc_d; ptrs+=inc_s; }
                else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**ptrs; ptrd+=inc_d; ptrs+=inc_s; }
              } else { // Overlapping buffers
                CImg<floatT> buf((unsigned int)siz);
                cimg_for(buf,ptr,float) { *ptr = *ptrs; ptrs+=inc_s; }
                ptrs = buf;
                if (_opacity>=1) while (siz-->0) { *ptrd = *(ptrs++); ptrd+=inc_d; }
                else while (siz-->0) { *ptrd = omopacity**ptrd + opacity**(ptrs++); ptrd+=inc_d; }
              }
            }
          }
        }
        return _mp_arg(1);

Project: CImg
File: CImg.h

    **/
    CImg<T>& blur(const float sigma_x, const float sigma_y, const float sigma_z,
                  const bool boundary_conditions=true, const bool is_gaussian=false) {
      if (is_empty()) return *this;
      if (is_gaussian) {
        if (_width>1) vanvliet(sigma_x,0,'x',boundary_conditions);
        if (_height>1) vanvliet(sigma_y,0,'y',boundary_conditions);
        if (_depth>1) vanvliet(sigma_z,0,'z',boundary_conditions);
      } else {
        if (_width>1) deriche(sigma_x,0,'x',boundary_conditions);
        if (_height>1) deriche(sigma_y,0,'y',boundary_conditions);
        if (_depth>1) deriche(sigma_z,0,'z',boundary_conditions);
      }
      return *this;

Project: CImg
File: CImg.h

        \param dy Height of images in the written file.
        \param dz Depth of images in the written file.
        \param dc Spectrum of images in the written file.
    **/
    static void save_empty_cimg(const char *const filename,
                                const unsigned int nb,

Project: CImg
File: CImg.h

    template<typename tp, typename tf, typename tc, typename to>
    CImg<T>& draw_object3d(LibBoard::Board& board,
                           const float x0, const float y0, const float z0,
                           const CImg<tp>& vertices, const CImgList<tf>& primitives,
                           const CImgList<tc>& colors, const CImgList<to>& opacities,
                           const unsigned int render_type=4,
                           const bool is_double_sided=false, const float focale=700,
                           const float lightx=0, const float lighty=0, const float lightz=-5e8,
                           const float specular_lightness=0.2f, const float specular_shininess=0.1f,
                           const float g_opacity=1) {
      return draw_object3d(board,x0,y0,z0,vertices,primitives,colors,opacities,render_type,
                           is_double_sided,focale,lightx,lighty,lightz,
                           specular_lightness,specular_shininess,g_opacity,CImg<floatT>::empty());

Project: CImg
File: CImg.h

    //! Return a \c 1x5 image containing specified values.
    static CImg<T> vector(const T& a0, const T& a1, const T& a2, const T& a3, const T& a4) {
      CImg<T> r(1,5); T *ptr = r._data;
      *(ptr++) = a0; *(ptr++) = a1; *(ptr++) = a2; *(ptr++) = a3; *(ptr++) = a4;
      return r;

Project: CImg
File: CImg.h

    template<typename t, typename ti>
    CImg<T>& _solve(const CImg<t>& A, const CImg<ti>& indx) {
      typedef _cimg_Ttfloat Ttfloat;
      const int N = (int)size();
      int ii = -1;
      Ttfloat sum;
      for (int i = 0; i<N; ++i) {
        const int ip = (int)indx[i];
        sum = (*this)(ip);
        (*this)(ip) = (*this)(i);
        if (ii>=0) for (int j = ii; j<=i - 1; ++j) sum-=A(j,i)*(*this)(j);
        else if (sum!=0) ii = i;
        (*this)(i) = (T)sum;
      }
      for (int i = N - 1; i>=0; --i) {
        sum = (*this)(i);
        for (int j = i + 1; j<N; ++j) sum-=A(j,i)*(*this)(j);
        (*this)(i) = (T)(sum/A(i,i));
      }
      return *this;

Project: CImg
File: CImg.h

    //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp10.
    static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5,
                     CImgDisplay& disp6, CImgDisplay& disp7, CImgDisplay& disp8, CImgDisplay& disp9,
                     CImgDisplay& disp10) {
      disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event =
        disp6._is_event = disp7._is_event = disp8._is_event = disp9._is_event = disp10._is_event = false;
      while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed ||
              !disp6._is_closed || !disp7._is_closed || !disp8._is_closed || !disp9._is_closed || !disp10._is_closed) &&
             !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event &&
             !disp6._is_event && !disp7._is_event && !disp8._is_event && !disp9._is_event && !disp10._is_event)
        wait_all();

Project: CImg
File: CImg.h

    template<typename T1, typename T2, typename T3>
    inline void swap(T1& a1, T1& b1, T2& a2, T2& b2, T3& a3, T3& b3) {
      cimg::swap(a1,b1,a2,b2); cimg::swap(a3,b3);

Project: CImg
File: CImg.h


    static int _assign_xshm(Display *dpy, XErrorEvent *error) {
      cimg::unused(dpy,error);
      cimg::X11_attr().is_shm_enabled = false;
      return 0;

Project: CImg
File: CImg.h

    //! Load image from a raw binary file \newinstance.
    static CImg<T> get_load_raw(const char *const filename,
                                const unsigned int size_x=0, const unsigned int size_y=1,
                                const unsigned int size_z=1, const unsigned int size_c=1,
                                const bool is_multiplexed=false, const bool invert_endianness=false,
                                const ulongT offset=0) {
      return CImg<T>().load_raw(filename,size_x,size_y,size_z,size_c,is_multiplexed,invert_endianness,offset);

Project: CImg
File: CImg.h

    //! Convert pixel values from RGB to YCbCr color spaces \newinstance.
    CImg<Tuchar> get_YCbCrtoRGB() const {
      return CImg<Tuchar>(*this,false).YCbCrtoRGB();

Project: CImg
File: CImg.h

      }
      float operator()(const float x, const float y, const float z, const unsigned int c) const {
        return (float)(*mp)(x,y,z,c);

Project: CImg
File: CImg.h


      static double mp_arg(_cimg_math_parser& mp) {
        const int _ind = (int)_mp_arg(4);
        const unsigned int
          nb_args = (unsigned int)mp.opcode[2] - 4,
          ind = _ind<0?_ind + nb_args:(unsigned int)_ind,
          siz = (unsigned int)mp.opcode[3];
        if (siz>0) {
          if (ind>=nb_args) std::memset(&_mp_arg(1) + 1,0,siz*sizeof(double));
          else std::memcpy(&_mp_arg(1) + 1,&_mp_arg(ind + 4) + 1,siz*sizeof(double));
          return cimg::type<double>::nan();
        }
        if (ind>=nb_args) return 0;
        return _mp_arg(ind + 4);

Project: CImg
File: CImg.h

      Mutex_info() { for (unsigned int i = 0; i<32; ++i) pthread_mutex_init(&mutex[i],0); }

Project: CImg
File: CImg.h

    //! Add random noise to pixel values \newinstance.
    CImg<T> get_noise(const double sigma, const unsigned int noise_type=0) const {
      return (+*this).noise(sigma,noise_type);

Project: CImg
File: CImg.h

    //! Uniformly quantize pixel values \newinstance.
    CImg<T> get_quantize(const unsigned int n, const bool keep_range=true) const {
      return (+*this).quantize(n,keep_range);

Project: CImg
File: CImg.h

    template<typename tp, typename tc>
    CImg<T>& draw_spline(const CImg<tp>& points,
                         const tc *const color, const float opacity=1,
                         const bool is_closed_set=false, const float precision=4,
                         const unsigned int pattern=~0U, const bool init_hatch=true) {
      if (is_empty() || !points || points._width<2) return *this;
      CImg<Tfloat> tangents;
      switch (points._height) {
      case 0 : case 1 :
        throw CImgArgumentException(_cimg_instance
                                    "draw_spline(): Invalid specified point set (%u,%u,%u,%u,%p).",
                                    cimg_instance,
                                    points._width,points._height,points._depth,points._spectrum,points._data);
      case 2 : {
        tangents.assign(points._width,points._height);
        cimg_forX(points,p) {
          const unsigned int
            p0 = is_closed_set?(p + points.width() - 1)%points.width():(p?p - 1:0),
            p1 = is_closed_set?(p + 1)%points.width():(p + 1<points.width()?p + 1:p);
          const float
            x = (float)points(p,0),
            y = (float)points(p,1),
            x0 = (float)points(p0,0),
            y0 = (float)points(p0,1),
            x1 = (float)points(p1,0),
            y1 = (float)points(p1,1),
            u0 = x - x0,
            v0 = y - y0,
            n0 = 1e-8f + cimg::hypot(u0,v0),
            u1 = x1 - x,
            v1 = y1 - y,
            n1 = 1e-8f + cimg::hypot(u1,v1),
            u = u0/n0 + u1/n1,
            v = v0/n0 + v1/n1,
            n = 1e-8f + cimg::hypot(u,v),
            fact = 0.5f*(n0 + n1);
          tangents(p,0) = (Tfloat)(fact*u/n);
          tangents(p,1) = (Tfloat)(fact*v/n);
        }
      } break;
      default : {
        tangents.assign(points._width,points._height);
        cimg_forX(points,p) {
          const unsigned int
            p0 = is_closed_set?(p + points.width() - 1)%points.width():(p?p - 1:0),
            p1 = is_closed_set?(p + 1)%points.width():(p + 1<points.width()?p + 1:p);
          const float
            x = (float)points(p,0),
            y = (float)points(p,1),
            z = (float)points(p,2),
            x0 = (float)points(p0,0),
            y0 = (float)points(p0,1),
            z0 = (float)points(p0,2),
            x1 = (float)points(p1,0),
            y1 = (float)points(p1,1),
            z1 = (float)points(p1,2),
            u0 = x - x0,
            v0 = y - y0,
            w0 = z - z0,
            n0 = 1e-8f + cimg::hypot(u0,v0,w0),
            u1 = x1 - x,
            v1 = y1 - y,
            w1 = z1 - z,
            n1 = 1e-8f + cimg::hypot(u1,v1,w1),
            u = u0/n0 + u1/n1,
            v = v0/n0 + v1/n1,
            w = w0/n0 + w1/n1,
            n = 1e-8f + cimg::hypot(u,v,w),
            fact = 0.5f*(n0 + n1);
          tangents(p,0) = (Tfloat)(fact*u/n);
          tangents(p,1) = (Tfloat)(fact*v/n);
          tangents(p,2) = (Tfloat)(fact*w/n);
        }
      }
      }
      return draw_spline(points,tangents,color,opacity,is_closed_set,precision,pattern,init_hatch);

Project: CImg
File: CImg.h

    //! Load image using various non-native ways \newinstance.
    static CImg<T> get_load_other(const char *const filename) {
      return CImg<T>().load_other(filename);

Project: CImg
File: CImg.h


    const T& operator()(const unsigned int x, const unsigned int y) const {
      return _data[x + y*_width];

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& fill(const CImg<t>& values, const bool repeat_values=true) {
      if (is_empty() || !values) return *this;
      T *ptrd = _data, *ptre = ptrd + size();
      for (t *ptrs = values._data, *ptrs_end = ptrs + values.size(); ptrs<ptrs_end && ptrd<ptre; ++ptrs)
        *(ptrd++) = (T)*ptrs;
      if (repeat_values && ptrd<ptre) for (T *ptrs = _data; ptrd<ptre; ++ptrs) *(ptrd++) = *ptrs;
      return *this;

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& operator<<=(const t value) {
      if (is_empty()) return *this;
      cimg_openmp_for(*this,((longT)*ptr) << (int)value,65536);
      return *this;

Project: CImg
File: CImg.h

      return *ptr_min;
    }

    //! Return a reference to the minimum pixel value of the instance list \const.
    const T& min() const {
      bool is_all_empty = true;
      T *ptr_min = 0;
      cimglist_for(*this,l) if (!_data[l].is_empty()) {
        ptr_min = _data[l]._data;
        is_all_empty = false;
        break;
      }
      if (is_all_empty)
        throw CImgInstanceException(_cimglist_instance
                                    "min(): %s.",
                                    _data?"List of empty images":"Empty instance",
                                    cimglist_instance);
      T min_value = *ptr_min;
      cimglist_for(*this,l) {
        const CImg<T>& img = _data[l];

Project: CImg
File: CImg.h


    T _cubic_atXYZ_pc(const float fx, const float fy, const float fz, const int c) const {
      return cimg::type<T>::cut(_cubic_atXYZ_p(fx,fy,fz,c));

Project: CImg
File: CImg.h


      static double mp_set_ixyzc(_cimg_math_parser& mp) {
        CImg<T> &img = mp.imgout;
        const int
          x = (int)_mp_arg(2), y = (int)_mp_arg(3),
          z = (int)_mp_arg(4), c = (int)_mp_arg(5);
        const double val = _mp_arg(1);
        if (x>=0 && x<img.width() && y>=0 && y<img.height() &&
            z>=0 && z<img.depth() && c>=0 && c<img.spectrum())
          img(x,y,z,c) = (T)val;
        return val;

Project: CImg
File: CImg.h

       \param codec Type of compression (See http://www.fourcc.org/codecs.php to see available codecs).
       \param keep_open Tells if the video writer associated to the specified filename
       must be kept open or not (to allow frames to be added in the same file afterwards).
    **/
    const CImgList<T>& save_video(const char *const filename, const unsigned int fps=25,
                                  const char *codec=0, const bool keep_open=false) const {
#ifndef cimg_use_opencv
      cimg::unused(codec,keep_open);
      return save_ffmpeg_external(filename,fps);
#else
      static cv::VideoWriter *writers[32] = { 0 };
      static CImgList<charT> filenames(32);
      static CImg<intT> sizes(32,2,1,1,0);
      static int last_used_index = -1;

      // Detect if a video writer already exists for the specified filename.
      cimg::mutex(9);
      int index = -1;
      if (filename) {
        if (last_used_index>=0 && !std::strcmp(filename,filenames[last_used_index])) {
          index = last_used_index;
        } else cimglist_for(filenames,l) if (filenames[l] && !std::strcmp(filename,filenames[l])) {
            index = l; break;
          }
      } else index = last_used_index;
      cimg::mutex(9,0);

      // Find empty slot for capturing video stream.
      if (index<0) {
        if (!filename)
          throw CImgArgumentException(_cimglist_instance
                                      "save_video(): No already open video writer found. You must specify a "
                                      "non-(null) filename argument for the first call.",
                                      cimglist_instance);
        else { cimg::mutex(9); cimglist_for(filenames,l) if (!filenames[l]) { index = l; break; } cimg::mutex(9,0); }
        if (index<0)
          throw CImgIOException(_cimglist_instance
                                "save_video(): File '%s', no video writer slots available. "
                                "You have to release some of your previously opened videos.",
                                cimglist_instance,filename);
        if (is_empty())
          throw CImgInstanceException(_cimglist_instance
                                      "save_video(): Instance list is empty.",
                                      cimglist_instance);
        const unsigned int W = _data?_data[0]._width:0, H = _data?_data[0]._height:0;
        if (!W || !H)
          throw CImgInstanceException(_cimglist_instance
                                      "save_video(): Frame [0] is an empty image.",
                                      cimglist_instance);
        const char
          *const _codec = codec && *codec?codec:cimg_OS==2?"mpeg":"mp4v",
          codec0 = cimg::uppercase(_codec[0]),
          codec1 = _codec[0]?cimg::uppercase(_codec[1]):0,
          codec2 = _codec[1]?cimg::uppercase(_codec[2]):0,
          codec3 = _codec[2]?cimg::uppercase(_codec[3]):0;
        cimg::mutex(9);
        writers[index] = new cv::VideoWriter(filename,_cimg_fourcc(codec0,codec1,codec2,codec3),fps,cv::Size(W,H));
        if (!writers[index]->isOpened()) {
          delete writers[index];
          writers[index] = 0;
          cimg::mutex(9,0);
          throw CImgIOException(_cimglist_instance
                                "save_video(): File '%s', unable to initialize video writer with codec '%c%c%c%c'.",
                                cimglist_instance,filename,
                                codec0,codec1,codec2,codec3);
        }
        CImg<charT>::string(filename).move_to(filenames[index]);
        sizes(index,0) = W;
        sizes(index,1) = H;
        cimg::mutex(9,0);
      }

      if (!is_empty()) {
        const unsigned int W = sizes(index,0), H = sizes(index,1);
        cimg::mutex(9);
        cimglist_for(*this,l) {
          CImg<T> &src = _data[l];
          if (src.is_empty())
            cimg::warn(_cimglist_instance
                       "save_video(): Skip empty frame %d for file '%s'.",
                       cimglist_instance,l,filename);
          if (src._depth>1 || src._spectrum>3)
            cimg::warn(_cimglist_instance
                       "save_video(): Frame %u has incompatible dimension (%u,%u,%u,%u). "
                       "Some image data may be ignored when writing frame into video file '%s'.",
                       cimglist_instance,l,src._width,src._height,src._depth,src._spectrum,filename);
          if (src._width==W && src._height==H && src._spectrum==3)
            writers[index]->write(CImg<ucharT>(src)._cimg2cvmat());
          else {
            CImg<ucharT> _src(src,false);
            _src.channels(0,std::min(_src._spectrum - 1,2U)).resize(W,H);
            _src.resize(W,H,1,3,_src._spectrum==1);
            writers[index]->write(_src._cimg2cvmat());
          }
        }
        cimg::mutex(9,0);
      }

      cimg::mutex(9);
      if (!keep_open) {
        delete writers[index];
        writers[index] = 0;
        filenames[index].assign();
        sizes(index,0) = sizes(index,1) = 0;
        last_used_index = -1;
      } else last_used_index = index;
      cimg::mutex(9,0);

Project: CImg
File: CImg.h

  template<typename T>
  inline CImg<_cimg_Tfloat> pseudoinvert(const CImg<T>& instance) {
    return instance.get_pseudoinvert();

Project: CImg
File: CImg.h


      static double mp_Ioff(_cimg_math_parser& mp) {
        double *ptrd = &_mp_arg(1) + 1;
        const unsigned int
          boundary_conditions = (unsigned int)_mp_arg(3),
          vsiz = (unsigned int)mp.opcode[4];
        const CImg<T> &img = mp.imgin;
        const longT
          off = (longT)_mp_arg(2),
          whd = (longT)img.width()*img.height()*img.depth();
        const T *ptrs;
        if (off>=0 && off<whd) {
          ptrs = &img[off];
          cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; }
          return cimg::type<double>::nan();
        }
        if (img._data) switch (boundary_conditions) {
          case 3 : { // Mirror
            const longT whd2 = 2*whd, moff = cimg::mod(off,whd2);
            ptrs = &img[moff<whd?moff:whd2 - moff - 1];
            cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; }
            return cimg::type<double>::nan();
          }
          case 2 : // Periodic
            ptrs = &img[cimg::mod(off,whd)];
            cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; }
            return cimg::type<double>::nan();
          case 1 : // Neumann
            ptrs = off<0?&img[0]:&img[whd - 1];
            cimg_for_inC(img,0,vsiz - 1,c) { *(ptrd++) = *ptrs; ptrs+=whd; }
            return cimg::type<double>::nan();
          default : // Dirichlet
            std::memset(ptrd,0,vsiz*sizeof(double));
            return cimg::type<double>::nan();
          }
        std::memset(ptrd,0,vsiz*sizeof(double));
        return cimg::type<double>::nan();

Project: CImg
File: CImg.h

    //! Wait for any event occuring either on the display \c disp1, \c disp2, \c disp3, \c disp4, ... \c disp6.
    static void wait(CImgDisplay& disp1, CImgDisplay& disp2, CImgDisplay& disp3, CImgDisplay& disp4, CImgDisplay& disp5,
                     CImgDisplay& disp6) {
      disp1._is_event = disp2._is_event = disp3._is_event = disp4._is_event = disp5._is_event =
        disp6._is_event = false;
      while ((!disp1._is_closed || !disp2._is_closed || !disp3._is_closed || !disp4._is_closed || !disp5._is_closed ||
              !disp6._is_closed) &&
             !disp1._is_event && !disp2._is_event && !disp3._is_event && !disp4._is_event && !disp5._is_event &&
             !disp6._is_event) wait_all();

Project: CImg
File: CImg.h


      static double mp_bitwise_or(_cimg_math_parser& mp) {
        return (double)((longT)_mp_arg(2) | (longT)_mp_arg(3));

Project: CImg
File: CImg.h

    **/
    CImg<T>& boxfilter(const float boxsize, const int order, const char axis='x',
                       const bool boundary_conditions=true,
                       const unsigned int nb_iter=1) {
      if (is_empty() || !boxsize || (boxsize<=1 && !order)) return *this;
      const char naxis = cimg::lowercase(axis);
      const float nboxsize = boxsize>=0?boxsize:-boxsize*
        (naxis=='x'?_width:naxis=='y'?_height:naxis=='z'?_depth:_spectrum)/100;
      switch (naxis) {
      case 'x' : {
        cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 &&
                                                                   _height*_depth*_spectrum>=16))
        cimg_forYZC(*this,y,z,c)
          _cimg_blur_box_apply(data(0,y,z,c),nboxsize,_width,1U,order,boundary_conditions,nb_iter);
      } break;
      case 'y' : {
        cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 &&
                                                                   _height*_depth*_spectrum>=16))
        cimg_forXZC(*this,x,z,c)
          _cimg_blur_box_apply(data(x,0,z,c),nboxsize,_height,(ulongT)_width,order,boundary_conditions,nb_iter);
      } break;
      case 'z' : {
        cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 &&
                                                                   _height*_depth*_spectrum>=16))
        cimg_forXYC(*this,x,y,c)
          _cimg_blur_box_apply(data(x,y,0,c),nboxsize,_depth,(ulongT)_width*_height,order,boundary_conditions,nb_iter);
      } break;
      default : {
        cimg_pragma_openmp(parallel for cimg_openmp_collapse(3) cimg_openmp_if(_width>=(cimg_openmp_sizefactor)*256 &&
                                                                   _height*_depth*_spectrum>=16))
        cimg_forXYZ(*this,x,y,z)
          _cimg_blur_box_apply(data(x,y,z,0),nboxsize,_spectrum,(ulongT)_width*_height*_depth,
                               order,boundary_conditions,nb_iter);
      }
      }
      return *this;

Project: CImg
File: CImg.h

#if cimg_use_cpp11==1
    CImg(CImg<T>&& img):_width(0),_height(0),_depth(0),_spectrum(0),_is_shared(false),_data(0) {
      swap(img);

Project: CImg
File: CImg.h

    template<typename t>
    bool is_sameYZ(const CImg<t>& img) const {
      return is_sameYZ(img._height,img._depth);

Project: CImg
File: CImg.h

  struct CImgDisplayException : public CImgException {

Project: CImg
File: CImg.h

    **/
    CImg<T>& load_dlm(const char *const filename) {
      return _load_dlm(0,filename);

Project: CImg
File: CImg.h

    **/
    int window_x() const {
      return _window_x;

Project: CImg
File: CImg.h

       \param[out] y Y-coordinate of the pixel value, if test succeeds.
       \note If true, set coordinates (n,x,y).
    **/
    template<typename t>

Project: CImg
File: CImg.h

      static long double cut(const long double val) { return val; }

Project: CImg
File: CImg.h

    **/
    bool is_sameZC(const unsigned int size_z, const unsigned int size_c) const {
      return _depth==size_z && _spectrum==size_c;

Project: CImg
File: CImg.h


    Tfloat _linear_atXY(const float fx, const float fy, const int z=0, const int c=0) const {
      const float
        nfx = cimg::cut(fx,0,width() - 1),
        nfy = cimg::cut(fy,0,height() - 1);
      const unsigned int
        x = (unsigned int)nfx,
        y = (unsigned int)nfy;
      const float
        dx = nfx - x,
        dy = nfy - y;
      const unsigned int
        nx = dx>0?x + 1:x,
        ny = dy>0?y + 1:y;
      const Tfloat
        Icc = (Tfloat)(*this)(x,y,z,c),  Inc = (Tfloat)(*this)(nx,y,z,c),
        Icn = (Tfloat)(*this)(x,ny,z,c), Inn = (Tfloat)(*this)(nx,ny,z,c);
      return Icc + dx*(Inc - Icc + dy*(Icc + Inn - Icn - Inc)) + dy*(Icn - Icc);

Project: CImg
File: CImg.h

    template<typename T>
    static void screenshot(const int x0, const int y0, const int x1, const int y1, CImg<T>& img) {
      img.assign();
      HDC hScreen = GetDC(GetDesktopWindow());
      if (hScreen) {
        const int
          width = GetDeviceCaps(hScreen,HORZRES),
          height = GetDeviceCaps(hScreen,VERTRES);
        int _x0 = x0, _y0 = y0, _x1 = x1, _y1 = y1;
        if (_x0>_x1) cimg::swap(_x0,_x1);
        if (_y0>_y1) cimg::swap(_y0,_y1);
        if (_x1>=0 && _x0<width && _y1>=0 && _y0<height) {
          _x0 = std::max(_x0,0);
          _y0 = std::max(_y0,0);
          _x1 = std::min(_x1,width - 1);
          _y1 = std::min(_y1,height - 1);
          const int bw = _x1 - _x0 + 1, bh = _y1 - _y0 + 1;
          HDC hdcMem = CreateCompatibleDC(hScreen);
          if (hdcMem) {
            HBITMAP hBitmap = CreateCompatibleBitmap(hScreen,bw,bh);
            if (hBitmap) {
              HGDIOBJ hOld = SelectObject(hdcMem,hBitmap);
              if (hOld && BitBlt(hdcMem,0,0,bw,bh,hScreen,_x0,_y0,SRCCOPY) && SelectObject(hdcMem,hOld)) {
                BITMAPINFOHEADER bmi;
                bmi.biSize = sizeof(BITMAPINFOHEADER);
                bmi.biWidth = bw;
                bmi.biHeight = -bh;
                bmi.biPlanes = 1;
                bmi.biBitCount = 32;
                bmi.biCompression = BI_RGB;
                bmi.biSizeImage = 0;
                bmi.biXPelsPerMeter = bmi.biYPelsPerMeter = 0;
                bmi.biClrUsed = bmi.biClrImportant = 0;
                unsigned char *buf = new unsigned char[4*bw*bh];
                if (GetDIBits(hdcMem,hBitmap,0,bh,buf,(BITMAPINFO*)&bmi,DIB_RGB_COLORS)) {
                  img.assign(bw,bh,1,3);
                  const unsigned char *ptrs = buf;
                  T *pR = img.data(0,0,0,0), *pG = img.data(0,0,0,1), *pB = img.data(0,0,0,2);
                  cimg_forXY(img,x,y) {
                    *(pR++) = (T)ptrs[2];
                    *(pG++) = (T)ptrs[1];
                    *(pB++) = (T)ptrs[0];
                    ptrs+=4;
                  }
                }
                delete[] buf;
              }
              DeleteObject(hBitmap);
            }
            DeleteDC(hdcMem);
          }
        }
        ReleaseDC(GetDesktopWindow(),hScreen);
      }
      if (img.is_empty())
        throw CImgDisplayException("CImgDisplay::screenshot(): Failed to take screenshot "
                                   "with coordinates (%d,%d)-(%d,%d).",
                                   x0,y0,x1,y1);

Project: CImg
File: CImg.h

    // (Precise up to n = 78, less precise for n>78).
    inline double fibonacci(const int n) {
      if (n<0) return cimg::type<double>::nan();
      if (n<3) return 1;
      if (n<11) {
        cimg_uint64 fn1 = 1, fn2 = 1, fn = 0;
        for (int i = 3; i<=n; ++i) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; }
        return (double)fn;
      }
      if (n<75) // precise up to n = 74, faster than the integer calculation above for n>10
        return (double)((cimg_uint64)(_fibonacci(n) + 0.5));

      if (n<94) { // precise up to n = 78, less precise for n>78 up to n = 93, overflows for n>93
        cimg_uint64
          fn1 = (cimg_uint64)1304969544928657ULL,
          fn2 = (cimg_uint64)806515533049393ULL,
          fn = 0;
        for (int i = 75; i<=n; ++i) { fn = fn1 + fn2; fn2 = fn1; fn1 = fn; }
        return (double)fn;
      }
      return _fibonacci(n); // Not precise, but better than the wrong overflowing calculation

Project: CImg
File: CImg.h

    template<typename T>
    inline T round(const T& x, const double y, const int rounding_type=0) {
      if (y<=0) return x;
      if (y==1) switch (rounding_type) {
        case 0 : return cimg::round(x);
        case 1 : return (T)std::ceil((_cimg_Tfloat)x);
        default : return (T)std::floor((_cimg_Tfloat)x);
        }
      const double sx = (double)x/y, floor = std::floor(sx), delta =  sx - floor;
      return (T)(y*(rounding_type<0?floor:rounding_type>0?std::ceil(sx):delta<0.5?floor:std::ceil(sx)));

Project: CImg
File: CImg.h

        \param pos Index of the insertion.
        \param is_shared Tells if the inserted image is a shared copy of \c img or not.
    **/
    template<typename t>
    CImgList<T>& insert(const CImg<t>& img, const unsigned int pos=~0U, const bool is_shared=false) {
      const unsigned int npos = pos==~0U?_width:pos;
      if (npos>_width)
        throw CImgArgumentException(_cimglist_instance
                                    "insert(): Invalid insertion request of specified image (%u,%u,%u,%u,%p) "
                                    "at position %u.",
                                    cimglist_instance,
                                    img._width,img._height,img._depth,img._spectrum,img._data,npos);
      if (is_shared)
        throw CImgArgumentException(_cimglist_instance
                                    "insert(): Invalid insertion request of specified shared image "
                                    "CImg<%s>(%u,%u,%u,%u,%p) at position %u (pixel types are different).",
                                    cimglist_instance,
                                    img.pixel_type(),img._width,img._height,img._depth,img._spectrum,img._data,npos);

      CImg<T> *const new_data = (++_width>_allocated_width)?new CImg<T>[_allocated_width?(_allocated_width<<=1):
                                                                        (_allocated_width=16)]:0;
      if (!_data) { // Insert new element into empty list
        _data = new_data;
        *_data = img;
      } else {
        if (new_data) { // Insert with re-allocation
          if (npos) std::memcpy((void*)new_data,(void*)_data,sizeof(CImg<T>)*npos);
          if (npos!=_width - 1)
            std::memcpy((void*)(new_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos));
          std::memset((void*)_data,0,sizeof(CImg<T>)*(_width - 1));
          delete[] _data;
          _data = new_data;
        } else if (npos!=_width - 1) // Insert without re-allocation
          std::memmove((void*)(_data + npos + 1),(void*)(_data + npos),sizeof(CImg<T>)*(_width - 1 - npos));
        _data[npos]._width = _data[npos]._height = _data[npos]._depth = _data[npos]._spectrum = 0;
        _data[npos]._data = 0;

Project: CImg
File: CImg.h


    Tfloat _linear_atXYZ_p(const float fx, const float fy=0, const float fz=0, const int c=0) const {
      const float
        nfx = cimg::mod(fx,(float)_width),
        nfy = cimg::mod(fy,(float)_height),
        nfz = cimg::mod(fz,(float)_depth);
      const unsigned int
        x = (unsigned int)nfx,
        y = (unsigned int)nfy,
        z = (unsigned int)nfz;
      const float
        dx = nfx - x,
        dy = nfy - y,
        dz = nfz - z;
      const unsigned int
        nx = cimg::mod(x + 1,_width),
        ny = cimg::mod(y + 1,_height),
        nz = cimg::mod(z + 1,_depth);
      const Tfloat
        Iccc = (Tfloat)(*this)(x,y,z,c), Incc = (Tfloat)(*this)(nx,y,z,c),
        Icnc = (Tfloat)(*this)(x,ny,z,c), Innc = (Tfloat)(*this)(nx,ny,z,c),
        Iccn = (Tfloat)(*this)(x,y,nz,c), Incn = (Tfloat)(*this)(nx,y,nz,c),
        Icnn = (Tfloat)(*this)(x,ny,nz,c), Innn = (Tfloat)(*this)(nx,ny,nz,c);
      return Iccc +
        dx*(Incc - Iccc +
            dy*(Iccc + Innc - Icnc - Incc +
                dz*(Iccn + Innn + Icnc + Incc - Icnn - Incn - Iccc - Innc)) +
            dz*(Iccc + Incn - Iccn - Incc)) +
        dy*(Icnc - Iccc +
            dz*(Iccc + Icnn - Iccn - Icnc)) +
        dz*(Iccn - Iccc);

Project: CImg
File: CImg.h


      static double mp_list_whd(_cimg_math_parser& mp) {
        const unsigned int ind = (unsigned int)cimg::mod((int)_mp_arg(2),mp.listin.width());
        return (double)mp.listin[ind]._width*mp.listin[ind]._height*mp.listin[ind]._depth;

Project: CImg
File: CImg.h

      static cimg_uint64 inf() { return max(); }
      static cimg_uint64 cut(const double val) {

Project: CImg
File: CImg.h


      static double mp_max(_cimg_math_parser& mp) {
        const unsigned int i_end = (unsigned int)mp.opcode[2];
        double val = _mp_arg(3);
        for (unsigned int i = 4; i<i_end; ++i) val = std::max(val,_mp_arg(i));
        return val;

Project: CImg
File: CImg.h


    T _cubic_atX_pc(const float fx, const int y, const int z, const int c) const {
      return cimg::type<T>::cut(_cubic_atX_p(fx,y,z,c));

Project: CImg
File: CImg.h

    template<typename t>
    CImg<T>& operator*=(const t value) {
      if (is_empty()) return *this;
      cimg_openmp_for(*this,*ptr * value,262144);
      return *this;

Project: CImg
File: CImg.h

    **/
    CImg<T>& operator+=(const char *const expression) {
      return *this+=(+*this)._fill(expression,true,1,0,0,"operator+=",this);

Project: CImg
File: CImg.h

    //! Access to a pixel value, using Dirichlet boundary conditions for the X and Y coordinates \const.
    T atXY(const int x, const int y, const int z, const int c, const T& out_value) const {
      return (x<0 || y<0 || x>=width() || y>=height())?out_value:(*this)(x,y,z,c);