【问题标题】:How to use the pretrained .caffemodel to perform prediction on single image on python如何使用预训练的 .caffemodel 在 python 上对单个图像执行预测
【发布时间】:2020-11-29 18:20:40
【问题描述】:

如何使用经过训练的网络架构的预训练 .caffemodel(已从数据集页面安装)和 .prototxt 文件来预测单个图像(性别分类)?

【问题讨论】:

    标签: python-3.x classification conv-neural-network caffe


    【解决方案1】:

    Caffe 模型可以在 OpenCV 中运行。此外,您不必在您的环境中安装 Caffe。

    模型加载

    import cv2
    model = cv2.dnn.readNetFromCaffe("x.prototxt", "y.caffemodel")
    

    调整输入大小

    您需要将输入图像的大小调整为参考模型的预期输入大小。这在 prototxt 文件中有所提及。例如,以下模型需要 (1, 3, 160, 160) 形状的输入。

    input: "data"
    input_dim: 1
    input_dim: 3
    input_dim: 160
    input_dim: 160
    

    您可以读取图像并调整其大小,如下所示。

    img = cv2.imread("img.jpg")
    img = cv2.resize(img , (160, 160)) #this is (160, 160, 3) shaped image
    img_blob = cv2.dnn.blobFromImage(img ) #this is (1, 3, 160, 160) shaped image
    

    预测

    您现在可以将调整大小的图像传递给构建的模型。

    model.setInput(img_blob)
    output = model.forward()
    print(output)
    

    即使您的环境中未安装 Caffe,此功能也有效。 OpenCV 也封装了 torch 和 tensorflow 模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 2018-12-15
      • 1970-01-01
      • 2019-12-30
      • 2019-02-22
      • 2021-08-14
      • 1970-01-01
      相关资源
      最近更新 更多