图像分类现如今已经使用在各个领域,如ImageNet中花类识别。现PaddleHub已将定制打造的动物识别模型resnet50_vd_animals和mobilenet_v2_animals开源,并且支持一键完成动物识别,适用于拍照识图类APP中。
以下列图片为待预测图片。
1.jpg为
2.jpg为
3.jpg为
4.jpg为
5.jpg为
其中,若是待预测图片放在一个文件中,如右侧所示文件夹下的图片,test.txt为图片名及后缀,每一行是待预测图片的存放路径,具体如下:
以下是使用PaddleHub进行一键动物识别,所以第一步就是安装paddlehub,这里安装的是paddlehub==1.6.0
#使用清华镜像进行快速安装, https://pypi.tuna.tsinghua.edu.cn/simple下面是有下划线的。
!pip install paddlehub==1.6.0 -i https://pypi.tuna.tsinghua.edu.cn/simple
# 读入待预测图片
test_img_path = ["./1.jpg", "./2.jpg", "./3.jpg", "./4.jpg", "./5.jpg"]
#导入画图模块,matplotlib.pyplot作为plt,导入matplotlib中的image模块作为mpimg
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# 使用matplotlib中的mpimg读待预测图片,这里展示图片1.jpg,即其中大熊猫图片
img1 = mpimg.imread(test_img_path[0])
#对图片进行重新设置大小,并展示
plt.figure(figsize=(10,10))
plt.imshow(img1)
plt.axis('off')
plt.show()
读文件夹下的待预测图片的路径,即上述的test.txt
!cat test.txt
用户想要利用动物识别模型识别动物,只需读入该文件,将文件内容存成list,list中的每个元素是待预测图片的存放路径
#读入刚刚的待预测文件夹下的图片的路径,即test.txt,进行元素转换成list
with open('test.txt', 'r') as f:
test_img_path=[]
for line in f:
test_img_path.append(line.strip())
print(test_img_path)
PaddleHub提供了两种动物识别模型:
resnet50_vd_animals:ResNet-vd其实就是ResNet-D,是ResNet原始结构的变种,可用于图像分类和特征提取。该PaddleHub Module采用百度自创动物数据集训练得到,支持7978种动物的分类识别。
mobilenet_v2_animals:MobileNet V2是一个轻量化的卷积神经网络,它在MobileNet的基础上,做了Inverted Residuals和Linear bottlenecks这两大改进。该 PaddleHub Module 是在百度自建动物数据集上训练得到的,可用于图像分类和特征提取,当前已支持7978种动物的分类识别。
#读入paddlehub,并读取相应的预训练模型。这里读取的是resnet50_vd_animals模型
import paddlehub as hub
module = hub.Module(name="resnet50_vd_animals")
# module = hub.Module(name="mobilenet_v2_animals")
三、预测
PaddleHub对于支持一键预测的module,可以调用module的相应预测API,完成预测功能。
import cv2
np_images =[cv2.imread(image_path) for image_path in test_img_path]
results = module.classification(images=np_images)
for result in results:
print(result)
以下是动物识别的结果
#这里使用的模型是mobilenet_v2_animals
import paddlehub as hub
module = hub.Module(name="mobilenet_v2_animals")
import cv2
np_images =[cv2.imread(image_path) for image_path in test_img_path]
results = module.classification(images=np_images)
for result in results:
print(result)
结果如下