代码我直接用的sample中的代码,用cmake编译一下即可
OpenCV4.0的源码下载后,自带的sample文件:opencv-4.0.0/samples/dnn/object_detection.cpp
或直接参看路径
https://github.com/opencv/opencv/blob/master/samples/dnn/object_detection.cpp
编译完成后运行如下命令即可进行前向预测:
./object_detection -i=dog.jpg -c=yolov3.cfg -m=yolov3.weights -classes=coco.names --scale=0.00392
其中dog.jpg文件、coco.names文件和yolov3.cfg文件均从yolov3的github中下载,
https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg
https://github.com/pjreddie/darknet/blob/master/data/coco.names
https://github.com/pjreddie/darknet/blob/master/data/dog.jpg
而参数从如下路径下载:
https://pjreddie.com/media/files/yolov3.weights
我随便找了张图片进行预测,会发现报错:
terminate called after throwing an instance of 'cv::Exception'
what(): OpenCV(4.0.0) /home/luke/Download/opencv-4.0.0/modules/dnn/src/layers/concat_layer.cpp:95: error: (-201:Incorrect size of input array) Inconsistent shape for ConcatLayer in function 'getMemoryShapes'
需要添加上宽高的参数,注意这个参数不是你图片的真实宽高,而是需要rezise的参数,参考
./object_detection -i=dog.jpg -c=yolov3.cfg -m=yolov3.weights -classes=coco.names --scale=0.00392 --width=416 --height=416
或者
./object_detection -i=dog.jpg -c=yolov3.cfg -m=yolov3.weights -classes=coco.names --scale=0.00392 --width=768 --height=576