Created
February 13, 2017 15:48
-
-
Save arumoy/0b75af2078160c281d36da7401847e28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * To change this license header, choose License Headers in Project Properties. | |
| * To change this template file, choose Tools | Templates | |
| * and open the template in the editor. | |
| */ | |
| package svm_train; | |
| import org.opencv.core.Core; | |
| import org.opencv.core.CvType; | |
| import org.opencv.core.Mat; | |
| import org.opencv.core.Scalar; | |
| import org.opencv.core.TermCriteria; | |
| import org.opencv.highgui.Highgui; | |
| import org.opencv.ml.CvSVMParams; | |
| import org.opencv.ml.CvSVM; | |
| /** | |
| * | |
| * @author arumoy.chakraborty | |
| */ | |
| public class Main { | |
| static { | |
| System.loadLibrary(Core.NATIVE_LIBRARY_NAME); | |
| } | |
| private static final String TRAINING_DATA_ROOT = | |
| "C:\\Users\\arumoy.chakraborty\\Desktop\\SVM_Train\\"; | |
| /** | |
| * @param args the command line arguments | |
| */ | |
| public static void main(String[] args) { | |
| CvSVMParams params = new CvSVMParams(); | |
| params.set_svm_type(CvSVM.C_SVC); | |
| params.set_kernel_type(CvSVM.LINEAR); | |
| params.set_gamma(1); | |
| params.set_degree(0); | |
| params.set_coef0(0); | |
| params.set_C(1); | |
| params.set_p(0); | |
| params.set_nu(0); | |
| params.set_term_crit( | |
| new TermCriteria(TermCriteria.MAX_ITER, 1000, 0.01)); | |
| Mat imr = Highgui.imread(acquireTrainingDataColor("orange")+"1.bmp", | |
| Highgui.IMREAD_GRAYSCALE); | |
| Mat bir_ = imr.reshape(0, 1); | |
| Mat bir = new Mat(); | |
| bir_.convertTo(bir, CvType.CV_32F); | |
| Mat imb = Highgui.imread(acquireTrainingDataColor("orange")+"1.bmp", | |
| Highgui.IMREAD_GRAYSCALE); | |
| Mat bib_ = imb.reshape(0, 1); | |
| Mat bib = new Mat(); | |
| bib_.convertTo(bib, CvType.CV_32F); | |
| Mat trainData = new Mat(), labels = new Mat(); | |
| for (int i = 0; i < 10; i++) { | |
| trainData.push_back(bir); | |
| labels.push_back(new Mat(1, 1, CvType.CV_32F, new Scalar(1.0))); | |
| trainData.push_back(bib); | |
| labels.push_back(new Mat(1, 1, CvType.CV_32F, new Scalar(2.0))); | |
| } | |
| // CvSVM svm = new CvSVM(trainData, labels); | |
| CvSVM svm = new CvSVM(); | |
| boolean train = false; | |
| try { | |
| train = svm.train(trainData, labels, new Mat(), new Mat(), params); | |
| } catch (Exception e) { | |
| System.out.println(e.getMessage()); | |
| } | |
| if (train) { | |
| System.out.println(svm.predict(bir)); | |
| } | |
| } | |
| private static String acquireTrainingDataColor(String col) { | |
| return TRAINING_DATA_ROOT + col + "\\"; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment