阅读 188

Android上进行yolov5目标检测,以torchscript的方式

环境

  • windows 10 64bit
  • android studio 4.1.2
  • yolov5 3.0
  • pytorch 1.6+cu101

前言

前文 在Android上运行YOLOv5目标检测 我们介绍过使用ncnn的方式在android设备上进行yolov5的目标检测。本篇介绍另一种方式,即torchscript

代码实践

这个demo来自pytorch官方,地址是: github.com/pytorch/and… 下载下来使用android studio打开备用。

接下来需要准备torchscript模型,这里使用yolov5 3.0的版本进行转换,来到源码目录,修改model/export.py文件

model.model[-1].export = True
复制代码

改为

model.model[-1].export = False
复制代码

然后,还是在这个文件,在代码块

ts = torch.jit.trace(model, img)
ts.save(f)
复制代码

的中间,加入下面两句

from torch.utils.mobile_optimizer import optimize_for_mobile
ts = optimize_for_mobile(ts)
复制代码

yolov5 android torchscript

修改完成后就可以进行转换了

(pytorch1.6) xugaoxiang@1070Ti:~/workshop/yolov5-3.0$ python models/export.py --weights weights/yolov5s.pt
Namespace(batch_size=1, img_size=[640, 640], weights='weights/yolov5s.pt')
Fusing layers...
Model Summary: 224 layers, 7266973 parameters, 0 gradients

Starting TorchScript export with torch 1.6.0+cu101...
/home/xugaoxiang/workshop/yolov5-3.0/models/yolo.py:49: TracerWarning: Converting a tensor to a Python boolean might cause the trace to be incorrect. We can't record the data flow of Python values, so this value will be treated as a constant in the future. This means that the trace might not generalize to other inputs!
  if self.grid[i].shape[2:4] != x[i].shape[2:4]:
/home/xugaoxiang/anaconda3/envs/pytorch1.6/lib/python3.7/site-packages/torch/jit/_trace.py:940: TracerWarning: Encountering a list at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
  _force_outplace,
TorchScript export success, saved as weights/yolov5s.torchscript.pt

Starting ONNX export with onnx 1.8.1...
ONNX export success, saved as weights/yolov5s.onnx

Starting CoreML export with coremltools 4.1...
CoreML export failure: Unknown type __torch__.torch.classes.xnnpack.Conv2dOpContext encountered in graph lowering. This type is not supported in ONNX export.

Export complete (13.42s). Visualize with https://github.com/lutzroeder/netron.
复制代码

命令的最后是导出onnx的报错,由于我们使用的是torchscript而没有用到onnx,所以这个错误可以忽略。将weights/yolov5s.torchscript.pt拷贝android工程中的目录app/src/main/assets

yolov5 android torchscript

注意看,app自带的测试图片也是存放在这里文件夹下,classes.txt是目标的名称,如果要替换自己训练的模型,这个文件也要记得修改。

准备工具就绪,接下来,我们就使用android studio来编译并且安装到android手机上去,测试自带的3张图片

yolov5 android torchscript

yolov5 android torchscript

yolov5 android torchscript

当然,这个app也可以选择手机内的图片进行检测

yolov5 android torchscript

除此以外,还可以使用手机摄像头进行目标检测

yolov5 android torchscript

使用自己的模型

yolov5的模型训练请参考这篇 xugaoxiang.com/2020/07/02/…,作为测试,我们也使用上文中训练出来的口罩检测模型

torchscript转换的步骤和上面是一样的,这里就省略了,把生成的torchscript.pt放到assets目录下,重命名为yolov5s.torchscript.pt

接着修改classes.txt

mask
no-mask
复制代码

这里的值必须与你训练时的保持一致

然后修改文件app/src/main/java/org/pytorch/demo/objectdetection/MainActivity.java

mModule = PyTorchAndroid.loadModuleFromAsset(getAssets(), "best.torchscript.pt");
BufferedReader br = new BufferedReader(new InputStreamReader(getAssets().open("classes.txt")));
复制代码

根据自己的情况,修改这2个文件名

接着修改文件ObjectDetectionActivity.java

private static int mOutputColumn = 7; // left, top, right, bottom, score and 80 class probability
复制代码

这个值是5+class数量,针对口罩这个就是5+2=7,同样是这个文件,往下拉

Result result = new Result(cls, outputs[i*7+4], rect);
复制代码

修改i*后面的值,与mOutputColumn是一样的。

最后,重新编译下工程并安装到手机上进行测试

yolov5 android torchscript

yolov5 android torchscript

yolov5 android torchscript

yolov5 android torchscript

参考资料

文章分类
人工智能
文章标签