OZ++ Sample: DynamicAdaptedFeatureDetector
/******************************************************************************
 *
 * Copyright (c) 2017 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer.
 *
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 *  DynamicdAdaptedFeatureDetector.cpp
 *
 *****************************************************************************/

//2017/06/10
/*
 //FAST feature detection 10 times until that number of keypoints are found
 Ptr<FeatureDetector> detector(new DynamicAdaptedFeatureDetector(new FastAdjuster(20,true),100, 110
*/
 
#include <oz++/motif/Label.h>
#include <oz++/motif/RowColumn.h>
#include <oz++/motif/LabeledTrackBar.h>
#include <oz++/opencv/OpenCVScaleComboBox.h>
#include <oz++/opencv/OpenCVMainView.h>
#include <oz++/opencv/OpenCVImageView.h>
#include <oz++/motif/FileOpenDialog.h>
#include <opencv2/features2d/features2d.hpp>

namespace OZ {

class MainView :public OpenCVMainView {

private:
  ///////////////////////////////////////////////
  //Inner classes start.
  class OriginalImageView: public OpenCVImageView {
  private:
    cv::Mat originalImage; 
    cv::Mat scaledImage;
    
    virtual void display()
    {
       show(scaledImage);
    }
 
  public:
    OriginalImageView(View* parent, const char* name, Args& args)
    :OpenCVImageView(parent, name, args)
    {
      try {
        const char* filename = (const char*)args.get(XmNimageFileName);
        int imageLoadingFlag = args.get(XmNimageLoadingFlag);
        int scalingRatio = (int)args.get(XmNimageScalingRatio);

        loadImage(filename, imageLoadingFlag, scalingRatio);
 
      } catch (OZ::Exception ex) {
        caught(ex);
      }
    } 

    ~OriginalImageView()
    {
    }
    
    void loadImage(const char* filename, 
        int imageLoadingFlag= CV_LOAD_IMAGE_COLOR,
                int scalingRatio=100)
    {
      originalImage = readImage(filename, imageLoadingFlag);
      scaleImage(originalImage, scaledImage, scalingRatio);
    }    

    void rescale(int scalingRatio)
    {
      scaledImage.release();
      scaleImage(originalImage, scaledImage, scalingRatio);
    }
  };

  class DetectedImageView: public OpenCVImageView {
  private:
    cv::Mat originalImage; 
    cv::Mat detectedImage; 
    cv::Mat scaledImage;

    //The scale image is displayed on this image view.
    virtual void display()
    {
       show(scaledImage);
    }
 
  public:
    DetectedImageView(View* parent, const char* name, Args& args)
    :OpenCVImageView(parent, name, args)
    {
      try {
        const char* filename = (const char*)args.get(XmNimageFileName);
        int imageLoadingFlag = args.get(XmNimageLoadingFlag);

        int scalingRatio = (int)args.get(XmNimageScalingRatio);
        loadImage(filename, imageLoadingFlag, scalingRatio);

      } catch (OZ::Exception ex) {
        caught(ex);
      }
    } 

    ~DetectedImageView()
    {
    }
    
    void loadImage(const char* filename, 
        int imageLoadingFlag= CV_LOAD_IMAGE_COLOR,
                int scalingRatio=100)
    {
      originalImage = readImage(filename, imageLoadingFlag);
      detectedImage  = originalImage.clone();
      //detectedImage.create( originalImage.size(), originalImage.type() );

      scaleImage(detectedImage, scaledImage, scalingRatio);
    }    

    void rescale(int scalingRatio)
    {
      scaledImage.release();
      scaleImage(detectedImage, scaledImage, scalingRatio);
    }

    void detect(int min, int max, int iterator, 
                      int scalingRatio)
    //void detect(int scalingRatio)
    {
      //OpenCV2.4.8
      //class CV_EXPORTS FastAdjuster: public AdjusterAdapter {
      //
      // FastAdjuster(int init_thresh=20, 
      //   bool nonmax=true, int min_thresh=1, int max_thresh=200);

      //
      //class CV_EXPORTS DynamicAdaptedFeatureDetector: public FeatureDetector {
      //
      //DynamicAdaptedFeatureDetector( const Ptr<AdjusterAdapter>& adjuster, 
      //   int min_features=400, int max_features=500, int max_iters=5 );

      detectedImage  = originalImage.clone();

      cv::Ptr<cv::DynamicAdaptedFeatureDetector> detector = 
          new cv::DynamicAdaptedFeatureDetector(
                      new cv::FastAdjuster(20, true), 
                      min, max, iterator);
      std::vector<cv::KeyPoint> keypoints;

      detector->detect(detectedImage, keypoints);

      drawKeypoints(detectedImage, keypoints, detectedImage, 
                                    cv::Scalar(0xff, 0x00, 0x00)); //BLUE in BGR
      scaleImage(detectedImage, scaledImage, scalingRatio);
    }
  };
  //Inner classes end.
    
private:

