Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JNI Demo (invode opencv ...)
#include "cvjni.h"
#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>
using namespace std;
using namespace cv;
/*
* Class: CVJNI
* Method: toBMP
* Signature: ([B)[B
*/
JNIEXPORT jbyteArray JNICALL Java_CVJNI_toBMP (JNIEnv * env, jclass jc, jbyteArray jba) {
cout << "This is in JNI" << endl;
//convert jbyteArray to vector<char>
unsigned char * isCopy;
jbyte* jbae = env->GetByteArrayElements(jba, isCopy);
jsize len = env->GetArrayLength(jba);
char * imageSource = (char *)jbae;
vector<char> imageSourceV;
for (int i = 0; i < len; i++) {
imageSourceV.push_back(imageSource[i]);
}
//convert format
Mat image = imdecode(imageSourceV, CV_LOAD_IMAGE_COLOR);
vector<unsigned char> imageDesV;
imencode(".bmp", image, imageDesV);
//convert vector<char> to jbyteArray
jbyte* result_e = new jbyte[imageDesV.size()];
jbyteArray result = env->NewByteArray(imageDesV.size());
for (int i = 0; i < imageDesV.size(); i++) {
result_e[i] = (jbyte)imageDesV[i];
}
env->SetByteArrayRegion(result, 0, imageDesV.size(), result_e);
return result;
}
import java.io.*;
public class CVJNI {
//Load jni library
static {
try {
System.loadLibrary("cvjni");
} catch (Exception e) {
e.printStackTrace();
}
}
//native method
public static native byte[] toBMP(byte[] imageSource);
//main
public static void main(String [] args) {
String input = args[0];
String output = args[1];
FileInputStream fi = null;
FileOutputStream fo = null;
try {
File infile = new File(args[0]);
int len = (int)infile.length();
//get source
fi = new FileInputStream(infile);
byte[] imageSource = new byte[len];
fi.read(imageSource, 0, len);
//revoke native method
byte[] outImage = CVJNI.toBMP(imageSource);
//write
fo = new FileOutputStream(output);
fo.write(outImage);
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if (fi != null)
fi.close();
if (fo != null)
fo.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
# FOR MAC
CC=g++
SEARCH_LIB=-lopencv_core -lopencv_highgui
INCLUDE=-I/usr/local/include -I$(JAVA_INCLUDE)
LIBRARY=-L/usr/local/lib
FLAGS= -m64 -dynamiclib -fPIC
OUT=libcvjni.jnilib
SRC=cvjni.cpp
mac:
$(CC) $(FLAGS) $(LIBRARY) $(SEARCH_LIB) $(INCLUDE) $(SRC) -o $(OUT)
# FOR LINUX
CC=g++
CV_PATH=/usr/local/lib
SEARCH_LIB=$(CV_PATH)/libopencv_core.so $(CV_PATH)/libopencv_highgui.so
INCLUDE=-I/usr/local/include -I$(JAVA_INCLUDE)
LIBRARY=-L/usr/local/lib
OUT=libcvjni.so
SRC=cvjni.cpp
FLAGS= -m64 -shared -fPIC
all:
$(CC) $(FLAGS) $(SRC) $(SEARCH_LIB) -o $(OUT) $(INCLUDE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment