Skip to content

Instantly share code, notes, and snippets.

@Dobiasd
Last active December 12, 2018 14:38
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 Dobiasd/21651861b73042762126e8eea52d9974 to your computer and use it in GitHub Desktop.
Save Dobiasd/21651861b73042762126e8eea52d9974 to your computer and use it in GitHub Desktop.
// Example code for how to:
// - load an image using CImg
// - convert it to a fdeep::tensor5
// - use it as input for a forward pass on an image classification model
// - print the class number
// compile with:
// g++ -std=c++14 -O3 cimg_example.cpp -L/usr/X11R6/lib -lm -lpthread -lX11 -o cimg_example
#include <fdeep/fdeep.hpp>
#include "CImg.h"
fdeep::tensor5 cimg_to_tensor5(const cimg_library::CImg<unsigned char>& image,
fdeep::float_type low = 0.0f, fdeep::float_type high = 1.0f)
{
const int width = image.width();
const int height = image.height();
const int channels = image.spectrum();
std::vector<unsigned char> pixels;
pixels.reserve(height * width * channels);
// CImg stores the pixels of an image non-interleaved:
// http://cimg.eu/reference/group__cimg__storage.html
// This loop changes the order to interleaved,
// e.e. RRRGGGBBB to RGBRGBRGB for 3-channel images.
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
for (int c = 0; c < channels; c++)
{
pixels.push_back(image(x, y, 0, c));
}
}
}
return fdeep::tensor5_from_bytes(pixels.data(), height, width, channels,
low, high);
}
int main()
{
const cimg_library::CImg<unsigned char> image("image.jpg");
const auto model = fdeep::load_model("model.json");
// Use the correct scaling, i.e. low and high.
const auto input = cimg_to_tensor5(image, 0.0f, 1.0f);
const auto result = model.predict_class({input});
std::cout << result << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment