本文代码来源:https://github.com/OlafenwaMoses/ImageAI/tree/master/imageai/Detection
之前的数字识别属于图像分类,即给出一个手写的数字,通过图像识别得出属于该手写数字属于0-9哪个类别。
有的应用环境下不仅需要我们给图像分类,还需要标记出目标的位置。因此涉及到对象检测。
对象检测涉及两个任务,一个是框出目标的位置,一个是确定对象的类型。对象检测的方法有不少种,但原理攻城狮现在都看不太懂。因此攻城狮选择了其中比较新潮而流行的YOLO(You Only Look Once)。同时,为了方便,选择了只需几行代码就可以完成检测工作的ImageAI。
图片来自YOLO官方网站,相当有风格。
要完成对象检测,我们首先需要配置一些环境,这里简述如下:
其次需要下载ImageAI,https://github.com/OlafenwaMoses/ImageAI/releases/download/1.0/yolo.h5
然后按照ImageAI的中文官方文档写一个phython程序:
from imageai.Detection import ObjectDetection
import os
execution_path = os.getcwd()
detector = ObjectDetection()
detector.setModelTypeAsYOLOv3()
detector.setModelPath( os.path.join(execution_path , "yolo.h5"))
detector.loadModel()
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , "image2.jpg"), output_image_path=os.path.join(execution_path , "image2new.jpg"), minimum_percentage_probability=30)
for eachObject in detections:
print(eachObject["name"] , " : ", eachObject["percentage_probability"], " : ", eachObject["box_points"] )
print("--------------------------------")
这个程序可以把和phython程序同文件夹的image2.jpg(文件名可以自己改)转化为标记好的mage2new.jpg。(记得把下载的yolo.h5也放在同一个文件夹里)
卖家秀如图:
实际测试这个模型的识别精度挺高的,美中不足就是模型是预设好的,只能识别一些预设的目标,例如车、人、购物袋等等。
更新:ImageAI也支持视频识别,具体见ImageAI的中文官方文档。