SOL9 Sample: ImageThresholding

SOL9 2.0 Samples

1 Screenshot















2 Source code

/*
 * ImageThresholding.cpp 
 * Copyright (c) 2015 Antillia.com TOSHIYUKI ARAI. ALL RIGHTS RESERVED. 
 */


//2017/04/12

// See: http://docs.opencv.org/3.2.0/d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57
// See: http://docs.opencv.org/3.2.0/db/d8e/tutorial_threshold.html
/*
double cv::threshold  ( InputArray  src,  
  OutputArray  dst,  
  double  thresh,  
  double  maxval,  
  int  type  
 )   
*/

#define _CONSOLE_

#include <sol/ModuleFileName.h>
#include <sol/Pair.h>
#include <sol/DropFiles.h>
#include <sol/LabeledTrackBar.h>
#include <sol/LabeledComboBox.h>

#include <sol/FileDialog.h>
#include <sol/opencv/OpenCVApplicationView.h>
#include <sol/opencv/OpenCVImageView.h>


namespace SOL {

class MainView :public OpenCVApplicationView {

private:
  ////////////////////////////////////////////////////////////////////////////////////////
  //Inner class starts.
  class OriginalImageView :public OpenCVImageView {
  private:
    cv::Mat originalImage;
    
    //This is a mandatory method, because in parent class it's declared
    //as a pure virtual function.
    cv::Mat& getMat()
    {
      return originalImage;
    }
    
    void display()
    {
      show(originalImage);
    }
    
  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);
        loadImage(filename, imageLoadingFlag);
      } catch (SOL::Exception ex) {
        caught(ex);
      }
    }
    
    ~OriginalImageView()
    {
    }
    
    void loadImage(const char* filename, int imageLoadingFlag= CV_LOAD_IMAGE_COLOR)
    {
      try {
        originalImage = readImage(filename, imageLoadingFlag);
        refresh();
      } catch (Exception& ex) {
        caught(ex);
      }
    }
  };
  
  class BinarizedImageView  :public OpenCVImageView {
  private:
    cv::Mat originalImage;
    cv::Mat grayImage;
    cv::Mat destImage;
    
    cv::Mat& getMat()
    {
      return destImage;
    }
    
    void display()
    {
      show(destImage);
    }
    
  public:
    BinarizedImageView(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);
        loadImage(filename, imageLoadingFlag);
      } catch (SOL::Exception ex) {
        caught(ex);
      }
    }
    
    ~BinarizedImageView()
    {
    }
    
    void loadImage(const char* filename, int imageLoadingFlag= CV_LOAD_IMAGE_COLOR)
    {
      try {
        originalImage = readImage(filename, imageLoadingFlag);
        cv::cvtColor( originalImage, grayImage, COLOR_BGR2GRAY); 
        destImage  = grayImage.clone();
        refresh();
      } catch (Exception& ex) {
        caught(ex);
      }
    }
    
    void binarize(int thresholdType, int thresholdValue)
    {
      cv::threshold( grayImage, destImage, thresholdValue, THRESHOLD_VALUE_MAX, thresholdType );

      refresh();
    }
  };
  //Inner class ends.
  ////////////////////////////////////////////////////////////////////////////////////////
  
  
  StringT<char>                imageFile;
  
  SmartPtr<OriginalImageView>  originalImage;
  SmartPtr<BinarizedImageView> binarizedImage;

  int                          thresholdTypeIndex;
  
  SmartPtr<LabeledComboBox>    thresholdTypeComboBox;

  int                          thresholdValue;
  
  SmartPtr<LabeledTrackBar>    thresholdValueTrackBar;
  
  FileDialog                   filedlg;

  static const int THRESHOLD_VALUE_MAX = 255;

  static int getThresholdType(int index) 
  {
    int n = 0;
    //We don't include the THRESH_OTSU type
    Pair<int, int> types[] = {
      {n++, cv::THRESH_BINARY     },
      {n++, cv::THRESH_BINARY_INV },
      {n++, cv::THRESH_TRUNC      },
      {n++, cv::THRESH_TOZERO     },
      {n++, cv::THRESH_TOZERO_INV },
      {n++, cv::THRESH_OTSU       }, 
      {n++, cv::THRESH_TRIANGLE   }, 
    };
    int type = THRESH_BINARY; 
    if (index >= 0 && index <n) {
      type = types[index].second;
    } 
    return type;
  }
  
  void updateCaption()
  {
    char caption[MAX_PATH];
    sprintf_s(caption, CountOf(caption), "%s - %s", 
        (const char*)imageFile, 
        getAppName() ); 
       
    setText(caption);
  }

  
  void selChanged(Action& event)
  {
    thresholdTypeIndex = thresholdTypeComboBox -> getCurSel();
    binarizedImage -> binarize( getThresholdType(thresholdTypeIndex), thresholdValue );
  }
  
  void trackBarScrolled(Action& event)
  {
    thresholdTypeIndex = thresholdTypeComboBox -> getCurSel();
    thresholdValue     = thresholdValueTrackBar -> getPosition();
    binarizedImage -> binarize( getThresholdType(thresholdTypeIndex), thresholdValue );
  }
  
  void resize(int w, int h)
  {
    if (originalImage && binarizedImage) {
      originalImage           -> reshape(          2,   2, (w-170)/2-2, h-4);
      binarizedImage          -> reshape((w-170)/2+1,   2, (w-170)/2-2, h-4);
      thresholdTypeComboBox   -> reshape((w-170)+1,   2,         165,  50);
      thresholdValueTrackBar  -> reshape((w-170)+1,  70,         165,  50);
    }
  }


  void openFile(const char* filename)
  {
    try {
        
        originalImage   -> loadImage(filename);
        binarizedImage  -> loadImage(filename);
        const char* fname = strrchr(filename, '\\');
        if (fname) {
          fname++;
        }
        imageFile = fname;
        updateCaption();

        binarizedImage -> binarize( getThresholdType(thresholdTypeIndex), thresholdValue );

    } catch (Exception& ex) {
      caught(ex);
    }
  }
  
  void dropFiles(Action& action)
  {
    char fileName[MAX_PATH] = { 0 };
    DropFiles drop((HDROP)action.getWParam());
    //fileName[0] = ZERO;
    int num = drop.queryFile(0, fileName, CountOf(fileName));
    if(num > 0) {
      if (filedlg.isImageFileName(fileName)) {
        openFile(fileName);
        bringUp();
      } else {        
        bringUp(); //Activate and raise this view
        showErrorDialog("Invalid image filename", fileName,  MB_OK);
      }
    }
  }


  void confirm(Action& action)
  {
    int rc = MessageBox(NULL, "Are you sure to close this window?", "Confirmation", 
                MB_OKCANCEL|MB_ICONEXCLAMATION);
    if (rc == IDOK) {
      exit(action);
    }
  }
  
