Volume Cartographer 2.27.0
ImageIO.hpp
1#pragma once
2
3#include <optional>
4
5#include <opencv2/core.hpp>
6
11
12namespace volcart
13{
14
24auto ReadImage(const filesystem::path& path) -> cv::Mat;
25
31 std::optional<int> compression;
32
34 std::optional<int> padding;
35};
36
46 const filesystem::path& path, const cv::Mat& img, WriteImageOpts = {});
47
48template <class Iterable>
49void WriteImageSequence(
50 const filesystem::path& path,
51 const Iterable& iterable,
52 const WriteImageOpts& opts = {})
53{
54 namespace fs = volcart::filesystem;
55
56 // components
57 fs::path parent;
58 std::string prefix;
59 std::string suffix;
60 fs::path ext;
61
62 // If directory, default to dir/###.tif
63 if (fs::is_directory(path)) {
64 parent = path;
65 ext = ".tif";
66 }
67
68 // If path, decompose to replace {} with a number
69 else {
70 parent = path.parent_path();
71 ext = path.extension();
72
73 // Split into a prefix and suffix
74 auto stem = path.stem().string();
75 std::tie(prefix, std::ignore, suffix) = partition(stem, "{}");
76
77 // Log when separator not found
78 if (suffix.empty()) {
79 Logger()->debug(
80 "Index placement separator \\{\\} not found in stem: {}", stem);
81 }
82 }
83
84 // Setup padding (default or user-provided)
85 auto pad = std::to_string(std::size(iterable)).size();
86 pad = opts.padding.value_or(pad);
87
88 // Write images
89 for (const auto [i, image] : enumerate(iterable)) {
90 const auto name = prefix + to_padded_string(i, pad) + suffix;
91 auto filepath = (parent / name).replace_extension(ext);
92 WriteImage(filepath, image, opts);
93 }
94}
95
96} // namespace volcart
auto enumerate(Iterable &&it)
Wrap an Iterable into a new one whose iterators return an [index, value] pair.
Definition: Iteration.hpp:527
Alias for std::filesystem
Volume Cartographer library
auto Logger() -> std::shared_ptr< spdlog::logger >
Volume Cartographer global logger.
auto to_padded_string(Integer val, const int padding, const char fill='0') -> std::string
Convert an Integer to a padded string.
Definition: String.hpp:247
auto ReadImage(const filesystem::path &path) -> cv::Mat
Read an image from the specified path.
static auto partition(std::string_view s, std::string_view sep) -> std::tuple< std::string, std::string, std::string >
Partition a string by a separator substring.
Definition: String.hpp:223
void WriteImage(const filesystem::path &path, const cv::Mat &img, WriteImageOpts={})
Write image to the specified path.
std::optional< int > padding
Definition: ImageIO.hpp:34
std::optional< int > compression
Definition: ImageIO.hpp:31