十行Python代码搞定图片中的物体检测

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gshengod/article/details/80959504

“Word is useless, show me the pic” -MR Lu

先看下原图:
这里写图片描述
图片表述的是一男一女在散步,后面有一辆车,现在来看下我们通过十行代码实现的效果:

这里写图片描述

我们可以看到,在这幅图中其实有三个“person”被识别出来,包括后面非常非常小的行人,还有一个“car”被识别出来,可以说模型能力基本达到了人眼的能力。现在就来介绍如何把这个识别结果用10行python代码实现。

代码

既然代码用得少,必然是站在了巨人的肩膀上去做事,需要安装大量第三方库。

1.需要首先用pip3安装以下库:

pip3 install numpy、scipy、opencv-python、pillow、matplotlib、h5py、keras、

注意:用到的是python3,有一些库在国内安装很慢,可以使用豆瓣源

pip3  install 第三方库名  -i  https://pypi.doubanio.com/simple/  --trusted-host pypi.doubanio.com

2.然后要安装用到的识别库,名字叫imageai:

pip3 install https://github.com/OlafenwaMoses/ImageAI/releases/download/2.0.1/imageai-2.0.1-py3-none-any.whl 

3.接着要下载训练好的模型,我们直接使用现成的模型做预测,模型地址(145MB):

https://github.com/OlafenwaMoses/ImageAI/releases/download/1.0/resnet50_coco_best_v2.0.1.h5

4.最后来看看代码:

from imageai.Detection import ObjectDetection
import os

execution_path = os.getcwd()


detector = ObjectDetection()
detector.setModelTypeAsRetinaNet()
detector.setModelPath( os.path.join(execution_path , "resnet50_coco_best_v2.0.1.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image3.jpg"), output_image_path=os.path.join(execution_path , "image3new.jpg"))


for eachObject in detections:
   print(eachObject["name"] + " : " + eachObject["percentage_probability"] )
   print("--------------------------------")

clone代码地址:https://github.com/OlafenwaMoses/ImageAI

其中模型要跟代码放到统一路径下,image2.jpg是输入图片,image2new.jpg是输出图片。一共有效行数为10,不是你来打我,哈哈。运行这个文件就会生成标记好的图片。

是不是很简单,谢谢大家~

猜你喜欢

转载自blog.csdn.net/gshengod/article/details/80959504