SOL9 Sample: CannyEdgeDetector

SOL9 2.0 Samples

1 Screenshot







2 Source code

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


//2017/03/30

// Please see "http://docs.opencv.org/2.4/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html#basic-linear-transform"
// void Canny(const Mat& image, Mat& edges, 
//  double threshold1, double threshold2, int apertureSize=3, bool L2gradient=false)
// See also: https://en.wikipedia.org/wiki/Canny_edge_detector

#define _CONSOLE_

#include <sol/ModuleFileName.h>
#include <sol/DropFiles.h>
#include <sol/LabeledTrackBar.h>
#include <sol/FileDialog.h>
#include <sol/StringT.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;
    
    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);

        originalImage = readImage(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 DetectedImageView :public OpenCVImageView {
  private:
    cv::Mat originalImage;
    cv::Mat grayImage;
    
    cv::Mat detectedImage;
    
    cv::Mat& getMat()
    {
      return detectedImage;
    }
    
    void display()
    {
      show(detectedImage);
    }
    
  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);
        loadImage(filename, imageLoadingFlag);       
      } catch (SOL::Exception ex) {
        caught(ex);
      }
    }
    
    ~DetectedImageView()
    {
    }

    void loadImage(const char* filename, int imageLoadingFlag=CV_LOAD_IMAGE_COLOR)
    {
      try {
        originalImage = readImage( filename, imageLoadingFlag );
        detectedImage.create( originalImage.size(), originalImage.type() );
        cv::cvtColor( originalImage, grayImage, COLOR_BGR2GRAY );
        
        refresh();
      } catch(Exception& ex) {
        caught(ex);
      }
    }
    
    void detectEdge(double threshold1, double threshold2)
    {
      cv::Canny(grayImage, detectedImage, threshold1, threshold2);
      refresh();
    }
  };
  //Inner class ends.
  ////////////////////////////////////////////////////////////////////////////////////////
  
  
  StringT<char>                imageFile;
  StringT<char>                savedImageFile;
  
  SmartPtr<OriginalImageView>  originalImage;
  SmartPtr<DetectedImageView>  detectedImage;
    
  int                          threshold1Max;
  int                          threshold1;
  SmartPtr<LabeledTrackBar>    threshold1TrackBar;
  
  int                          threshold2Max;
  int                          threshold2;
  SmartPtr<LabeledTrackBar>    threshold2TrackBar;
  FileDialog                   filedlg;
  
  void updateCaption()
  {
    char caption[MAX_PATH];
    sprintf_s(caption, CountOf(caption), "%s - %s", 
          (const char*)imageFile, 
          getAppName());
    setText(caption);
  }

  //Horizontal Scroll event by threshold1TrackBar and threshold2TrackBar.
  void trackBarScrolled(Action& action)
  {
    threshold1 = threshold1TrackBar->getPosition();
    threshold2 = threshold2TrackBar->getPosition();
    
    detectedImage -> detectEdge((double)threshold1, (double)threshold2);
  }


  void resize(int w, int h)
  {
    if (originalImage && detectedImage && 
          threshold1TrackBar && threshold2TrackBar) {
      originalImage      -> reshape(2,            2,  (w-160)/2-1,    h-4);
      detectedImage      -> reshape((w-160)/2+1,  2,  (w-160)/2-1,    h-4);
      threshold1TrackBar -> reshape(w-155 + 10,  10, 155, 60);      
      threshold2TrackBar -> reshape(w-155 + 10,  80, 155, 60);      
    }
  }

  void openFile(const char* filename)
  {
    try {
      originalImage  -> loadImage(filename);
      detectedImage  -> loadImage(filename);
      const char* fname = strrchr(filename, '\\');
      if (fname) {
        fname++;
      }
      imageFile = fname;
      
      updateCaption();
 
      detectedImage -> detectEdge((double)threshold1, (double)threshold2);
      
    } 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)
  {
    imageFile = "..\\images\\Cloud.png";
    int imageLoadingFlag = CV_LOAD_IMAGE_COLOR;
    try {
      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);
      detectedImage = new DetectedImageView(this, "cvwindow2", ar); 

      threshold1Max = 300;
      threshold2Max = 300;

      threshold1 =  50;
      threshold2 = 100;
        
      ar.reset();
      ar.set(XmNminimum, 0);
      ar.set(XmNmaximum, threshold1Max);
      ar.set(XmNposition, threshold1);
      ar.set(XmNdisplayOddValue, false);
      threshold1TrackBar = new LabeledTrackBar(this, "Threshold1", ar);
      
      threshold1TrackBar -> addCallback(XmNtrackBarScrollCallback, this,
        (Callback)&MainView::trackBarScrolled, NULL);
            
      ar.reset();
      ar.set(XmNminimum, 0);
      ar.set(XmNmaximum, threshold2Max);
      ar.set(XmNposition, threshold2);
      ar.set(XmNdisplayOddValue, false);
      threshold2TrackBar = new LabeledTrackBar(this, "Threshold2", ar);

      threshold2TrackBar -> addCallback(XmNtrackBarScrollCallback, this,
        (Callback)&MainView::trackBarScrolled, NULL);
            
      addCallback(XmNmenuCallback, IDM_EXIT, this,
          (Callback)&MainView::confirm, NULL);
      
      detectedImage->detectEdge(threshold1, threshold2);
      
      ar.reset();
      ar.set(XmNfilter, FileDialog::getImageFilesFilter());
      filedlg.create(this, "OpenFile", ar);

      updateCaption();
      
    } 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);
    }
  }

  //2017/12/01
  void save(Action& action)
  {
    try {
      if (!savedImageFile.isEmpty()) {
        //Write detected image into the filename.
        detectedImage->writeImage(savedImageFile);
      } else {
        saveAs(action);
      }
    } catch (Exception& ex) {
      caught(ex);
    }
  }
  
  //2017/12/01
  void saveAs(Action& action)
  {
    Args ar;
    
    char dir[MAX_PATH] = { 0 };
    if (restoreFileFolder(dir, CountOf(dir))) {
      ar.set(XmNdirectory, dir);
      filedlg.setValues(ar);
    }
    
    try {    
      if(filedlg.save()) {
    
        const char* filename = filedlg.getFileName();
        saveFileFolder(filename);
        
        //Write detected image into the filename.
        detectedImage->writeImage(filename);
        savedImageFile = 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,  860);
    args.set(XmNheight, 360);
    MainView view(applet, name, args);
    view.realize();

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


Last modified: 2 Dec. 2017

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