Skip to content

Instantly share code, notes, and snippets.

@ganler
Created March 21, 2020 08:15
Show Gist options
  • Save ganler/8b7ffcfcd1b250a2616ddbd18c128708 to your computer and use it in GitHub Desktop.
Save ganler/8b7ffcfcd1b250a2616ddbd18c128708 to your computer and use it in GitHub Desktop.
#include <opencv2/opencv.hpp>
std::vector<float> images2nchw(std::vector<cv::Mat> images, cv::Size size, double factor=1.0, bool flip_rb = true) {
std::vector<float> data;
data.reserve(size.area() * 3 * images.size());
size_t base = 0;
for(auto&& image : images)
{
assert(image.type() == CV_8UC3);
cv::resize(image, image, size);
int frame_size = size.area();
int iter_rows = image.rows;
int iter_cols = image.cols;
if(image.isContinuous())
{
iter_cols = image.total();
iter_rows = 1;
}
constexpr std::array<int, 3> no_swap {0, 1, 2};
constexpr std::array<int, 3> swap_rb {2, 1, 0};
const auto& index_ref = flip_rb ? swap_rb : no_swap;
for(auto c : index_ref)
for (int i = 0; i < iter_rows; ++i)
{
const auto* line = image.ptr<cv::Vec3b>(i);
for(int j = 0; j < iter_cols; ++j)
data.push_back((*line++)[c]);
}
}
return data;
}
int main()
{
cv::Mat ones = cv::Mat::ones({10, 10}, CV_8UC3);
std::cout << ones << '\n';
auto v = images2nchw({ones, ones}, ones.size(), 2);
for (int i = 0; i < ones.channels() * 2; ++i) {
for (int j = 0; j < ones.size().area(); ++j) {
std::cout << v[i * ones.size().area() + j] << ' ';
}
std::cout << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment