// Code for displaying OpenCV images (cv::Mat type) with imdebug.
// This is intended to be close to the standard opencv cv::imshow
// utility function.  (See
// http://opencv.willowgarage.com/documentation/cpp/user_interface.html#cv-imshow)
//
// @author Pascal Thomet
// June 21, 2012

#ifndef imdebugcvH
#define imdebugcvH

#include <string>
#include <sstream>
#include <cv.h>

#include <imdebug.h>

namespace cv
{

  void imdbg(const char * msg, const cv::Mat & img)
  {
    std::stringstream format;
    //Image size
    format << "w=" << img.cols << " h=" << img.rows;

    //Channels
    if (img.channels() == 4)//4 channels => bgra
      format << "bgra ";
    else if (img.channels() == 3) //3 channels ==> bgr
      format << "bgr ";
    else if (img.channels() == 2) //2 channels => luminance
+ alpha
  format << "luma";
    else if (img.channels() == 1) //1 channel => luminance
      format << "lum ";
    else
      throw std::runtime_error("imdbg supports only 1,2,3,
or 4 channels matrixes...");


    //detect image type
    {
      int depth = img.depth();
      if ( (depth == CV_8U) || (depth == CV_8S) )
        format << " b=8";
      else if (depth == CV_32F)
        format << " b=32f";
      else
        throw std::runtime_error("imdbg supports only CV_8U
CV_8S or CV_32F matrixes...");
    }
    format << "t=%s %p";

    ::imdebug(format.str().c_str(), msg, img.data);
  }


  //small addon in order to show two images at the same time
  (totally optional)
  void imdbg2(const char * msg, const cv::Mat & img1,
              cv::Mat & img2, bool addborder = true)
  {
    if (img1.type() != img2.type())
      throw std::runtime_error("imdbg2 supports only images
of same type");

    int maxH = (img1.rows > img2.rows) ? img1.rows :
      img2.rows;
    if (! addborder)
    {
      cv::Mat comp( cv::Size(img1.cols + img2.cols, maxH),
                    img1.type() );
      comp = 0;
      cv::Rect roi1(0, 0, img1.cols, img1.rows);
      img1.copyTo(comp(roi1));
      cv::Rect roi2(img1.cols, 0, img2.cols, img2.rows);
      img2.copyTo(comp(roi2));
      ::imdbg(msg, comp);
    }
    else
    {
      cv::Mat comp( cv::Size(img1.cols + img2.cols + 4, maxH
                             + 2), img1.type() );
      comp = 0;
      cv::Rect roi1(1, 1, img1.cols, img1.rows);
      img1.copyTo(comp(roi1));
      cv::Rect roi2(img1.cols + 2, 1, img2.cols, img2.rows);
      img2.copyTo(comp(roi2));
      ::imdbg(msg, comp);
    }
  }
}

#endif
