1. Add opencv to the workspace
File->Import..->Android->Existing Code into Workspace. Locate the path and check "Copy projects into workspace"2. Add opencv dependency to the project:
Right click on the project->properties->Android, click "Add", and add the opencv lib:3. Add opencv support code:
Add declarations:
Mat mat;
private BaseLoaderCallback mLoaderCallback;
Overload onResume():@Override
public void onResume(){
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);
}
Add initilization in onCreate(), and any matrices are to be created after opencv lib are laoded successfully:@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
Log.i("HelloWorld: ", "OpenCV loaded successfully");
System.loadLibrary("HelloWorld");
createOpencvMatrices();
break;
default:
super.onManagerConnected(status);
}
}
};
}
void createOpencvMatrices(){
mat = new Mat();
// other matrices to be created, ...
}
Add a test function:
public native int test0(long matAddrDat);
Edit file activity_main.xml in res->layout:
<TextView android:id="@+id/tvHello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World" />
Declare TextView tvHello, and added this to onCreate:
tvHello = (TextView) findViewById(R.id.tvHello);
Add following after createOpencvMatrices();
createOpencvMatrices(); // matrix creation comes after loadLibrary
int out = test0(mat.getNativeObjAddr()); // test function
tvHello.setText("output from test0() = "+ out);
Edit HelloWorld.cpp:
......
JNIEXPORT int JNICALL Java_org_ski_helloworld_MainActivity_test0(JNIEnv*, jobject, jlong addrData)
{
Mat& mat = *(Mat*)addrData;
mat.create(1,3,CV_32F);
Mat_<float> &tmp = (Mat_<float> &)mat;
Mat_<float>::iterator it;
int i=1;
for (it =tmp.begin(); it!= tmp.end(); it++,i++)
*it = i;
int sum = 0;
for (it = tmp.begin(); it!= tmp.end(); it++)
sum += *it;
return sum;
}
......
You should get "output from test0() = 6" after you launch the app.
The zip file of the project: link.
No comments:
Post a Comment