public:
  MainView(OpenCVApplication& applet, const char* name, Args& args)
  :OpenCVApplicationView(applet, name, args)

  {
    try {
      imageFile = "..\\images\\flower.png";
      
      int  imageLoadingFlag = CV_LOAD_IMAGE_COLOR;
      Args ar;
      ar.set(XmNimageFileName, imageFile);
      ar.set(XmNimageLoadingFlag, imageLoadingFlag);
      originalImage = new OriginalImageView(this, "cvwindow1", ar); 
      originalImage -> addCallback(XmNdropCallback, this,
        (Callback)&MainView::dropFiles, NULL);
      
      ar.reset();
      ar.set(XmNimageFileName, imageFile);
      ar.set(XmNimageLoadingFlag, imageLoadingFlag);
      binarizedImage = new BinarizedImageView(this, "cvwindow2", ar); 

      //Create a thresholdTypeComboBx
      ar.reset();
      thresholdTypeComboBox = new LabeledComboBox(this, "ThresholdType", ar);
      const char* types[] = {
        "Binary",
        "Binary Inverted",
        "Threshold Truncated",
        "Threshold to Zero",
        "Threshold to Zero Inverted",
        //"Mask", 
        "Otsu", 
        "Triangle", 
      };
      for (int i = 0; i<CountOf(types); i++) {
        thresholdTypeComboBox -> addString(types[i]);
      }
      thresholdTypeIndex = 3;
      
      thresholdTypeComboBox -> setCurSel(thresholdTypeIndex);
      //Add a selChanged callback.
      thresholdTypeComboBox -> addCallback(XmNselChangeCallback, this,
        (Callback)&MainView::selChanged, NULL);
     
      //Create a thresholdValueTrackBar
      thresholdValue = 80;
      ar.reset();
      ar.set(XmNminimum, 0);
      ar.set(XmNmaximum, THRESHOLD_VALUE_MAX);
      ar.set(XmNposition, thresholdValue);
      ar.set(XmNdisplayOddValue, FALSE);
      thresholdValueTrackBar = new LabeledTrackBar(this, "ThresholdValue", ar);
      //Add a trackBarScrolled callback to the thresoldValueTackBar
      thresholdValueTrackBar -> addCallback(XmNtrackBarScrollCallback, this,
        (Callback)&MainView::trackBarScrolled, NULL);
 
      addCallback(XmNmenuCallback, IDM_EXIT, this,
          (Callback)&MainView::confirm, NULL);

      binarizedImage -> binarize(getThresholdType(thresholdTypeIndex), thresholdValue);
   
      updateCaption();  

      ar.reset();
      ar.set(XmNfilter, FileDialog::getImageFilesFilter());
      filedlg.create(this, "OpenFile", ar);
      
    } catch (Exception& ex) {
      caught(ex);
    }
  }

  ~MainView()
  {
  }

  void open(Action& action)
  {
    Args ar;
    
    char dir[MAX_PATH] = { 0 };
    if (restoreFileFolder(dir, CountOf(dir))) {
      ar.set(XmNdirectory, dir);
      filedlg.setValues(ar);
    }
    
    try {    
      if(filedlg.open()) {
    
        const char* filename = filedlg.getFileName();
        saveFileFolder(filename);

        openFile(filename);
      }
    } catch (Exception& ex) {
      caught(ex);
    }
  }  
};
}

//
void main(int argc, char** argv) 
{
  try {
    ModuleFileName module(argv[0]);
    
    const char*  name = module.getAppName();
        
    OpenCVApplication applet(name, argc, argv);

    Args args;
    args.set(XmNwidth,  800);
    args.set(XmNheight, 400);  
    MainView view(applet, name, args);
    view.realize();

    applet.run();
    
  } catch (SOL::Exception& ex) {
    caught(ex);
  }
}


Last modified: 27 Apr. 2017

Copyright (c) 2017 Antillia.com ALL RIGHTS RESERVED.