只需10行Python代码,就能实现目标检测!
2012年深度学习的突破性进展和迅速普及,使得R-CNN、Fast-RCNN、Faster-RCNN、RetinaNet以及快速、高度准确的SSD、YOLO等目标检测算法应运而生。这些基于深度学习、机器学习的算法,需要一定的数学以及深度学习框架基础。有数百万的专业计算机程序员和软件开发人员想要集成和创建基于目标检测算法的新产品。同时由于理解和实际使用较为复杂,一直无法实现。如何开发出高效的目标检测代码呢?ImageAI就应运而生了。
ImageAI让代码变得简洁
👉点击领取:最全Python资料合集
准备工作
使用ImageAI实现目标检测,只需进行以下4步:
在你的电脑上安装Python
安装ImageAI,配置依赖环境
下载目标检测模块文件
运行样例代码(只需10行)
pip install tensorflowpip install numpypip install scipypip install opencv-pythonpip install pillowpip install matplotlibpip install h5pypip install keraspip3 install imageai --upgrade注意:第一次安装ImageAI库,需要下载对应版本的.whl文件,文摘菌的电脑是Python3的环境,所以下载了imageai-2.0.2-py3-none-any.whl 文件,然后转移到相应的文件夹下,执行如下命令即可安装:
pip install imageai-2.0.2-py3-none-any.whl开启10行代码的目标检测
FirstDetection.py:
from imageai.Detection import ObjectDetectionimport osexecution_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 , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))for eachObject in detections:print(eachObject["name"] , " : " , eachObject["percentage_probability"] )
图片来源:alzheimers.co.uk
图片来源:Wikicommons
在Spyder编译器中运行结果如下所示:
知其然知其所以然:代码解读
下面来解释一下这10行代码的工作原理:
from imageai.Detection import ObjectDetectionimport osexecution_path = os.getcwd()
在以上3行代码中,在第一行导入了ImageAI的目标检测类;在第二行导入了Python的os类;在第三行中定义了一个变量,保存Python文件、RetinaNet模型文件以及图像所在文件夹的路径。
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 , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"))
在以上5行代码中,我们在第一行中定义了一个目标检测类的实例;在第二行中将实例的模型类型设定为RetinaNet;在第三行中将模型路径设置为RetinaNet模型的路径;在第四行中将模型加载到目标检测类的实例中;在第五行中调用检测函数,并将文件输入输出路径作为参数传入。
for eachObject in detections:print(eachObject["name"] , " : " , eachObject["percentage_probability"] )
自定义目标检测
除此外,ImageAI也支持强大的自定义目标检测。其中之一是能够提取图像中检测到的每个物体。只需要将参数
extract_detected_objects=True传入
detectObjectsFromImage函数中,如下所示,目标检测类将为图像对象创建一个文件夹,提取每个图像,将每个子图像保存到创建的新文件夹中,并返回一个包含每个图像路径的数组。
detections, extracted_images = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image.jpg"), output_image_path=os.path.join(execution_path , "imagenew.jpg"), extract_detected_objects=True)ImageAI的其他功能
ImageAI提供了许多功能,可用于目标检测任务的自定义和部署。其支持的功能包括:
调整最小概率:默认情况下,概率小于50%的物体不会显示。对于需要高精度的情况,可以增加此值;对于需要检测所有可能对象的情况,可以减少此值。 自定义目标检测:通过提供的CustomObject类,可以使检测类检测一个或几个特定目标。 检测速度:通过将检测速度设置为“fast”、“faster”或“fastest”,可以减少检测图像所需的时间。 输入类型:可指定并解析图像的文件路径,以Numpy数组或图像文件流作为输入 输出类型:可指定detectObjectsFromImage函数以文件或Numpy数组的形式返回图像
https://towardsdatascience.com/object-detection-with-10-lines-of-code-d6cb4d86f606