{"action":"created","issue":{"url":"https://api.github.com/repos/memo/ofxMSATensorFlow/issues/34","repository_url":"https://api.github.com/repos/memo/ofxMSATensorFlow","labels_url":"https://api.github.com/repos/memo/ofxMSATensorFlow/issues/34/labels{/name}","comments_url":"https://api.github.com/repos/memo/ofxMSATensorFlow/issues/34/comments","events_url":"https://api.github.com/repos/memo/ofxMSATensorFlow/issues/34/events","html_url":"https://github.com/memo/ofxMSATensorFlow/issues/34","id":278749480,"number":34,"title":"Run ssd w/ mobilenet using tensorflow C++ API is slower than tensorflow python API","user":{"login":"kikirizki","id":7989381,"avatar_url":"https://avatars1.githubusercontent.com/u/7989381?v=4","gravatar_id":"","url":"https://api.github.com/users/kikirizki","html_url":"https://github.com/kikirizki","followers_url":"https://api.github.com/users/kikirizki/followers","following_url":"https://api.github.com/users/kikirizki/following{/other_user}","gists_url":"https://api.github.com/users/kikirizki/gists{/gist_id}","starred_url":"https://api.github.com/users/kikirizki/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/kikirizki/subscriptions","organizations_url":"https://api.github.com/users/kikirizki/orgs","repos_url":"https://api.github.com/users/kikirizki/repos","events_url":"https://api.github.com/users/kikirizki/events{/privacy}","received_events_url":"https://api.github.com/users/kikirizki/received_events","type":"User","site_admin":false},"labels":[],"state":"closed","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":7,"created_at":"2017-12-03T06:32:18Z","updated_at":"2018-03-22T10:50:18Z","closed_at":"2017-12-04T03:43:46Z","author_association":"NONE","body":"Recently I try to run ssd with mobilenet model from [tensorflow object detection api](https://github.com/tensorflow/models/tree/master/research/object_detection). I try to run realtime object detection using tensorflow+opencv on both python and c++, surprisingly the c++ is much slower than the python API. I am sure that I run both of them with GPU support, here is my code \r\n```\r\n/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.\r\n\r\nLicensed under the Apache License, Version 2.0 (the \"License\");\r\nyou may not use this file except in compliance with the License.\r\nYou may obtain a copy of the License at\r\n\r\n    http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nUnless required by applicable law or agreed to in writing, software\r\ndistributed under the License is distributed on an \"AS IS\" BASIS,\r\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\nSee the License for the specific language governing permissions and\r\nlimitations under the License.\r\n==============================================================================*/\r\n\r\n// A minimal but useful C++ example showing how to load an Imagenet-style object\r\n// recognition TensorFlow model, prepare input images for it, run them through\r\n// the graph, and interpret the results.\r\n//\r\n// It's designed to have as few dependencies and be as clear as possible, so\r\n// it's more verbose than it could be in production code. In particular, using\r\n// auto for the types of a lot of the returned values from TensorFlow calls can\r\n// remove a lot of boilerplate, but I find the explicit types useful in sample\r\n// code to make it simple to look up the classes involved.\r\n//\r\n// To use it, compile and then run in a working directory with the\r\n// learning/brain/tutorials/label_image/data/ folder below it, and you should\r\n// see the top five labels for the example Lena image output. You can then\r\n// customize it to use your own models or images by changing the file names at\r\n// the top of the main() function.\r\n//\r\n// The googlenet_graph.pb file included by default is created from Inception.\r\n//\r\n// Note that, for GIF inputs, to reuse existing code, only single-frame ones\r\n// are supported.\r\n\r\n#include <fstream>\r\n#include <utility>\r\n#include <vector>\r\n#include <iostream>\r\n#include <opencv2/core/mat.hpp>\r\n#include <opencv2/videoio.hpp>\r\n#include <opencv/cv.hpp>\r\n\r\n#include \"tensorflow/cc/ops/const_op.h\"\r\n#include \"tensorflow/cc/ops/image_ops.h\"\r\n#include \"tensorflow/cc/ops/standard_ops.h\"\r\n#include \"tensorflow/core/framework/graph.pb.h\"\r\n#include \"tensorflow/core/framework/tensor.h\"\r\n#include \"tensorflow/core/graph/default_device.h\"\r\n#include \"tensorflow/core/graph/graph_def_builder.h\"\r\n#include \"tensorflow/core/lib/core/errors.h\"\r\n#include \"tensorflow/core/lib/core/stringpiece.h\"\r\n#include \"tensorflow/core/lib/core/threadpool.h\"\r\n#include \"tensorflow/core/lib/io/path.h\"\r\n#include \"tensorflow/core/lib/strings/stringprintf.h\"\r\n#include \"tensorflow/core/platform/env.h\"\r\n#include \"tensorflow/core/platform/init_main.h\"\r\n#include \"tensorflow/core/platform/logging.h\"\r\n#include \"tensorflow/core/platform/types.h\"\r\n#include \"tensorflow/core/public/session.h\"\r\n#include \"tensorflow/core/util/command_line_flags.h\"\r\n\r\n// These are all common classes it's handy to reference with no namespace.\r\nusing tensorflow::Flag;\r\nusing tensorflow::Tensor;\r\nusing tensorflow::Status;\r\nusing tensorflow::string;\r\nusing tensorflow::int32;\r\n\r\nusing namespace std;\r\n\r\n// Takes a file name, and loads a list of labels from it, one per line, and\r\n// returns a vector of the strings. It pads with empty strings so the length\r\n// of the result is a multiple of 16, because our model expects that.\r\nStatus ReadLabelsFile(const string& file_name, std::vector<string>* result,\r\n                      size_t* found_label_count) {\r\n    std::ifstream file(file_name);\r\n    if (!file) {\r\n        return tensorflow::errors::NotFound(\"Labels file \", file_name,\r\n                                            \" not found.\");\r\n    }\r\n    result->clear();\r\n    string line;\r\n    while (std::getline(file, line)) {\r\n        result->push_back(line);\r\n    }\r\n    *found_label_count = result->size();\r\n    const int padding = 16;\r\n    while (result->size() % padding) {\r\n        result->emplace_back();\r\n    }\r\n    return Status::OK();\r\n}\r\n\r\nstatic Status ReadEntireFile(tensorflow::Env* env, const string& filename,\r\n                             Tensor* output) {\r\n    tensorflow::uint64 file_size = 0;\r\n    TF_RETURN_IF_ERROR(env->GetFileSize(filename, &file_size));\r\n\r\n    string contents;\r\n    contents.resize(file_size);\r\n\r\n    std::unique_ptr<tensorflow::RandomAccessFile> file;\r\n    TF_RETURN_IF_ERROR(env->NewRandomAccessFile(filename, &file));\r\n\r\n    tensorflow::StringPiece data;\r\n    TF_RETURN_IF_ERROR(file->Read(0, file_size, &data, &(contents)[0]));\r\n    if (data.size() != file_size) {\r\n        return tensorflow::errors::DataLoss(\"Truncated read of '\", filename,\r\n                                            \"' expected \", file_size, \" got \",\r\n                                            data.size());\r\n    }\r\n    output->scalar<string>()() = data.ToString();\r\n    return Status::OK();\r\n}\r\n\r\n// Given an image file name, read in the data, try to decode it as an image,\r\n// resize it to the requested size, and then scale the values as desired.\r\nStatus ReadTensorFromImageFile(const string& file_name, const int input_height,\r\n                               const int input_width, const float input_mean,\r\n                               const float input_std,\r\n                               std::vector<Tensor>* out_tensors) {\r\n    auto root = tensorflow::Scope::NewRootScope();\r\n    using namespace ::tensorflow::ops;  // NOLINT(build/namespaces)\r\n\r\n    string input_name = \"file_reader\";\r\n    string output_name = \"normalized\";\r\n\r\n    // read file_name into a tensor named input\r\n    Tensor input(tensorflow::DT_STRING, tensorflow::TensorShape());\r\n    TF_RETURN_IF_ERROR(\r\n            ReadEntireFile(tensorflow::Env::Default(), file_name, &input));\r\n\r\n    // use a placeholder to read input data\r\n    auto file_reader =\r\n            Placeholder(root.WithOpName(\"input\"), tensorflow::DataType::DT_STRING);\r\n\r\n    std::vector<std::pair<string, tensorflow::Tensor>> inputs = {\r\n            {\"input\", input},\r\n    };\r\n\r\n    // Now try to figure out what kind of file it is and decode it.\r\n    const int wanted_channels = 3;\r\n    tensorflow::Output image_reader;\r\n    if (tensorflow::StringPiece(file_name).ends_with(\".png\")) {\r\n        image_reader = DecodePng(root.WithOpName(\"png_reader\"), file_reader,\r\n                                 DecodePng::Channels(wanted_channels));\r\n    } else if (tensorflow::StringPiece(file_name).ends_with(\".gif\")) {\r\n        // gif decoder returns 4-D tensor, remove the first dim\r\n        image_reader =\r\n                Squeeze(root.WithOpName(\"squeeze_first_dim\"),\r\n                        DecodeGif(root.WithOpName(\"gif_reader\"), file_reader));\r\n    } else {\r\n        // Assume if it's neither a PNG nor a GIF then it must be a JPEG.\r\n        image_reader = DecodeJpeg(root.WithOpName(\"jpeg_reader\"), file_reader,\r\n                                  DecodeJpeg::Channels(wanted_channels));\r\n    }\r\n    // Now cast the image data to float so we can do normal math on it.\r\n    // auto float_caster =\r\n    //     Cast(root.WithOpName(\"float_caster\"), image_reader, tensorflow::DT_FLOAT);\r\n\r\n    auto uint8_caster =  Cast(root.WithOpName(\"uint8_caster\"), image_reader, tensorflow::DT_UINT8);\r\n\r\n    // The convention for image ops in TensorFlow is that all images are expected\r\n    // to be in batches, so that they're four-dimensional arrays with indices of\r\n    // [batch, height, width, channel]. Because we only have a single image, we\r\n    // have to add a batch dimension of 1 to the start with ExpandDims().\r\n    auto dims_expander = ExpandDims(root.WithOpName(\"dim\"), uint8_caster, 0);\r\n\r\n    // Bilinearly resize the image to fit the required dimensions.\r\n    // auto resized = ResizeBilinear(\r\n    //     root, dims_expander,\r\n    //     Const(root.WithOpName(\"size\"), {input_height, input_width}));\r\n\r\n\r\n    // Subtract the mean and divide by the scale.\r\n    // auto div =  Div(root.WithOpName(output_name), Sub(root, dims_expander, {input_mean}),\r\n    //     {input_std});\r\n\r\n\r\n    //cast to int\r\n    //auto uint8_caster =  Cast(root.WithOpName(\"uint8_caster\"), div, tensorflow::DT_UINT8);\r\n\r\n    // This runs the GraphDef network definition that we've just constructed, and\r\n    // returns the results in the output tensor.\r\n    tensorflow::GraphDef graph;\r\n    TF_RETURN_IF_ERROR(root.ToGraphDef(&graph));\r\n\r\n    std::unique_ptr<tensorflow::Session> session(\r\n            tensorflow::NewSession(tensorflow::SessionOptions()));\r\n    TF_RETURN_IF_ERROR(session->Create(graph));\r\n    TF_RETURN_IF_ERROR(session->Run({inputs}, {\"dim\"}, {}, out_tensors));\r\n    return Status::OK();\r\n}\r\n\r\n// Reads a model graph definition from disk, and creates a session object you\r\n// can use to run it.\r\nStatus LoadGraph(const string& graph_file_name,\r\n                 std::unique_ptr<tensorflow::Session>* session) {\r\n    tensorflow::GraphDef graph_def;\r\n    Status load_graph_status =\r\n            ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def);\r\n    if (!load_graph_status.ok()) {\r\n        return tensorflow::errors::NotFound(\"Failed to load compute graph at '\",\r\n                                            graph_file_name, \"'\");\r\n    }\r\n    session->reset(tensorflow::NewSession(tensorflow::SessionOptions()));\r\n    Status session_create_status = (*session)->Create(graph_def);\r\n    if (!session_create_status.ok()) {\r\n        return session_create_status;\r\n    }\r\n    return Status::OK();\r\n}\r\n\r\n\r\n\r\nint main(int argc, char* argv[]) {\r\n    // These are the command-line flags the program can understand.\r\n    // They define where the graph and input data is located, and what kind of\r\n    // input the model expects. If you train your own model, or use something\r\n    // other than inception_v3, then you'll need to update these.\r\n    string image(argv[1]);\r\n    string graph =\"ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb\";\r\n    string labels =\"mscoco_label_map.pbtxt\";\r\n    int32 input_width = 299;\r\n    int32 input_height = 299;\r\n    int32 depth =3;\r\n    float input_mean = 0;\r\n    float input_std = 255;\r\n    string input_layer = \"image_tensor:0\";\r\n    vector<string> output_layer ={ \"detection_boxes:0\", \"detection_scores:0\", \"detection_classes:0\", \"num_detections:0\" };\r\n\r\n    bool self_test = false;\r\n    string root_dir = \"\";\r\n  //============================================//\r\n    cv::VideoCapture cap(0);\r\n    // creating a Tensor for storing the data\r\n    tensorflow::Tensor input_tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape({1,input_height,input_width,depth}));\r\n    auto input_tensor_mapped = input_tensor.tensor<float, 4>();\r\n    cv::Mat img_stream;\r\n    const float * source_data;\r\n    // copying the data into the corresponding tensor\r\n    cv::namedWindow(\"camera\");\r\n    cv::Size s(input_height,input_width);\r\n    cv::Mat resized_img;\r\n    cv::Mat resized_i;\r\n    std::unique_ptr<tensorflow::Session> session;\r\n    string graph_path = tensorflow::io::JoinPath(root_dir, graph);\r\n    std::vector<Tensor> resized_tensors;\r\n    string image_path = tensorflow::io::JoinPath(root_dir, image);\r\n    Status read_tensor_status;\r\n    std::vector<Tensor> outputs;\r\n    int image_width;\r\n    int image_height;\r\n\r\n    // First we load and initialize the model.\r\n    LoadGraph(graph_path, &session);\r\n    ReadTensorFromImageFile(image_path, input_height, input_width, input_mean,\r\n                            input_std, &resized_tensors);\r\n\r\n    for(;;) {\r\n        cap>>img_stream;\r\n//        cv::resize(img_stream,resized_i,s,0,0,cv::INTER_CUBIC);\r\n//        resized_i.convertTo(resized_img, CV_32FC1);\r\n//        source_data = (float*) resized_img.data;\r\n//        for (int y = 0; y < input_height; ++y) {\r\n//            const float *source_row = source_data + (y * input_width * depth);\r\n//            for (int x = 0; x < input_width; ++x) {\r\n//                const float *source_pixel = source_row + (x * depth);\r\n//                for (int c = 0; c < depth; ++c) {\r\n//                    const float *source_value = source_pixel + c;\r\n//                    input_tensor_mapped(0, y, x, c) = *source_value;\r\n//                }\r\n//            }\r\n//        }\r\n        //============================================//\r\n        const Tensor& resized_tensor = resized_tensors[0];\r\n        // << \",data:\" << resized_tensor.flat<tensorflow::uint8>();\r\n        // Actually run the image through the model.\r\n\r\n        session->Run({{input_layer, resized_tensor}},\r\n                                         output_layer, {}, &outputs);\r\n        image_width = resized_tensor.dims();\r\n        image_height = 0;\r\n        //int image_height = resized_tensor.shape()[1];\r\n        //tensorflow::TTypes<float>::Flat iNum = outputs[0].flat<float>();\r\n        tensorflow::TTypes<float>::Flat scores = outputs[1].flat<float>();\r\n        tensorflow::TTypes<float>::Flat classes = outputs[2].flat<float>();\r\n        tensorflow::TTypes<float>::Flat num_detections = outputs[3].flat<float>();\r\n        auto boxes = outputs[0].flat_outer_dims<float,3>();\r\n//        LOG(ERROR) << \"num_detections:\" << num_detections(0) << \",\" << outputs[0].shape().DebugString();\r\n        for(size_t i = 0; i < num_detections(0) && i < 20;++i)\r\n        {\r\n            if(scores(i) > 0.5)\r\n            {\r\n                cout<< i << \",score:\" << scores(i) << \",class:\" << classes(i)<< \",box:\" << \",\" << boxes(0,i,0) << \",\" << boxes(0,i,1) << \",\" << boxes(0,i,2)<< \",\" << boxes(0,i,3);\r\n            }\r\n        }\r\n        cv::imshow(\"camera\",img_stream);\r\n        if (cv::waitKey(33) == 27)\r\n            break;\r\n    }\r\n\r\n\r\n    return 0;\r\n}\r\n```\r\n\r\nNote : Since I do not know how to convert cv::Mat into tensor, I do not actually detect the object from the camera for each frame instead I substitute the cv::Mat with image from image file (\"cat.jpg\"). My intention is to compare the performance between tensorflow C++ and python API for object detection w mobilenet..\r\nthanks, \r\n\r\noke then why the C++ API is slower?\r\nthanks"},"comment":{"url":"https://api.github.com/repos/memo/ofxMSATensorFlow/issues/comments/375261080","html_url":"https://github.com/memo/ofxMSATensorFlow/issues/34#issuecomment-375261080","issue_url":"https://api.github.com/repos/memo/ofxMSATensorFlow/issues/34","id":375261080,"user":{"login":"kerolos","id":3300016,"avatar_url":"https://avatars0.githubusercontent.com/u/3300016?v=4","gravatar_id":"","url":"https://api.github.com/users/kerolos","html_url":"https://github.com/kerolos","followers_url":"https://api.github.com/users/kerolos/followers","following_url":"https://api.github.com/users/kerolos/following{/other_user}","gists_url":"https://api.github.com/users/kerolos/gists{/gist_id}","starred_url":"https://api.github.com/users/kerolos/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/kerolos/subscriptions","organizations_url":"https://api.github.com/users/kerolos/orgs","repos_url":"https://api.github.com/users/kerolos/repos","events_url":"https://api.github.com/users/kerolos/events{/privacy}","received_events_url":"https://api.github.com/users/kerolos/received_events","type":"User","site_admin":false},"created_at":"2018-03-22T10:50:18Z","updated_at":"2018-03-22T10:50:18Z","author_association":"NONE","body":"thanks a lot @kikirizki for your reply and help :) . "}}
{"actor":{"display_login":"kerolos"}}