版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
记录一下今天学习的成果,scala利用opencv识别车辆截取图片并计数,当然可以通过自己训练模型去识别各种物品,对制作机器学习训练集有很大的帮助,贴出关键的代码供大家学习参考
实现思路
- 利用opencv训练车辆识别器
- 遍历输入文件夹中所有图片,利用opencv识别到所有车辆
- 将每一张图片中的车辆截取保存
- 对每一张图中的车辆和所有车辆进行计数
关键代码:
def PlDeal(filepath:String , outpath:String): Unit ={
//分别对应输入输出路径
val file = new File(filepath)
val outfile = new File(outpath)
//判断输出目录是否存在
if(!outfile.exists()){
println("文件不存在,开始创建.....")
outfile.mkdir()
println("文件创建成功!")
}
else {
outfile.delete()
println("文件删除完毕!")
}
//判断输入目录是否能够正确打开
if(!file.isDirectory){
System.out.println("请输入正确的文件夹路径")
}
else if(file.isDirectory){
val filelist = file.list
var sum=0
//遍历输入文件夹中的所有图片
for( i <- 0 until filelist.length){
val imgname = filelist(i)
val image : Mat = Imgcodecs.imread(filepath + "/" + imgname)
//图片检测
val vehicleDetections : MatOfRect = new MatOfRect()
//车辆识别的方法
vehicleDetecter.detectMultiScale(image,vehicleDetections)
val rects = vehicleDetections.toArray
println("第"+(i+1)+"次识别的数量"+rects.length)
for (rect <- rects){
val sub: Mat = image.submat(rect)
Imgproc.rectangle(image, new Point(rect.x-2, rect.y-2), new Point(rect.x + rect.width, rect.y + rect.height),
new Scalar(0, 255, 0))
Imgcodecs.imwrite(outpath+"/"+System.currentTimeMillis()+".jpg",sub)
}
sum += vehicleDetections.toArray().length
}
println("总共识别车的数量"+sum)
}
}
运行结果:
控制台输出结果:
实验图片:
截取图片:
优缺点总结
优点:思路简单,利用opencv自带识别器进行识别无需编写大量识别代码
缺点:识别精度不够,虽然自己训练的模型相比自带的模型识别精度有很大提高,但相比利用神经网络或机器学习进行识别的精度还是相差很多