下面介绍如何在Android Studio开发环境下通过角蜂鸟SDK使用Mnist卷积神经网络,实现数字识别,本文的介绍示例是使用角蜂鸟摄像头,如果需要外部图像来源可参考示例工程实现
该lib下包含了SungemSDK-Android及javacv所需要的jar和so库
注意:libs文件夹路径不能包含中文,否则会编译失败
2.请在build.gradle文件里,将上述库放入正确路径下,如检索不到,可手动添加引用:
为了保证SDK正常运行,需要在AndroidManistest.xml文件下添加下列许可:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.hardware.usb.host"/>
<uses-permission android:name="android.hardware.usb.accessory"/>
<uses-feature android:name="android.hardware.usb.host"/>
下面通过一个简单hello2018的例子讲解具体怎么使用角蜂鸟SDK
初始化HsDevice,用于角蜂鸟通信和显示结果,具体代码如下:
mHsDevice = new HsDevice(this) {
@Override
public void openSucceed(UsbDevice usbDevice) {
Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
mUsbDevice = usbDevice;
mCbDevice.setChecked(true);
}
@Override
public void openFailed() {
mCbDevice.setChecked(false);
Toast.makeText(MainActivity.this, "请重新插拔角蜂鸟允许权限", Toast.LENGTH_SHORT).show();
}
@Override
public void disConnected() {
mCbDevice.setChecked(false);
Toast.makeText(MainActivity.this, "断开连接", Toast.LENGTH_SHORT).show();
}
};
Hello2018Thread继承HsThread,处理业务逻辑,核心代码如下:
@Override
public void run() {
super.run();
int status = openDevice();
if (status != ConnectStatus.HS_OK) {
return;
}
int id = allocateGraphByAssets("graph_mnist");
if (id<0) {
return;
}
for (int i = 1; i < 5; i++) {
int[] ints = new int[28 * 28];
try {
InputStream inputStream = mActivity.getAssets().open("hello/" + i + ".jpg");
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap.getPixels(ints, 0, 28, 0, 0, 28, 28);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
float[] float_tensor = new float[28 * 28];
for (int j = 0; j < 28 * 28; j++) {
float_tensor[j] = Color.red(ints[j]) * 0.007843f - 1;
}
int status_load = loadTensor(float_tensor, float_tensor.length, id);
if (status_load == ConnectStatus.HS_OK) {
float[] result = getResult(id);
if (result != null) {
int max = getMaxPossible(result);
mHandler.sendEmptyMessage(max);
}
}
}
}
public int getMaxPossible(float[] arr) {
int max = 0;
float max_f = 0;
for (int i = 0; i < arr.length; i++) {
float temp = arr[i];
if (temp > max_f) {
max = i;
max_f = temp;
}
}
return max;
}
注意:如果不打开设备,程序会执行openFailed()回调,想再次使用,请重新插拔角蜂鸟