Skip to content

Instantly share code, notes, and snippets.

@slaypni
Last active August 29, 2015 14:23
Show Gist options
  • Save slaypni/17d7edd7b9bb37d650a4 to your computer and use it in GitHub Desktop.
Save slaypni/17d7edd7b9bb37d650a4 to your computer and use it in GitHub Desktop.
Machine Learning Sample Code with OpenCV 3.0 for Android
import android.util.Log;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.ml.LogisticRegression;
public class MLTest {
private final static String TAG = MLTest.class.getSimpleName();
MLTest() {
run();
}
void run() {
float[][] trainingData = new float[][]{{501f, 10f}, {255f, 10f}, {501f, 255f}, {10f, 501f}};
Mat trainingDataMat = new Mat(4, 2, CvType.CV_32FC1);
for (int i = 0; i < trainingData.length; i++) {
for (int j = 0; j < trainingData[i].length; j++) {
trainingDataMat.put(i, j, trainingData[i][j]);
}
}
float[] labels = new float[]{1.0f, 2.0f, 1.0f, 2.0f};
Mat labelsMat= new Mat(4, 1, CvType.CV_32FC1);
for (int i = 0; i < trainingData.length; i++) {
labelsMat.put(i, 0, labels[i]);
}
float[] testData = new float[]{502f, 10f};
Mat testDataMat = new Mat(1, 2, CvType.CV_32FC1);
for (int i = 0; i < testData.length; i++) {
testDataMat.put(0, i, testData[i]);
}
Mat resultMat = new Mat(1, 1, CvType.CV_32SC1);
LogisticRegression clf = LogisticRegression.create();
clf.train(trainingDataMat, 0, labelsMat);
clf.predict(testDataMat, resultMat, 0);
Log.i(TAG, String.format("predicted: %f", (float)resultMat.get(0, 0)[0]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment