Labels

Linux (6) OpenCV (4) Deep Learning (3) MATLAB (3) Mac OS X (3) Windows (2) C# (1) Node JS (1)

2013年7月14日 星期日

Using LIBSVM with OpenCV Mat


  LIBSVM is the most popular machine learning tool developed by C. J. Lin at National Taiwan University (http://www.csie.ntu.edu.tw/~cjlin/libsvm/). This code demonstrates how to load a data matrix in CSV format using OpenCV, and allocates LIBSVM data structure to do SVM predict. 


#include "svm.h"
#include <iostream>

#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/ml/ml.hpp"
#include <iostream>

using namespace cv;
using namespace std;


const char *CSV_FILE = "/Users/kuanting/libsvm-3.17/heart_scale.csv";
const char *MODEL_FILE = "/Users/kuanting/libsvm-3.17/heart_scale.model";

int main(int argc, char * argv[])
{
    CvMLData dataFile;
    
    // Load matrix data in csv format
    if (dataFile.read_csv(CSV_FILE) != 0)
    {
        fprintf(stderr, "Can't read csv file %s\n", CSV_FILE);
        return -1;
    }
    
    Mat dataMat(dataFile.get_values()); // Default data type is float
    
    struct svm_model *SVMModel;
    if ((SVMModel = svm_load_model(MODEL_FILE)) == 0) {
        fprintf(stderr, "Can't load SVM model %s", MODEL_FILE);
        return -2;
    }
    
    struct svm_node *svmVec;
    svmVec = (struct svm_node *)malloc((dataMat.cols+1)*sizeof(struct svm_node));
    double *predictions = new double[dataMat.rows];
    float *dataPtr = dataMat.ptr<float>(); // Get data from OpenCV Mat
    double prob_est[2];  // Probability estimation
    int r, c;
    for (r=0; r<dataMat.rows; r++)
    {
        for (c=0; c<dataMat.cols; c++)
        {
            svmVec[c].index = c+1// Index starts from 1; Pre-computed kernel starts from 0
            svmVec[c].value = dataPtr[r*dataMat.cols + c];
        }
        svmVec[c].index = -1;   // End of line
        
        if(svm_check_probability_model(SVMModel))
        {
            predictions[r] = svm_predict_probability(SVMModel, svmVec, prob_est);
            printf("%f\t%f\t%f\n", predictions[r], prob_est[0], prob_est[1]);
        }
        else
        {
            predictions[r] = svm_predict(SVMModel, svmVec);
            printf("%f\n", predictions[r]);
        }
    }
    
    return 0;
}

2013年7月2日 星期二

Using SCP on MAC with Filename Containing Spaces

This is a little tricky so it's worth posting:


scp user@host:"'/Path/Some Filename With Spaces'" [destination]


Note that we need to use " + ' to brace the Path, or the SCP will print error "scp: ambiguous target"