最近再做一个Android端的人脸识别项目,每次使用新的测试机器就要拷贝模型文件,较为麻烦。所以通过上网查找和自己的一些修改,完成了直接从assert目录下将我们需要的深度学习网络模型文件拷贝到指定的位置,供后面需要加载模型时使用。
拷贝函数 //模型拷贝代码 将assets目录下的文件夹拷贝到指定目录下。 private void initFaceDetModel(AssetManager assetManager) throws IOException { String modelPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "TestModel"; //拷贝目标路径 File modelFolder = new File(modelPath); if (!modelFolder.exists()) { modelFolder.mkdir(); } //FaceModel 为assert文件夹下文件夹名称s String[] files = assetManager.list("FaceModel"); Toast.makeText(MainActivity.this, "模型初始化中...", Toast.LENGTH_LONG).show(); for (String file : files) { String destFile = modelPath + File.separator + file; File modelFile = new File(destFile); if (!modelFile.exists()) { InputStream inputStream = assetManager.open("FaceModel" + File.separator + file); FileOutputStream outputStream = new FileOutputStream(destFile); byte[] bytes = new byte[1024]; while (inputStream.read(bytes) != -1) { outputStream.write(bytes); } inputStream.close(); outputStream.close(); } } Toast.makeText(MainActivity.this,"模型初始化完成!", Toast.LENGTH_LONG).show(); } 使用 AssetManager assetManager = this.getAssets(); try { initFaceDetModel(assetManager); } catch (IOException e) { e.printStackTrace(); }至此,即可完成运行应用后自动拷贝模型,进行初始化了。
为了保证整个模型文件一致性和减少反复遍历的时间,特改写了第二版本。
private static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (int i=0; i<children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } // 目录此时为空,可以删除 return dir.delete(); } //模型拷贝代码 将assets目录下的文件夹拷贝到指定目录下。 private void initFaceDetModel(AssetManager assetManager) throws IOException { String modelPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "TestModel"; //拷贝目标路径 File modelFolder = new File(modelPath); String[] files = assetManager.list("FaceModel"); if (!modelFolder.exists()) { modelFolder.mkdir(); } else { String [] modelfiles = modelFolder.list(); if(!Arrays.equals(files,modelfiles)) //判断目标目录是否有和asserts文件夹相同文件 { //若不相同,则删除文件夹中所有文件 deleteDir(modelFolder); } else{ //若相同,则不在进行遍历操作 return; } } Toast.makeText(MainActivity.this, "模型初始化中...", Toast.LENGTH_LONG).show(); for (String file : files) { String destFile = modelPath + File.separator + file; File modelFile = new File(destFile); if (!modelFile.exists()) { InputStream inputStream = assetManager.open("FaceModel" + File.separator + file); FileOutputStream outputStream = new FileOutputStream(destFile); byte[] bytes = new byte[1024]; while (inputStream.read(bytes) != -1) { outputStream.write(bytes); } inputStream.close(); outputStream.close(); } } Toast.makeText(MainActivity.this,"模型初始化完成!", Toast.LENGTH_LONG).show(); }