-
Notifications
You must be signed in to change notification settings - Fork 45.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
C++ example to run object detection models #1741
Comments
Sounds like a reasonable request to me. Adding @jch1 @derekjchow for visibility. Also marking as "contributions welcome", since someone from the community could help with this. |
I tried to modify the image_label C++ code to run the detection. |
Yes, I also found that there were no equivalent tensorflow C++ APIs to do the same as Python APIs as below:
|
I ported the object detection example over to C# using TensorFlowSharp https://github.com/migueldeicaza/TensorFlowSharp. Using the C++ API directly should be similar.
|
I am also trying to modify the examples/label_image main.cc to export the trained model to C++. It seems the expected input type is uint8 (exact error: Running model failed: Invalid argument: Expects arg[0] to be uint8 but float is provided) . In the function ReadTensorFromImageFile() , I change the casting datatype to uint8, auto float_caster = Cast(root.WithOpName("uint8_caster"), image_reader, tensorflow::DataType::DT_UINT8); but still the tensor returned is of type float? Is this a casting issue? As, this https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/ops/math_ops.cc says casting is supported for only few datatypes, is uint8 not supported? Am I looking at the right place for Cast() operator? Any tips to convert C++ tensor to uint8? |
The uint8 happened because ResizeBillinear() converts the tensor back into float. We can get uint8 tensor by using Cast() at the end ,i.e. after scaling and normalizing. The C++ detection is running fine for me after this. |
Would you mind sharing the code? |
here is my code,I"d like to share it. I edit it from label_image.cc /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// A minimal but useful C++ example showing how to load an Imagenet-style object
// recognition TensorFlow model, prepare input images for it, run them through
// the graph, and interpret the results.
//
// It"s designed to have as few dependencies and be as clear as possible, so
// it"s more verbose than it could be in production code. In particular, using
// auto for the types of a lot of the returned values from TensorFlow calls can
// remove a lot of boilerplate, but I find the explicit types useful in sample
// code to make it simple to look up the classes involved.
//
// To use it, compile and then run in a working directory with the
// learning/brain/tutorials/label_image/data/ folder below it, and you should
// see the top five labels for the example Lena image output. You can then
// customize it to use your own models or images by changing the file names at
// the top of the main() function.
//
// The googlenet_graph.pb file included by default is created from Inception.
//
// Note that, for GIF inputs, to reuse existing code, only single-frame ones
// are supported.
#include <fstream>
#include <utility>
#include <vector>
#include <iostream>
#include "tensorflow/cc/ops/const_op.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/graph/default_device.h"
#include "tensorflow/core/graph/graph_def_builder.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/util/command_line_flags.h"
// These are all common classes it"s handy to reference with no namespace.
using tensorflow::Flag;
using tensorflow::Tensor;
using tensorflow::Status;
using tensorflow::string;
using tensorflow::int32;
using namespace std;
// Takes a file name, and loads a list of labels from it, one per line, and
// returns a vector of the strings. It pads with empty strings so the length
// of the result is a multiple of 16, because our model expects that.
Status ReadLabelsFile(const string& file_name, std::vector<string>* result,
size_t* found_label_count) {
std::ifstream file(file_name);
if (!file) {
return tensorflow::errors::NotFound("Labels file ", file_name,
" not found.");
}
result->clear();
string line;
while (std::getline(file, line)) {
result->push_back(line);
}
*found_label_count = result->size();
const int padding = 16;
while (result->size() % padding) {
result->emplace_back();
}
return Status::OK();
}
static Status ReadEntireFile(tensorflow::Env* env, const string& filename,
Tensor* output) {
tensorflow::uint64 file_size = 0;
TF_RETURN_IF_ERROR(env->GetFileSize(filename, &file_size));
string contents;
contents.resize(file_size);
std::unique_ptr<tensorflow::RandomAccessFile> file;
TF_RETURN_IF_ERROR(env->NewRandomAccessFile(filename, &file));
tensorflow::StringPiece data;
TF_RETURN_IF_ERROR(file->Read(0, file_size, &data, &(contents)[0]));
if (data.size() != file_size) {
return tensorflow::errors::DataLoss("Truncated read of "", filename,
"" expected ", file_size, " got ",
data.size());
}
output->scalar<string>()() = data.ToString();
return Status::OK();
}
// Given an image file name, read in the data, try to decode it as an image,
// resize it to the requested size, and then scale the values as desired.
Status ReadTensorFromImageFile(const string& file_name, const int input_height,
const int input_width, const float input_mean,
const float input_std,
std::vector<Tensor>* out_tensors) {
auto root = tensorflow::Scope::NewRootScope();
using namespace ::tensorflow::ops; // NOLINT(build/namespaces)
string input_name = "file_reader";
string output_name = "normalized";
// read file_name into a tensor named input
Tensor input(tensorflow::DT_STRING, tensorflow::TensorShape());
TF_RETURN_IF_ERROR(
ReadEntireFile(tensorflow::Env::Default(), file_name, &input));
// use a placeholder to read input data
auto file_reader =
Placeholder(root.WithOpName("input"), tensorflow::DataType::DT_STRING);
std::vector<std::pair<string, tensorflow::Tensor>> inputs = {
{"input", input},
};
// Now try to figure out what kind of file it is and decode it.
const int wanted_channels = 3;
tensorflow::Output image_reader;
if (tensorflow::StringPiece(file_name).ends_with(".png")) {
image_reader = DecodePng(root.WithOpName("png_reader"), file_reader,
DecodePng::Channels(wanted_channels));
} else if (tensorflow::StringPiece(file_name).ends_with(".gif")) {
// gif decoder returns 4-D tensor, remove the first dim
image_reader =
Squeeze(root.WithOpName("squeeze_first_dim"),
DecodeGif(root.WithOpName("gif_reader"), file_reader));
} else {
// Assume if it"s neither a PNG nor a GIF then it must be a JPEG.
image_reader = DecodeJpeg(root.WithOpName("jpeg_reader"), file_reader,
DecodeJpeg::Channels(wanted_channels));
}
// Now cast the image data to float so we can do normal math on it.
// auto float_caster =
// Cast(root.WithOpName("float_caster"), image_reader, tensorflow::DT_FLOAT);
auto uint8_caster = Cast(root.WithOpName("uint8_caster"), image_reader, tensorflow::DT_UINT8);
// The convention for image ops in TensorFlow is that all images are expected
// to be in batches, so that they"re four-dimensional arrays with indices of
// [batch, height, width, channel]. Because we only have a single image, we
// have to add a batch dimension of 1 to the start with ExpandDims().
auto dims_expander = ExpandDims(root.WithOpName("dim"), uint8_caster, 0);
// Bilinearly resize the image to fit the required dimensions.
// auto resized = ResizeBilinear(
// root, dims_expander,
// Const(root.WithOpName("size"), {input_height, input_width}));
// Subtract the mean and divide by the scale.
// auto div = Div(root.WithOpName(output_name), Sub(root, dims_expander, {input_mean}),
// {input_std});
//cast to int
//auto uint8_caster = Cast(root.WithOpName("uint8_caster"), div, tensorflow::DT_UINT8);
// This runs the GraphDef network definition that we"ve just constructed, and
// returns the results in the output tensor.
tensorflow::GraphDef graph;
TF_RETURN_IF_ERROR(root.ToGraphDef(&graph));
std::unique_ptr<tensorflow::Session> session(
tensorflow::NewSession(tensorflow::SessionOptions()));
TF_RETURN_IF_ERROR(session->Create(graph));
TF_RETURN_IF_ERROR(session->Run({inputs}, {"dim"}, {}, out_tensors));
return Status::OK();
}
// Reads a model graph definition from disk, and creates a session object you
// can use to run it.
Status LoadGraph(const string& graph_file_name,
std::unique_ptr<tensorflow::Session>* session) {
tensorflow::GraphDef graph_def;
Status load_graph_status =
ReadBinaryProto(tensorflow::Env::Default(), graph_file_name, &graph_def);
if (!load_graph_status.ok()) {
return tensorflow::errors::NotFound("Failed to load compute graph at "",
graph_file_name, """);
}
session->reset(tensorflow::NewSession(tensorflow::SessionOptions()));
Status session_create_status = (*session)->Create(graph_def);
if (!session_create_status.ok()) {
return session_create_status;
}
return Status::OK();
}
int main(int argc, char* argv[]) {
// These are the command-line flags the program can understand.
// They define where the graph and input data is located, and what kind of
// input the model expects. If you train your own model, or use something
// other than inception_v3, then you"ll need to update these.
string image(argv[1]);
string graph ="faster_rcnn_resnet101_coco_11_06_2017/frozen_inference_graph.pb";
string labels ="labels/mscoco_label_map.pbtxt";
int32 input_width = 299;
int32 input_height = 299;
float input_mean = 0;
float input_std = 255;
string input_layer = "image_tensor:0";
vector<string> output_layer ={ "detection_boxes:0", "detection_scores:0", "detection_classes:0", "num_detections:0" };
bool self_test = false;
string root_dir = "";
// First we load and initialize the model.
std::unique_ptr<tensorflow::Session> session;
string graph_path = tensorflow::io::JoinPath(root_dir, graph);
LOG(ERROR) << "graph_path:" << graph_path;
Status load_graph_status = LoadGraph(graph_path, &session);
if (!load_graph_status.ok()) {
LOG(ERROR) << "LoadGraph ERROR!!!!"<< load_graph_status;
return -1;
}
// Get the image from disk as a float array of numbers, resized and normalized
// to the specifications the main graph expects.
std::vector<Tensor> resized_tensors;
string image_path = tensorflow::io::JoinPath(root_dir, image);
Status read_tensor_status =
ReadTensorFromImageFile(image_path, input_height, input_width, input_mean,
input_std, &resized_tensors);
if (!read_tensor_status.ok()) {
LOG(ERROR) << read_tensor_status;
return -1;
}
const Tensor& resized_tensor = resized_tensors[0];
LOG(ERROR) <<"image shape:" << resized_tensor.shape().DebugString()<< ",len:" << resized_tensors.size() << ",tensor type:"<< resized_tensor.dtype();
// << ",data:" << resized_tensor.flat<tensorflow::uint8>();
// Actually run the image through the model.
std::vector<Tensor> outputs;
Status run_status = session->Run({{input_layer, resized_tensor}},
output_layer, {}, &outputs);
if (!run_status.ok()) {
LOG(ERROR) << "Running model failed: " << run_status;
return -1;
}
int image_width = resized_tensor.dims();
int image_height = 0;
//int image_height = resized_tensor.shape()[1];
LOG(ERROR) << "size:" << outputs.size() << ",image_width:" << image_width << ",image_height:" << image_height << endl;
//tensorflow::TTypes<float>::Flat iNum = outputs[0].flat<float>();
tensorflow::TTypes<float>::Flat scores = outputs[1].flat<float>();
tensorflow::TTypes<float>::Flat classes = outputs[2].flat<float>();
tensorflow::TTypes<float>::Flat num_detections = outputs[3].flat<float>();
auto boxes = outputs[0].flat_outer_dims<float,3>();
LOG(ERROR) << "num_detections:" << num_detections(0) << "," << outputs[0].shape().DebugString();
for(size_t i = 0; i < num_detections(0) && i < 20;++i)
{
if(scores(i) > 0.5)
{
LOG(ERROR) << i << ",score:" << scores(i) << ",class:" << classes(i)<< ",box:" << "," << boxes(0,i,0) << "," << boxes(0,i,1) << "," << boxes(0,i,2)<< "," << boxes(0,i,3);
}
}
return 0;
}
|
I think some of the formatting must of been lost in the post as been trying to get the above code to run for the last couple of hours without success. Just comparing to label_image.cc to figure out what it is suppose to be doing. Will post when I have a working copy. Thanks |
Thank you for editing.. Now compiles without issue! |
Close this issue as it"s resolved. |
I use c++ code above, but the efficiency is very low, excuse me why? How to improve efficiency @daisyl0 |
@daisyl0 or @pzw520125 how can I compile it? Its keep giving me error. I tried with g++ and bazel build. If you are using bazel then can you please tell me which deps I need to include? |
Hey guys, I"m also wondering how to compile the code. Following the example in C++ API guide I changed the BUILD to look like this: `load("//tensorflow:tensorflow.bzl", "tf_cc_binary") tf_cc_binary( Where OB_Inference.cc in the code shared by @daisyl0. The file OB_Inference.cc is in TF_root/tensorflow/cc/example (as instructed in C++ API guide) and for compiling it I issued the following command:
But it gives me this error:
I appreciate any help as I"m very new to TF. Thank you. |
@shresthamalik how do you to Cast the ouputtensors from to float to unit, can you share the way to me, I meet same issue, thanks very much. |
Hi, @KallerLong1 there is a C++ TF API , Cast() which can be used for this purpose. I used this code for image classification as example: In this example, line 157 , uses Cast() to convert tensor to float. We can use Cast() to convert tensor to tensorflow::DT_UINT8 |
@shresthamalik Thanks very much for your help. I had to do the below steps, I don"t know how to do next to return a tensor project. Please see below code.
|
@shresthamalik Thanks for your help, I had resolved it. |
@daisyl0 |
Caused by: java.lang.IllegalArgumentException: Expects arg[0] to be uint8 but float is provided I am developping on Android Studio and the model input is : Found 1 possible inputs: (name=image_tensor, type=uint8(4), shape=[?,?,?,3]) In my android code what I am trying to get is the array float of the values of pixels of an image stored as Bitmap and then I am trying to feed the model. I am getting that error . |
If we have a requirement to pass in raw data files say numpy arrays of shape [height, width, 1] of float32 data type. That is what my object detection FRCNN model was trained on and will expect for input tensors. For this setup how should one store this and read into the main.cc @daisyl0 for a c++ execution? Thanks in advance. |
@terrydl Thanks for sharing your code. I was struggling on the cast issue :) |
I also have the problem same: "Invalid argument: Expects arg[0] to be bool but float is provided". I using tensorflow1.8 in C++ api, and load the *.pb model trained by python. When run the sesssion, error occurs, can you help me ? Thanks a lot @shresthamalik @tatatodd @yeephycho @khegelich360Fly |
Have you solved this problem?thank you! |
thank you very much for your code. |
@daisyl0 hi , how can convert uint8_caster to a Tensorflow::tensor object ? |
can anyone told me how to use tensorflow c++ API. what I am doing just googling too much copy and pasting codes I don"t understand even a single ++ API. I try to get any knowledge from official tensorflow web site but their only Input and output is mention, not detail documentation is available, How Internally It works. How to convert normal c++ data type to tensors etc. can anyone suggest me some good reference where I can grasp these knowledge?? |
Could you please help to add a C++ example to run the object detection models, similar to the python example object_detection_tutorial.ipynb? I am very interesting to run the object detection model Android platform.
The text was updated successfully, but these errors were encountered: