Img2Num C++ (Internal Developer Docs) dev
API Documentation
Loading...
Searching...
No Matches
image_utils.cpp
1#include "internal/image_utils.h"
2
3#include "img2num.h"
4#include "internal/fft_iterative.h"
5#include "internal/Image.h"
6#include "internal/PixelConverters.h"
7#include "internal/RGBAPixel.h"
8
9#include <algorithm>
10#include <cmath>
11#include <cstdint>
12#include <cstring>
13#include <limits>
14#include <vector>
15
16// M_PI is not defined by default on MSVC
17#ifndef M_PI
18#define M_PI 3.14159265358979323846
19#endif
20
21uint8_t quantize(uint8_t value, uint8_t region_size) {
22 if (region_size == 0) {
23 return value;
24 }
25
26 uint8_t bucket = value / region_size; // Narrowing to colour boundary with
27 // Range [0 : num_thresholds - 1].
28
29 uint8_t bucket_boundary = (bucket * region_size);
30 uint8_t bucket_midpoint =
31 bucket_boundary + (region_size / 2); // Map to threshold region's midpoint.
32
33 // In case of bucket_midpoint overflow: revert to a smaller bucket than the
34 // largest possible value.
35 bool overflow = bucket_midpoint < bucket_boundary;
36 if (overflow) {
37 bucket_midpoint = ((bucket - 1) * region_size) +
38 (region_size / 2); // Correction by reducing the bucket value belongs to.
39 }
40
41 return bucket_midpoint;
42}
43
49static size_t reflect_index(int p, int dim) {
50 if (dim <= 1)
51 return 0;
52 const int64_t period = 2 * static_cast<int64_t>(dim); // int64: 2*dim can overflow int
53 int64_t q = p % period;
54 if (q < 0)
55 q += period;
56 if (q >= dim)
57 q = period - 1 - q;
58 return static_cast<size_t>(q);
59}
60
61namespace img2num {
62
74void gaussian_blur_fft(uint8_t* image, size_t width, size_t height, double sigma_pixels) {
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}
164
165// Called from JS. `image` points to RGBA bytes.
166void invert_image(uint8_t* image, int width, int height) {
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}
179
180void threshold_image(uint8_t* image, const int width, const int height, const int num_thresholds) {
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}
199
200// Unlike `threshold_image` above, `num_thresholds` here is a per-channel 0-255
201// brightness cutoff, not a number of output levels. A pixel becomes pure black
202// only when all three of its channels are strictly below the cutoff.
204 uint8_t* image, const int width, const int height, const int num_thresholds
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}
225
226} // namespace img2num
Core image processing functions for img2num project.
void black_threshold_image(uint8_t *image, const int width, const int height, const int num_thresholds)
Apply black-thresholding to an image.
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.