  StringT<char>                imageFile;
  int                          imageLoadingFlag;
  int                          imageScalingRatio; //percentage 

  SmartPtr<Label>              label;
  SmartPtr<OriginalImageView>  originalImage;
  SmartPtr<DetectedImageView>   detectedImage;
  SmartPtr<RowColumn>          controlPane;
  SmartPtr<OpenCVScaleComboBox>  scaleComboBox;

  int                          minFeature;
  int                          maxFeature;
  int                          maxIterator;

  SmartPtr<LabeledTrackBar>     minFeatureTrackBar;
  SmartPtr<LabeledTrackBar>     maxFeatureTrackBar;
  SmartPtr<LabeledTrackBar>     maxIteratorTrackBar;

  SmartPtr<FileOpenDialog>     fileDialog;

public:
  void scaleChanged(Action& action)
  {
    int val = scaleComboBox->getScale();

    if (val > 0 && imageScalingRatio != val) {
      imageScalingRatio = val;
      originalImage -> rescale(imageScalingRatio); 
      detectedImage -> rescale(imageScalingRatio); 
    }
  }  

  void minFeatureTrackBarScrolled(Action& event)
  {
    minFeature = minFeatureTrackBar->getPosition(); 
    detectedImage->detect(minFeature, maxFeature, 
                          maxIterator,imageScalingRatio);
  }

  void maxFeatureTrackBarScrolled(Action& event)
  {
    maxFeature = maxFeatureTrackBar->getPosition();
    detectedImage->detect(minFeature, maxFeature,  
                          maxIterator,imageScalingRatio);
  }

  void maxIteratorTrackBarScrolled(Action& event)
  {
    maxIterator = maxIteratorTrackBar->getPosition();
    detectedImage->detect(minFeature, maxFeature,  
                          maxIterator,imageScalingRatio);
  }

  void cancel(Action& action)
  {
    fileDialog->popdown();
  }

  void fileOpen(Action& action)
  {
    fileDialog->popup();
  }

  void updateLabel(const char* filename)
  {
     CompoundString cs(filename);
     label->set(XmNlabelString, cs);    
  }

  void ok(Action& action)
  {
    try {  
      imageFile  = fileDialog->getFileName();
      const char* filename = (const char*)imageFile;
      printf("filename: %s\n", filename);
      fileDialog->popdown();
    
      originalImage->invalidate();
      originalImage->loadImage(filename, 
        imageLoadingFlag, imageScalingRatio);

      detectedImage->invalidate();
      detectedImage->loadImage(filename, 
        imageLoadingFlag, imageScalingRatio); 

      detectedImage->detect(minFeature, maxFeature,  
                          maxIterator,imageScalingRatio);
      updateLabel(filename);

      resize(width(), height());
      flush();
    } catch (OZ::Exception& ex) {
       caught(ex);
    } 
  }

