Skip to content

Instantly share code, notes, and snippets.

@jart
Last active October 14, 2017 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jart/c8b84a17ffa9e8e5dfa30342b8feca7a to your computer and use it in GitHub Desktop.
Save jart/c8b84a17ffa9e8e5dfa30342b8feca7a to your computer and use it in GitHub Desktop.
TensorFlow C++ PNG to JPG converter static binary
load("//tensorflow:tensorflow.bzl", "tf_cc_binary")
tf_cc_binary(
name = "png2jpg",
srcs = ["png2jpg.cc"],
linkstatic = 1,
deps = [
"//tensorflow/cc:cc_ops",
"//tensorflow/cc:client_session",
"//tensorflow/cc:scope",
"//tensorflow/core:direct_session",
"//tensorflow/core:framework",
"//tensorflow/core:lib",
"//tensorflow/core/kernels:constant_op",
"//tensorflow/core/kernels:decode_image_op",
"//tensorflow/core/kernels:encode_jpeg_op",
],
)
#include <iostream>
#include <vector>
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/array_ops.h"
#include "tensorflow/cc/ops/image_ops.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
using namespace tensorflow;
static Status ConvertPngToJpg(const string& png, string* jpg) {
Scope root = Scope::NewRootScope();
ClientSession session(root);
auto x = ops::Placeholder(root, DT_STRING);
auto decode_png = ops::DecodePng(root, x);
auto encode_jpg = ops::EncodeJpeg(root, decode_png);
Tensor t(DT_STRING, TensorShape({}));
t.scalar<string>()() = png;
std::vector<Tensor> outputs;
TF_RETURN_IF_ERROR(session.Run({{x, t}}, {encode_jpg}, &outputs));
*jpg = outputs[0].scalar<string>()();
return Status::OK();
}
int main(int argc, char* argv[]) {
if (argc != 1) {
std::cerr << "Usage: " << argv[0] << " <foo.png >bar.jpg" << std::endl;
return 1;
}
std::ostringstream png;
png << std::cin.rdbuf();
string jpg;
Status s = ConvertPngToJpg(png.str(), &jpg);
if (!s.ok()) {
std::cerr << s << std::endl;
return 1;
}
std::cout << jpg;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment