122 OpenCV DNN 实现图像分类
代码
import cv2 as cv
import numpy as np
bin_model = "../models/googlenet/bvlc_googlenet.caffemodel"
protxt = "../models/googlenet/bvlc_googlenet.prototxt"
# Load names of classes
classes = None
with open("classification_classes_ILSVRC2012.txt", 'rt') as f:
classes = f.read().rstrip('\n').split('\n')
# load CNN model
net = cv.dnn.readNetFromCaffe(protxt, bin_model)
# read input data
image = cv.imread("../images/vehicle_test.jpg")
blob = cv.dnn.blobFromImage(image, 1.0, (224, 224), (104, 117,123), False, crop=False)
result = np.copy(image)
cv.imshow("input", image)
# Run a model
net.setInput(blob)
out = net.forward()
# Get a class with a highest score.
out = out.flatten()
classId = np.argmax(out)
confidence = out[classId]
# Put efficiency information.
t, _ = net.getPerfProfile()
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
cv.putText(result, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0))
# Print predicted class.
label = '%s: %.4f' % (classes[classId] if classes else 'Class #%d' % classId, confidence)
cv.putText(result, label, (50, 50), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)
cv.imshow("googlenet-demo", result)
cv.waitKey(0)
cv.destroyAllWindows()
实验结果
解释
使用ImageNet数据集支持1000分类的GoogleNet网络模型, 分别演示了Python与C++语言中的使用该模型实现图像分类标签预测。其中label标签是在一个单独的文本文件中读取,模型从上面的链接中下载即可。读取模型的API:
retval = cv.dnn.readNetFromCaffe(prototxt[, caffeModel])
prototxt
表示模型的配置文件caffeModel
表示模型的权重二进制文件
使用模型实现预测的时候,需要读取图像作为输入,网络模型支持的输入数据是四维的输入,所以要把读取到的Mat对象转换为四维张量,OpenCV的提供的API为如下:
retval = cv.dnn.blobFromImage(image[, scalefactor[, size[, mean[, swapRB[, crop[, ddepth]]]]]])
image
输入图像scalefactor
默认1.0size
表示网络接受的数据大小mean
表示训练时数据集的均值,从通道中减去平均值的标量。如果图像具有BGR排序并且swapRB为true,则值应按(平均值R,平均值G,平均值B)顺序排列。swapRB
是否互换Red与Blur通道crop
剪切ddepth
数据类型
所有内容均来源于贾志刚老师的知识星球——OpenCV研习社,本文为个人整理学习,已获得贾老师授权,有兴趣、有能力的可以加入贾老师的知识星球进行深入学习。