  void resize(Dimension w, Dimension h)
  {
    int CP_WIDTH = 200;
    int LB_HEIGHT = 30;
    int ww =  w-CP_WIDTH;
    int hh = h - LB_HEIGHT;
    if (label && originalImage && detectedImage && controlPane 
     ) {
      label        -> reshape(0, 0, w, LB_HEIGHT); 
      originalImage-> reshape(0, LB_HEIGHT, ww/2, hh);
      detectedImage -> reshape(ww/2, LB_HEIGHT, ww/2-1, hh);
     
      controlPane  -> reshape(ww-1, LB_HEIGHT, CP_WIDTH+1, hh);

      //The following two lines are a workaround to erase garbage.
      controlPane -> unmap();
      controlPane -> map();
    }

    flush();
  }

public:
  MainView(OpenCVApplication& applet, const char* name, Args& args)
  :OpenCVMainView(applet, name, args) 
  {
    BulletinBoard* bboard = getBulletinBoard();
    imageFile = "../images/flower.png";
    imageLoadingFlag = CV_LOAD_IMAGE_COLOR;
    imageScalingRatio = 60; //%

    try {
      Args ar;
      CompoundString fileNamecs((const char*)imageFile);
      ar.set(XmNlabelString, fileNamecs); 
      ar.set(XmNalignment, XmALIGNMENT_BEGINNING); 
      label = new Label(bboard, "", ar);

      ar.reset();
      ar.set(XmNimageFileName, (const char*)imageFile);
      ar.set(XmNimageLoadingFlag, imageLoadingFlag);
      ar.set(XmNimageScalingRatio, imageScalingRatio);

      originalImage = new OriginalImageView(bboard, "", ar);

      ar.reset();
      ar.set(XmNimageFileName, (const char*)imageFile);
      ar.set(XmNimageLoadingFlag, imageLoadingFlag);
      ar.set(XmNimageScalingRatio, imageScalingRatio);

      detectedImage   = new DetectedImageView(bboard, "", ar);

      ar.reset();
      controlPane = new RowColumn(bboard, "", ar);
      const char* defaultScale = "60%";

      ar.reset();
      CompoundString scaler("Scale");
      ar.set(XmNlabelString, scaler);
      ar.set(XmNdefaultScale, defaultScale);
      scaleComboBox = new OpenCVScaleComboBox(controlPane, "", ar);
      scaleComboBox->addCallback(XmNselectionCallback, this,
        (Callback)&MainView::scaleChanged, NULL);


      minFeature = 100;
      maxFeature = 210;
      maxIterator = 10;
      CompoundString cs1("MinFeature:[10, 200]");
      ar.reset();
      ar.set(XmNtitleString, cs1);
      ar.set(XmNminimum, 10); 
      ar.set(XmNmaximum, 200);
      ar.set(XmNvalue, minFeature);
      minFeatureTrackBar = new LabeledTrackBar(controlPane, "minFeature", ar);
      minFeatureTrackBar -> addCallback(XmNvalueChangedCallback, this,
        (Callback)&MainView::minFeatureTrackBarScrolled, NULL);

      CompoundString cs2("MaxFeature:[200, 400]");
      ar.reset();
      ar.set(XmNtitleString, cs2);
      ar.set(XmNminimum, 200); 
      ar.set(XmNmaximum, 400);
      ar.set(XmNvalue, maxFeature);
      maxFeatureTrackBar = new LabeledTrackBar(controlPane, "maxFeature", ar);
      maxFeatureTrackBar -> addCallback(XmNvalueChangedCallback, this,
        (Callback)&MainView::maxFeatureTrackBarScrolled, NULL);

      CompoundString cs3("MaxIterator:[5, 20]");
      ar.reset();
      ar.set(XmNtitleString, cs3);
      ar.set(XmNminimum, 5);
      ar.set(XmNmaximum, 20);
      ar.set(XmNvalue, maxIterator);
      maxIteratorTrackBar = new LabeledTrackBar(controlPane, "maxIterator", ar);
      maxIteratorTrackBar -> addCallback(XmNvalueChangedCallback, this,
        (Callback)&MainView::maxIteratorTrackBarScrolled, NULL);

      detectedImage->detect(minFeature, maxFeature, 
                          maxIterator,imageScalingRatio);

      ar.reset();
      fileDialog = new FileOpenDialog(this, "FileOpenDialog", ar);
      fileDialog  -> getOkButton()
                  -> addCallback(XmNactivateCallback, this,
                          (Callback)&MainView::ok, NULL); 
      sendConfigureEvent(); 
    } catch(OZ::Exception& ex) {
      caught(ex);
    }
  }

  ~MainView()
  {
  }
};

}

//
int main(int argc, char** argv) 
{
  try {
    const char*  appclass = argv[0];
    OpenCVApplication applet(appclass, argc, argv);

    Args args;
    args.set(XmNwidth,  900);
    args.set(XmNheight, 380);
    MainView view(applet, argv[0], args);
    view.realize();

    applet.run();
    
  } catch (OZ::Exception& ex) {
    caught(ex);
  }
  return 0;
}