caffe使用训练好的模型识别代码

  • 54行可改图像均值
  • 81行可改图像放缩
  • 109行为识别阈值
#include <caffe/caffe.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <string>

using namespace caffe;
// using namespace std;

std::string CLASSES[81] = { "__background__",
"person", "bicycle", "car", "motorcycle",
"airplane", "bus", "train", "truck", "boat",
"traffic light", "fire hydrant", "stop sign", "parking meter",
"bench", "bird", "cat",
"dog", "horse", "sheep", "cow",
"elephant", "bear", "zebra", "giraffe" ,
"backpack", "umbrella", "handbag", "tie" ,
"suitcase", "frisbee", "skis", "snowboard" ,
"sports ball", "kite", "baseball bat", "baseball glove" ,
"skateboard", "surfboard", "tennis racket", "bottle" ,
"wine glass", "cup", "fork", "knife" ,
"spoon", "bowl", "banana", "apple" ,
"sandwich", "orange", "broccoli", "carrot" ,
"hot dog", "pizza", "donut", "cake" ,
"chair", "couch", "potted plant", "bed" ,
"dining table", "toilet", "tv", "laptop" ,
"mouse", "remote", "keyboard", "cell phone" ,
"microwave", "oven", "toaster", "sink" ,
"refrigerator", "book", "clock", "vase" ,
"scissors", "teddy bear", "hair drier", "toothbrush" ,
};

int main()
{
    std::string model_file("/home/lwd/code/dl/MobileNet-YOLO/models/darknet_yolov3/yolov3.prototxt");
    std::string weights_file("/home/lwd/code/dl/MobileNet-YOLO/models/darknet_yolov3/zhang.caffemodel");
    cv::Mat mean_;
    cv::Mat img = cv::imread("/home/lwd/code/dl/ssd/ssddetect/ssd_network_config/mobilenetssd/test0.jpg");

    // set net
    Caffe::set_mode(Caffe::GPU);
    shared_ptr<Net<float>> net_;
    net_.reset(new Net<float>(model_file, TEST));
    net_->CopyTrainedLayersFrom(weights_file);
    CHECK_EQ(net_->num_inputs(), 1) << "Network should have exactly one input.";
    CHECK_EQ(net_->num_outputs(), 1) << "Network should have exactly one output.";
    Blob<float> *input_layer = net_->input_blobs()[0];
    int num_channels_ = input_layer->channels();
    CHECK(num_channels_ == 3 || num_channels_ == 1) << "Input layer should have 1 or 3 channels.";
    cv::Size input_geometry_ = cv::Size(input_layer->width(), input_layer->height());
    std::vector<cv::Mat> channels;
    for (int i = 0; i < num_channels_; ++i)
    {
        cv::Mat channel(input_geometry_.height, input_geometry_.width, CV_32FC1, 0.0);
        channels.push_back(channel);
    }
    cv::merge(channels, mean_);
    //
    input_layer->Reshape(1, num_channels_, input_geometry_.height, input_geometry_.width);
    net_->Reshape();
    // input shape
    std::vector<cv::Mat> input_channels;
    int width = input_layer->width();
    int height = input_layer->height();
    float *input_data = input_layer->mutable_cpu_data();
    for (int i = 0; i < input_layer->channels(); ++i)
    {
        cv::Mat channel(height, width, CV_32FC1, input_data);
        input_channels.push_back(channel);
        input_data += width * height;
    }
    // input data
    cv::Mat sample = img;
    cv::Mat sample_resized;
    if (sample.size() != input_geometry_)
        cv::resize(sample, sample_resized, input_geometry_);
    else
        sample_resized = sample;
    cv::Mat sample_float;
    if (num_channels_ == 3)
        sample_resized.convertTo(sample_float, CV_32FC3, 0.0039215);
    else
        sample_resized.convertTo(sample_float, CV_32FC1, 0.0039215);
    cv::Mat sample_normalized;
    cv::subtract(sample_float, mean_, sample_normalized);
    cv::split(sample_normalized, input_channels);
    net_->Forward();
    Blob<float> *result_blob = net_->output_blobs()[0];
    const float *result = result_blob->cpu_data();
    const int num_det = result_blob->height();
    std::vector<std::vector<float>> detections;
    for (int k = 0; k < num_det; ++k)
    {
        if (result[0] == -1)
        {
            result += 7;
            continue;
        }
        std::vector<float> detection(result, result + 7);
        detections.push_back(detection);
        result += 7;
    }
    for (int i = 0; i < detections.size(); ++i)
    {
        const std::vector<float> &d = detections[i];
        // Detection format: [image_id, label, score, xmin, ymin, xmax, ymax].
        CHECK_EQ(d.size(), 7);
        const float score = d[2];
        if (score >= 0.61)
        {
            cv::Point pt1, pt2;
            pt1.x = (img.cols * d[3]);
            pt1.y = (img.rows * d[4]);
            pt2.x = (img.cols * d[5]);
            pt2.y = (img.rows * d[6]);
            cv::rectangle(img, pt1, pt2, cv::Scalar(0, 255, 0), 1, 8, 0);
            char label[100];
            sprintf(label, "%s,%f", CLASSES[static_cast<int>(d[1])].c_str(), score);
            int baseline;
            cv::Size size = cv::getTextSize(label, cv::FONT_HERSHEY_SIMPLEX, 0.5, 0, &baseline);
            cv::Point pt3;
            pt3.x = pt1.x + size.width;
            pt3.y = pt1.y - size.height;
            cv::rectangle(img, pt1, pt3, cv::Scalar(0, 255, 0), -1);
            cv::putText(img, label, pt1, cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0, 0, 0));
        }
    }
    cv::imshow("show", img);
    cv::waitKey();
    return 0;
}

  • CMakeLists.txt
  • 需要把libcaffe.so.1.0.0、caffe/build/include/caffe/proto和caffe/include/caffe拷贝过来
cmake_minimum_required(VERSION 2.8.3)
project(cpp)

add_compile_options(-std=c++14 -g)

find_package(OpenCV REQUIRED)
find_package(Boost REQUIRED COMPONENTS
  filesystem
)

include_directories(
  include
  /usr/local/cuda/include
  ${OpenCV_INCLUDE_DIRS}
  ${Boost_INCLUDE_DIRS}
)

link_directories(
	${OpenCV_LIBRARY_DIRS}
)

add_executable(mnist main.cc)
target_link_libraries(mnist
  ${OpenCV_LIBRARIES}
  ${Boost_LIBRARIES}
  ${PROJECT_SOURCE_DIR}/libcaffe.so.1.0.0
  glog
)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刀么克瑟拉莫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值