Img2Num C++ (Internal Developer Docs) dev
API Documentation
Loading...
Searching...
No Matches
img2num Namespace Reference

Classes

struct  ImageToSvgConfig
 Configuration options for image_to_svg. More...
 

Enumerations

enum class  Error {
  OK = 0 , BAD_ALLOC = 1 , INVALID_ARGUMENT = 2 , RUNTIME = 3 ,
  UNKNOWN = 4
}
 

Functions

void gaussian_blur_fft (uint8_t *image, size_t width, size_t height, double sigma)
 Apply a Gaussian blur to an image using FFT.
 
void invert_image (uint8_t *image, int width, int height)
 Invert the pixel values of an image.
 
void threshold_image (uint8_t *image, const int width, const int height, const int num_thresholds)
 Apply a thresholding operation to an image.
 
void black_threshold_image (uint8_t *image, const int width, const int height, const int num_thresholds)
 Apply black-thresholding to an image.
 
void kmeans (const uint8_t *data, uint8_t *out_data, int32_t *out_labels, const int32_t width, const int32_t height, const int32_t k, const int32_t max_iter, const uint8_t color_space)
 Perform k-means clustering on image data.
 
void bilateral_filter (uint8_t *image, size_t width, size_t height, double sigma_spatial, double sigma_range, uint8_t color_space)
 Apply bilateral filtering to an image.
 
std::string labels_to_svg (const uint8_t *data, const int32_t *labels, const int width, const int height, const int min_area, const int min_thickness)
 Convert labeled regions of an image into an SVG string.
 
std::string image_to_svg (const uint8_t *data, const int width, const int height, const ImageToSvgConfig &config)
 Convert labeled regions of an image into an SVG string.
 
Error get_last_error ()
 
const std::string get_last_error_message ()
 
void clear_last_error ()
 
void set_error (Error code, const std::string message)
 
template<typename Func , typename... Args>
void clear_last_error_and_catch (Func &&exception_prone_func, Args &&... args)
 

Variables

thread_local Error last_error {Error::OK}
 
thread_local std::string last_error_message {}
 

Detailed Description

Note
All image buffers are assumed to be stored in row-major order, unless otherwise noted.

Enumeration Type Documentation

◆ Error

enum class img2num::Error
strong

Definition at line 8 of file Error.h.

8{ OK = 0, BAD_ALLOC = 1, INVALID_ARGUMENT = 2, RUNTIME = 3, UNKNOWN = 4 };

Function Documentation

◆ bilateral_filter()

void img2num::bilateral_filter ( uint8_t *  image,
size_t  width,
size_t  height,
double  sigma_spatial,
double  sigma_range,
uint8_t  color_space 
)

Apply bilateral filtering to an image.

Parameters
imagePointer to RGBA pixel buffer.
widthWidth of the image in pixels.
heightHeight of the image in pixels.
sigma_spatialStandard deviation for spatial Gaussian (proximity weight).
sigma_rangeStandard deviation for range Gaussian (intensity similarity weight).
color_spaceColor space flag (0 = CIE LAB, 1 = RGB).
Note
The filter modifies the image buffer in-place.
Dox File: doxygen/img2num.h.dox

Definition at line 230 of file bilateral_filter.cpp.

233 {
234 GPU::getClassInstance().init_gpu();
235
236 if (GPU::getClassInstance().is_initialized()) {
237 bilateral_filter_gpu(image, width, height, sigma_spatial, sigma_range, color_space);
238 } else {
239 bilateral_filter_cpu(image, width, height, sigma_spatial, sigma_range, color_space);
240 }
241}

Referenced by image_to_svg().

+ Here is the caller graph for this function:

◆ black_threshold_image()

void img2num::black_threshold_image ( uint8_t *  image,
const int  width,
const int  height,
const int  num_thresholds 
)

Apply black-thresholding to an image.

Parameters
imagePointer to the image buffer.
widthWidth of the image in pixels.
heightHeight of the image in pixels.
num_thresholdsPer-channel brightness cutoff in the 0-255 range.
Note
A pixel is set to pure black when all of its red, green and blue channels are strictly below num_thresholds; all other pixels are left untouched. This is a brightness cutoff, not a number of output levels. Values of 0 or less leave the image unchanged.
Blackened pixels have their alpha channel set to an opaque 255.
Dox File: doxygen/img2num.h.dox

