Volume Cartographer 2.28.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
41 bool scaleMinMax{true};
42};
43
53 const filesystem::path& path, const cv::Mat& img, WriteImageOpts = {});
54
71template <class Iterable>
73 const filesystem::path& path,
74 const Iterable& iterable,
75 const WriteImageOpts& opts = {},
76 const std::size_t idxOffset = 0)
77{
78 namespace fs = filesystem;
79
80 // components
81 fs::path parent;
82 std::string prefix;
83 std::string suffix;
84 fs::path ext;
85
86 // If directory, default to dir/###.tif
87 if (fs::is_directory(path)) {
88 parent = path;
89 ext = ".tif";
90 }
91
92 // If path, decompose to replace {} with a number
93 else {
94 parent = path.parent_path();
95 ext = path.extension();
96
97 // Split into a prefix and suffix
98 auto stem = path.stem().string();
99 std::string sep;
100 std::tie(prefix, sep, suffix) = partition(stem, "{}");
101
102 // Log when separator not found
103 if (sep.empty()) {
104 Logger()->debug(
105 "Index placement separator {{}} not found in stem: {}", stem);
106 }
107 }
108
109 // Setup padding (default or user-provided)
110 auto pad = std::to_string(std::size(iterable)).size();
111 pad = opts.padding.value_or(pad);
112
113 // Write images
114 for (const auto [i, image] : enumerate(iterable)) {
115 const auto name =
116 prefix + to_padded_string(idxOffset + i, pad) + suffix;
117 auto filepath = (parent / name).replace_extension(ext);
118 WriteImage(filepath, image, opts);
119 }
120}
121
122} // namespace volcart
auto enumerate(Iterable &&it)
Wrap an Iterable into a new one whose iterators return an [index, value] pair.
Definition: Iteration.hpp:527
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.
void WriteImageSequence(const filesystem::path &path, const Iterable &iterable, const WriteImageOpts &opts={}, const std::size_t idxOffset=0)
Write a sequence of images to disk.
Definition: ImageIO.hpp:72
std::optional< int > padding
Definition: ImageIO.hpp:34
std::optional< int > compression
Definition: ImageIO.hpp:31