Definition at line 203 of file image_utils.cpp.

205 {
206 if (num_thresholds <= 0) {
207 return;
208 }
210 img.loadFromBuffer(image, width, height, ImageLib::RGBA_CONVERTER<uint8_t>);
211
212 const auto imgWidth {img.getWidth()}, imgHeight {img.getHeight()};
213 for (ImageLib::RGBAPixel<uint8_t>& p : img) {
214 const bool R {p.red < num_thresholds};
215 const bool G {p.green < num_thresholds};
216 const bool B {p.blue < num_thresholds};
217 if (R && B && G) {
218 p.setGray(0);
219 }
220 }
221
222 const auto& modified = img.getData();
223 std::memcpy(image, modified.data(), modified.size() * sizeof(ImageLib::RGBAPixel<uint8_t>));
224}

◆ clear_last_error()

void img2num::clear_last_error ( )

Definition at line 7 of file Error.cpp.

7 {
8 last_error = Error::OK;
9 last_error_message.clear();
10}

◆ clear_last_error_and_catch()

template<typename Func , typename... Args>
void img2num::clear_last_error_and_catch ( Func &&  exception_prone_func,
Args &&...  args 
)

Definition at line 25 of file Error.h.

25 {
26 clear_last_error(); // Clear any previous error state
27 try {
28 exception_prone_func(std::forward<Args>(args)...); // Call the passed function
29 } catch (const std::bad_alloc& e) {
30 set_error(Error::BAD_ALLOC, e.what());
31 } catch (const std::invalid_argument& e) {
32 set_error(Error::INVALID_ARGUMENT, e.what());
33 } catch (const std::runtime_error& e) {
34 set_error(Error::RUNTIME, e.what());
35 } catch (const std::exception& e) {
36 set_error(Error::UNKNOWN, e.what());
37 } catch (...) {
38 set_error(Error::UNKNOWN, "Unknown exception occurred");
39 }
40}

◆ gaussian_blur_fft()

void img2num::gaussian_blur_fft ( uint8_t *  image,
size_t  width,
size_t  height,
double  sigma_pixels 
)

Apply a Gaussian blur to an image using FFT.

Parameters
imagePointer to the image buffer (RGBA).
widthWidth of the image in pixels.
heightHeight of the image in pixels.
sigmaStandard deviation for Gaussian kernel.
Note
The operation modifies the image buffer in-place.
Dox File: doxygen/img2num.h.dox

Applies a Gaussian blur in place using FFT on the R, G and B channels of an RGBA image. The image is reflect-padded by ceil(3 * sigma_pixels) on each side before the FFT to avoid border darkening and circular edge wrapping. The alpha channel is left unchanged.

Parameters
imagePointer to RGBA data (4 bytes per pixel).
widthImage width in pixels.
heightImage height in pixels.
sigma_pixelsStandard deviation of the Gaussian in pixels. Must be finite and > 0, otherwise the image is left untouched.

Definition at line 74 of file image_utils.cpp.

74 {
75 if (!image || width == 0 || height == 0 || !std::isfinite(sigma_pixels) || sigma_pixels <= 0)
76 return;
77
78 // Keep every dimension within 2^30 so the int casts below (reflect_index, freq_coord)
79 // and next_power_of_two() cannot overflow.
80 constexpr size_t kMaxDim = size_t(1) << 30;
81 if (width > kMaxDim || height > kMaxDim)
82 return;
83
84 // Pad by at least 3*sigma pixels to avoid border darkening and edge wrapping.
85 // Check in double BEFORE casting: converting an out-of-range double to size_t is UB.
86 const double pad_d = std::ceil(3.0 * sigma_pixels);
87 if (pad_d > static_cast<double>(kMaxDim))
88 return;
89 const size_t pad = static_cast<size_t>(pad_d);
90
91 // Ensure width + 2*pad and height + 2*pad stay <= kMaxDim (written to avoid overflow)
92 if (pad > (kMaxDim - width) / 2 || pad > (kMaxDim - height) / 2)
93 return;
94 const size_t padded_width = width + 2 * pad;
95 const size_t padded_height = height + 2 * pad;
96
97 // Compute padded dimensions (next power of two); both are <= kMaxDim
98 const size_t W = fft::next_power_of_two(padded_width);
99 const size_t H = fft::next_power_of_two(padded_height);
100
101 // Cap total FFT buffer size to prevent memory exhaustion (DoS) from a huge sigma.
102 // This also covers the W * H overflow case, so no separate overflow check is needed.
103 constexpr size_t MAX_FFT_ELEMENTS = 64 * 1024 * 1024; // 64M elements limit
104 if (W > MAX_FFT_ELEMENTS / H)
105 return;
106 const size_t Npix_padded = W * H;
107
108 // Frequency coordinates helper (DC at corner)
109 auto freq_coord = [](int k, int dim) -> double {
110 return (k <= dim / 2) ? double(k) / dim : double(k - dim) / dim;
111 };
112
113 // Precompute Gaussian factor in frequency domain
114 const double two_pi2_sigma2 = 2.0 * M_PI * M_PI * sigma_pixels * sigma_pixels;
115
116 for (int channel = 0; channel < 3; channel++) {
117 // Allocate padded buffer
118 std::vector<fft::cd> data(Npix_padded, {0.0, 0.0});
119
120 // Copy image channel with reflect padding into padded buffer
121 for (size_t y = 0; y < H; y++) {
122 int py = static_cast<int>(y) - static_cast<int>(pad);
123 size_t src_y = reflect_index(py, static_cast<int>(height));
124 for (size_t x = 0; x < W; x++) {
125 int px = static_cast<int>(x) - static_cast<int>(pad);
126 size_t src_x = reflect_index(px, static_cast<int>(width));
127 data[y * W + x] = fft::cd(image[(src_y * width + src_x) * 4 + channel], 0.0);
128 }
129 }
130
131 // Forward 2D FFT
132 fft::iterative_fft_2d(data, W, H, false);
133
134 // Apply Gaussian filter in frequency domain
135 for (size_t y = 0; y < H; y++) {
136 double fy2 = freq_coord(y, H) * freq_coord(y, H);
137 for (size_t x = 0; x < W; x++) {
138 double fx2 = freq_coord(x, W) * freq_coord(x, W);
139 double gain = std::exp(-two_pi2_sigma2 * (fx2 + fy2));
140 data[y * W + x] *= gain;
141 }
142 }
143
144 // Inverse 2D FFT
145 fft::iterative_fft_2d(data, W, H, true);
146
147 // Copy back original width/height region from (pad, pad) and clamp
148 for (size_t y = 0; y < height; y++) {
149 for (size_t x = 0; x < width; x++) {
150 size_t py = y + pad;
151 size_t px = x + pad;
152 double v = data[py * W + px].real();
153 if (v < 0.0)
154 v = 0.0;
155 else if (v > 255.0)
156 v = 255.0;
157 image[(y * width + x) * 4 + channel] = static_cast<uint8_t>(std::lrint(v));
158 }
159 }
160 }
161
162 // Alpha channel remains unchanged
163}

◆ get_last_error()

Error img2num::get_last_error ( )
inline

Definition at line 13 of file Error.h.

13 {
14 return last_error;
15}

◆ get_last_error_message()

const std::string img2num::get_last_error_message ( )
inline

Definition at line 16 of file Error.h.

16 {
17 return last_error_message;
18}

◆ image_to_svg()

std::string img2num::image_to_svg ( const uint8_t *  data,
const int  width,
const int  height,
const ImageToSvgConfig &  config 
)

Convert labeled regions of an image into an SVG string.

Parameters
dataPointer to image data buffer.
widthWidth of the image in pixels.
heightHeight of the image in pixels.
configimg2num_ImageToSvgConfig Configuration Struct.

‍See img2num::ImageToSvgConfig.

Returns
std::string An SVG string containing data roughly approximate to the input image.
Note
Dox File: doxygen/img2num.h.dox

Definition at line 7 of file image_to_svg.cpp.

9 {
10 // self deallocate
11 std::vector<uint8_t> img_data(static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
12 std::vector<uint8_t> out_data(static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
13 std::vector<int32_t> out_labels(static_cast<size_t>(width) * static_cast<size_t>(height));
14
15 std::memcpy(
16 img_data.data(), data, static_cast<size_t>(width) * static_cast<size_t>(height) * 4
17 );
19 img_data.data(), width, height, config.bilateral_filter.sigma_spatial,
20 config.bilateral_filter.sigma_range, config.color_space
21 );
22 kmeans(
23 img_data.data(), out_data.data(), out_labels.data(), width, height, config.kmeans.k,
24 config.kmeans.max_iter, config.color_space
25 );
26 std::string svg {labels_to_svg(
27 data, out_labels.data(), width, height, config.min_cluster_area, config.min_thickness
28 )};
29
30 return svg;
31}
void bilateral_filter(uint8_t *image, size_t width, size_t height, double sigma_spatial, double sigma_range, uint8_t color_space)
Apply bilateral filtering to an image.
std::string labels_to_svg(const uint8_t *data, const int32_t *labels, const int width, const int height, const int min_area, const int min_thickness)
Convert labeled regions of an image into an SVG string.
void kmeans(const uint8_t *data, uint8_t *out_data, int32_t *out_labels, const int32_t width, const int32_t height, const int32_t k, const int32_t max_iter, const uint8_t color_space)
Perform k-means clustering on image data.
Definition kmeans.cpp:242
int min_cluster_area
Minimum area (in pixels) for a region to be included in the SVG.
Definition img2num.h:42

References bilateral_filter(), img2num::ImageToSvgConfig::color_space, img2num::ImageToSvgConfig::KMeansConfig::k, kmeans(), labels_to_svg(), img2num::ImageToSvgConfig::KMeansConfig::max_iter, img2num::ImageToSvgConfig::min_cluster_area, img2num::ImageToSvgConfig::min_thickness, img2num::ImageToSvgConfig::BilateralFilterConfig::sigma_range, and img2num::ImageToSvgConfig::BilateralFilterConfig::sigma_spatial.

+ Here is the call graph for this function:

◆ invert_image()

void img2num::invert_image ( uint8_t *  image,
int  width,
int  height 
)

Invert the pixel values of an image.

Parameters
imagePointer to the image buffer.
widthWidth of the image in pixels.
heightHeight of the image in pixels.
Note
Each pixel value is replaced by 255 - original_value.
Dox File: doxygen/img2num.h.dox

Definition at line 166 of file image_utils.cpp.

166 {
168 img.loadFromBuffer(image, width, height, ImageLib::RGBA_CONVERTER<uint8_t>);
169
170 for (ImageLib::RGBAPixel<uint8_t>& p : img) {
171 p.red = 255 - p.red;
172 p.blue = 255 - p.blue;
173 p.green = 255 - p.green;
174 }
175
176 const auto& modified = img.getData();
177 std::memcpy(image, modified.data(), modified.size() * sizeof(ImageLib::RGBAPixel<uint8_t>));
178}

◆ kmeans()

void img2num::kmeans ( const uint8_t *  data,
uint8_t *  out_data,
int32_t *  out_labels,
const int32_t  width,
const int32_t  height,
const int32_t  k,
const int32_t  max_iter,
const uint8_t  color_space 
)

Perform k-means clustering on image data.

Parameters
dataPointer to input image data buffer.
out_dataPointer to output buffer where clustered pixel values are stored.
out_labelsPointer to output buffer for cluster labels per pixel.
widthWidth of the image in pixels.
heightHeight of the image in pixels.
kNumber of clusters to compute.
max_iterMaximum number of iterations for the algorithm.
color_spaceColor space flag (0 = CIE LAB, 1 = RGB).
Note
The function does not modify the input buffer.
Dox File: doxygen/img2num.h.dox

Definition at line 242 of file kmeans.cpp.

245 {
246 GPU::getClassInstance().init_gpu();
247
248 if (GPU::getClassInstance().is_initialized()) {
249 kmeans_gpu(data, out_data, out_labels, width, height, k, max_iter, color_space);
250 } else {
251 kmeans_cpu(data, out_data, out_labels, width, height, k, max_iter, color_space);
252 }
253}

Referenced by image_to_svg().

+ Here is the caller graph for this function:

◆ labels_to_svg()

std::string img2num::labels_to_svg ( const uint8_t *  data,
const int32_t *  labels,
const int  width,
const int  height,
const int  min_area,
const int  min_thickness = 0 
)

Convert labeled regions of an image into an SVG string.

Parameters
dataPointer to image data buffer.
labelsPointer to label buffer, indicating region for each pixel.
widthWidth of the image in pixels.
heightHeight of the image in pixels.
min_areaMinimum area (in pixels) for a region to be included in the SVG.
Returns
std::string A valid SVG string containing the data.
Note
Dox File: doxygen/img2num.h.dox

Definition at line 206 of file labels_to_svg.cpp.

209 {
210 const int32_t num_pixels {width * height};
211 std::vector<int32_t> labels_vector {labels, labels + num_pixels};
212 std::vector<int32_t> region_labels;
213
214 // 1. enumerate regions and convert to Nodes
215 std::vector<Node_ptr> nodes;
216 region_labeling(data, labels_vector, region_labels, width, height, nodes);
217
218 // 2. initialize Graph from all Nodes
219 std::unique_ptr<std::vector<Node_ptr>> node_ptr =
220 std::make_unique<std::vector<Node_ptr>>(std::move(nodes));
221 Graph G(node_ptr, width, height);
222
223 // 3. Discover node adjacencies - add edges to Graph
224 G.discover_edges(region_labels, width, height);
225
226 // 4. Merge small area nodes until all nodes are minArea or larger
227 G.merge_small_area_nodes(min_area, min_thickness);
228
229 // 5. recolor image on new regions
230 ImageLib::Image<ImageLib::RGBAPixel<uint8_t>> results {width, height};
231 for (auto& n : G.get_nodes()) {
232 if (n->area() == 0)
233 continue;
234
235 auto [r, g, b] = n->color();
236 for (auto& [_, p] : n->get_pixels()) {
237 results(p.x, p.y) = {r, g, b};
238 }
239 }
240
241 // 6. Contours
242 // graph will manage computing contours
243 G.compute_contours();
244
245 // accumulate all contours for svg export
246 ColoredContours all_contours;
247 for (auto& n : G.get_nodes()) {
248 if (n->area() == 0)
249 continue;
250 ColoredContours node_contours = n->get_contours();
251 for (auto& c : node_contours.contours) {
252 all_contours.contours.push_back(c);
253 }
254 for (auto& c : node_contours.hierarchy) {
255 all_contours.hierarchy.push_back(c);
256 }
257 for (bool b : node_contours.is_hole) {
258 all_contours.is_hole.push_back(b);
259 }
260 for (auto& c : node_contours.colors) {
261 all_contours.colors.push_back(c);
262 }
263 for (auto& c : node_contours.curves) {
264 all_contours.curves.push_back(c);
265 }
266 }
267
268 // 7. Return SVG
269 return contoursResultToSVG(all_contours, width, height);
270}
Definition graph.h:33

Referenced by image_to_svg().

+ Here is the caller graph for this function:

◆ set_error()

void img2num::set_error ( Error  code,
const std::string  message 
)

Definition at line 12 of file Error.cpp.

12 {
13 last_error = code;
14 last_error_message = message;
15}

◆ threshold_image()

void img2num::threshold_image ( uint8_t *  image,
const int  width,
const int  height,
const int  num_thresholds 
)

Apply a thresholding operation to an image.

Parameters
imagePointer to the image buffer.
widthWidth of the image in pixels.
heightHeight of the image in pixels.
num_thresholdsNumber of thresholds to apply.
Note
Thresholds split pixel intensity ranges into discrete levels.
Dox File: doxygen/img2num.h.dox

Definition at line 180 of file image_utils.cpp.

180 {
181 if (num_thresholds <= 0) {
182 return;
183 }
184 const uint8_t REGION_SIZE(255 / num_thresholds); // Size of buckets per colour
185
187 img.loadFromBuffer(image, width, height, ImageLib::RGBA_CONVERTER<uint8_t>);
188
189 const auto imgWidth {img.getWidth()}, imgHeight {img.getHeight()};
190 for (ImageLib::RGBAPixel<uint8_t>& p : img) {
191 p.red = quantize(p.red, REGION_SIZE);
192 p.green = quantize(p.green, REGION_SIZE);
193 p.blue = quantize(p.blue, REGION_SIZE);
194 }
195
196 const auto& modified = img.getData();
197 std::memcpy(image, modified.data(), modified.size() * sizeof(ImageLib::RGBAPixel<uint8_t>));
198}

Variable Documentation

◆ last_error

thread_local Error img2num::last_error {Error::OK}

Definition at line 4 of file Error.cpp.

4{Error::OK};

◆ last_error_message

thread_local std::string img2num::last_error_message {}

Definition at line 5 of file Error.cpp.

5{};