-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimage_io.h
More file actions
610 lines (509 loc) · 23.8 KB
/
Copy pathimage_io.h
File metadata and controls
610 lines (509 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
/* Developed by Jimmy Hu */
#ifndef TINYDIP_IMAGE_IO_H // image_io.h header guard, follow the suggestion from https://codereview.stackexchange.com/a/293832/231235
#define TINYDIP_IMAGE_IO_H
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include "image.h"
namespace TinyDIP
{
Image<RGB> raw_image_to_array(const int xsize, const int ysize, const unsigned char * const image);
unsigned long bmp_read_x_size(const char *filename, const bool extension);
unsigned long bmp_read_y_size(const char *filename, const bool extension);
char bmp_read_detail(unsigned char *image, const int xsize, const int ysize, const char *filename, const bool extension);
BMPIMAGE bmp_file_read(const char *filename, const bool extension);
Image<RGB> bmp_read(const char* filename, const bool extension);
int bmp_write(std::string filename, Image<RGB> input);
int bmp_write(const char *filename, Image<RGB> input);
int bmp_write(const char *filename, const int xsize, const int ysize, const unsigned char *image);
unsigned char *array_to_raw_image(Image<RGB> input);
unsigned char bmp_filling_byte_calc(const unsigned int xsize, const int mod_num = 4);
namespace double_image
{
double* array_to_raw_image(Image<double> input);
int write(const char* filename, const int xsize, const int ysize, const double* image);
int write(const char* filename, Image<double> input);
TinyDIP::Image<double> read(const char* const filename, const bool extension);
double* array_to_raw_image(Image<HSV> input);
// -------------------------------------------------------------------------
// write_to_csv template function implementation (Execution Policy Overload)
// -------------------------------------------------------------------------
template <class ExecutionPolicy, class ElementT = double>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> &&
TinyDIP::is_streamable<ElementT>)
void write_to_csv(ExecutionPolicy&& policy, const char* const filename, const Image<ElementT>& input, const int precision = -1)
{
if (input.getDimensionality() != 2)
{
throw std::runtime_error("Input is not a 2D image!\n");
}
std::ofstream file(filename);
if (!file.is_open())
{
throw std::runtime_error("Could not open file for writing!\n");
}
const std::size_t height = input.getHeight();
const std::size_t width = input.getWidth();
// Pre-allocate vector size to prevent race conditions during thread execution
std::vector<std::string> row_strings(height);
std::vector<std::size_t> indices(height);
std::ranges::iota(indices, 0);
// Using standard library execution policy for multi-threading
std::for_each(std::forward<ExecutionPolicy>(policy), std::ranges::begin(indices), std::ranges::end(indices),
[&](const std::size_t y)
{
std::ostringstream oss;
if (precision >= 0)
{
oss << std::fixed << std::setprecision(precision);
}
for (std::size_t x = 0; x < width; ++x)
{
oss << input.at_without_boundary_check(x, y);
if (x < width - 1)
{
oss << ",";
}
}
// Thread-safe: Each thread writes to an exclusive index
row_strings[y] = oss.str();
});
// Write correctly ordered sequences into the file purely sequentially
for (std::size_t y = 0; y < height; ++y)
{
file << row_strings[y] << '\n';
}
}
// -------------------------------------------------------------------------
// write_to_csv template function implementation (OpenMP Fallback)
// -------------------------------------------------------------------------
template<class ElementT = double>
requires TinyDIP::is_streamable<ElementT>
void write_to_csv(const char* const filename, const Image<ElementT>& input, const int precision = -1)
{
if (input.getDimensionality() != 2)
{
throw std::runtime_error("Input is not a 2D image!\n");
}
std::ofstream file(filename);
if (!file.is_open())
{
throw std::runtime_error("Could not open file for writing!\n");
}
const std::size_t height = input.getHeight();
const std::size_t width = input.getWidth();
// Pre-allocate vector size to prevent race conditions
std::vector<std::string> row_strings(height);
#pragma omp parallel for
for (std::ptrdiff_t y = 0; y < static_cast<std::ptrdiff_t>(height); ++y)
{
std::ostringstream oss;
if (precision >= 0)
{
oss << std::fixed << std::setprecision(precision);
}
for (std::size_t x = 0; x < width; ++x)
{
oss << input.at_without_boundary_check(x, static_cast<std::size_t>(y));
if (x < width - 1)
{
oss << ",";
}
}
row_strings[static_cast<std::size_t>(y)] = oss.str();
}
// Write appropriately sequenced rows into the target file
for (std::size_t y = 0; y < height; ++y)
{
file << row_strings[y] << '\n';
}
}
// write_to_csv template function implementation
template <class ExecutionPolicy, class ElementT = double>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> &&
TinyDIP::is_streamable<ElementT>)
void write_to_csv(ExecutionPolicy&& policy, const std::string& filename, const Image<ElementT>& input, const int precision = -1)
{
write_to_csv(std::forward<ExecutionPolicy>(policy), filename.c_str(), input, precision);
return;
}
// ParseCSVRow struct implementation
template <typename ElementT = double>
struct ParseCSVRow
{
const std::vector<std::string>& row_strings;
TinyDIP::Image<ElementT>& image;
const std::size_t width;
void operator()(const std::size_t y) const
{
std::istringstream iss(row_strings[y]);
std::string cell;
std::size_t x = 0;
while (std::getline(iss, cell, ',') && x < width)
{
if constexpr (std::same_as<ElementT, double>)
{
image.at_without_boundary_check(x, y) = std::stod(cell);
}
else
{
std::istringstream cell_stream(cell);
ElementT val{};
cell_stream >> val;
image.at_without_boundary_check(x, y) = val;
}
++x;
}
}
};
// -------------------------------------------------------------------------
// read_from_csv template function implementation (Execution Policy Overload)
// -------------------------------------------------------------------------
template <class ExecutionPolicy, class ElementT = double>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> &&
TinyDIP::is_streamable<ElementT>)
TinyDIP::Image<ElementT> read_from_csv(ExecutionPolicy&& policy, const char* const filename)
{
std::ifstream file(filename);
if (!file.is_open())
{
throw std::runtime_error("Could not open file for reading!\n");
}
std::vector<std::string> lines;
std::string line;
// Read lines sequentially as file I/O is inherently linear
while (std::getline(file, line))
{
if (!line.empty())
{
lines.emplace_back(line);
}
}
if (lines.empty())
{
return TinyDIP::Image<ElementT>();
}
const std::size_t height = lines.size();
std::size_t width = 0;
// Deduce image width from the first row
std::istringstream first_line_stream(lines[0]);
std::string token;
while (std::getline(first_line_stream, token, ','))
{
++width;
}
TinyDIP::Image<ElementT> output(width, height);
std::vector<std::size_t> indices(height);
std::ranges::iota(indices, 0);
ParseCSVRow<ElementT> parser{ lines, output, width };
// Process row strings into double values in parallel
std::for_each(std::forward<ExecutionPolicy>(policy), std::ranges::begin(indices), std::ranges::end(indices), parser);
return output;
}
// -------------------------------------------------------------------------
// read_from_csv template function implementation (OpenMP Fallback)
// -------------------------------------------------------------------------
template <class ElementT = double>
requires TinyDIP::is_streamable<ElementT>
TinyDIP::Image<ElementT> read_from_csv(const char* const filename)
{
std::ifstream file(filename);
if (!file.is_open())
{
throw std::runtime_error("Could not open file for reading!\n");
}
std::vector<std::string> lines;
std::string line;
while (std::getline(file, line))
{
if (!line.empty())
{
lines.emplace_back(line);
}
}
if (lines.empty())
{
return TinyDIP::Image<ElementT>();
}
const std::size_t height = lines.size();
std::size_t width = 0;
std::istringstream first_line_stream(lines[0]);
std::string token;
while (std::getline(first_line_stream, token, ','))
{
++width;
}
TinyDIP::Image<ElementT> output(width, height);
ParseCSVRow<ElementT> parser{ lines, output, width };
#pragma omp parallel for
for (std::ptrdiff_t y = 0; y < static_cast<std::ptrdiff_t>(height); ++y)
{
parser(static_cast<std::size_t>(y));
}
return output;
}
}
namespace pnm
{
// -------------------------------------------------------------------------
// read_pnm_token function implementation
// Helper: Skip comments and read the next string token securely from a PPM
// -------------------------------------------------------------------------
inline std::string read_pnm_token(std::ifstream& file)
{
std::string token;
while (file >> token)
{
if (token.empty())
{
continue;
}
if (token[0] == '#')
{
// If it's a comment, discard the rest of the line
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
else
{
return token;
}
}
return "";
}
// -------------------------------------------------------------------------
// shift_color_value function implementation
// Helper: Precision bit shifting strictly ported from easyppm_read logic
// -------------------------------------------------------------------------
constexpr std::uint8_t shift_color_value(const int value, const int shift_bit)
{
if (shift_bit >= 0)
{
return static_cast<std::uint8_t>(value << shift_bit);
}
else
{
return static_cast<std::uint8_t>(value >> std::abs(shift_bit));
}
}
// -------------------------------------------------------------------------
// Default Lambda Object: Functor with operator() for pixel processing
// -------------------------------------------------------------------------
struct ProcessPPMData
{
const std::vector<int>& raw_data;
const std::string& magic;
const int shift_bit;
const std::size_t width;
const std::size_t height;
TinyDIP::Image<RGB>& image;
constexpr void operator()(const std::size_t i) const
{
const std::size_t x = i % width;
const std::size_t y = i / width;
const std::size_t flipped_y = height - 1 - y;
RGB pixel{};
if (magic == "P1")
{
const int val = (raw_data[i] == 0) ? 1 : 0;
pixel.channels[0] = static_cast<std::uint8_t>(val);
pixel.channels[1] = static_cast<std::uint8_t>(val);
pixel.channels[2] = static_cast<std::uint8_t>(val);
}
else if (magic == "P2")
{
const auto shifted_val = shift_color_value(raw_data[i], shift_bit);
pixel.channels[0] = shifted_val;
pixel.channels[1] = shifted_val;
pixel.channels[2] = shifted_val;
}
else if (magic == "P3")
{
const std::size_t base_idx = i * 3;
pixel.channels[0] = shift_color_value(raw_data[base_idx], shift_bit);
pixel.channels[1] = shift_color_value(raw_data[base_idx + 1], shift_bit);
pixel.channels[2] = shift_color_value(raw_data[base_idx + 2], shift_bit);
}
image.at_without_boundary_check(x, flipped_y) = pixel;
}
};
// -------------------------------------------------------------------------
// transform_pixel_processing template function implementation
// Generic Threading Engine for Data Processing (with invocable constraint)
// -------------------------------------------------------------------------
template <class ExecutionPolicy, typename Func, std::ranges::input_range RangeT>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> &&
std::invocable<Func, std::ranges::range_value_t<RangeT>>)
void transform_pixel_processing(ExecutionPolicy&& policy, const RangeT& indices, Func&& func)
{
std::for_each(std::forward<ExecutionPolicy>(policy), std::ranges::begin(indices), std::ranges::end(indices), std::forward<Func>(func));
}
// transform_pixel_processing_omp template function implementation
// Overload specifically designed to fall back to OpenMP
template <typename Func, std::ranges::random_access_range RangeT>
requires std::invocable<Func, std::ranges::range_value_t<RangeT>>
void transform_pixel_processing_omp(const RangeT& indices, Func&& func)
{
#pragma omp parallel for
for (std::ptrdiff_t i = 0; i < static_cast<std::ptrdiff_t>(std::ranges::size(indices)); ++i)
{
func(indices[i]);
}
}
// -------------------------------------------------------------------------
// read template function implementation
// Modern read_pnm incorporating execution policies and safety checks
// -------------------------------------------------------------------------
template <class ExecutionPolicy>
requires std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>
TinyDIP::Image<RGB> read(ExecutionPolicy&& policy, const std::filesystem::path& file_path, const int outbits = 8)
{
std::ifstream file(file_path, std::ios::binary);
if (!file.is_open())
{
throw std::runtime_error("Could not open file for reading: " + file_path.string());
}
const std::string magic = read_pnm_token(file);
if (magic != "P1" && magic != "P2" && magic != "P3")
{
throw std::runtime_error("Unsupported image format. Magic number found: " + magic);
}
const std::size_t width = std::stoull(read_pnm_token(file));
const std::size_t height = std::stoull(read_pnm_token(file));
int max_value = 1; // Default for P1 (PBM)
if (magic != "P1")
{
max_value = std::stoi(read_pnm_token(file));
}
const int in_bits = static_cast<int>(std::log2(max_value + 1));
const int shift_bit = outbits - in_bits;
const std::size_t pixel_count = width * height;
const std::size_t expected_values = (magic == "P3") ? (pixel_count * 3) : pixel_count;
// Fast-read phase securely ignoring comments throughout the matrix
std::vector<int> raw_data;
raw_data.reserve(expected_values);
for (std::size_t i = 0; i < expected_values; ++i)
{
std::string token = read_pnm_token(file);
if (token.empty())
{
throw std::runtime_error("Unexpected end of file while reading PNM data.");
}
raw_data.emplace_back(std::stoi(token));
}
TinyDIP::Image<RGB> image(width, height);
std::vector<std::size_t> indices(pixel_count);
std::ranges::iota(indices, 0); // Using C++23 std::ranges::iota
ProcessPPMData processor{ raw_data, magic, shift_bit, width, height, image };
// Dispatches to execution policy with constraints verified
transform_pixel_processing(std::forward<ExecutionPolicy>(policy), indices, processor);
return image;
}
// read template function implementation
// Overload fallback avoiding execution policies, instead opting for OpenMP
inline TinyDIP::Image<RGB> read(const std::filesystem::path& file_path, const int outbits = 8)
{
std::ifstream file(file_path, std::ios::binary);
if (!file.is_open())
{
throw std::runtime_error("Could not open file for reading: " + file_path.string());
}
const std::string magic = read_pnm_token(file);
if (magic != "P1" && magic != "P2" && magic != "P3")
{
throw std::runtime_error("Unsupported image format. Magic number found: " + magic);
}
const std::size_t width = std::stoull(read_pnm_token(file));
const std::size_t height = std::stoull(read_pnm_token(file));
int max_value = 1;
if (magic != "P1")
{
max_value = std::stoi(read_pnm_token(file));
}
const int in_bits = static_cast<int>(std::log2(max_value + 1));
const int shift_bit = outbits - in_bits;
const std::size_t pixel_count = width * height;
const std::size_t expected_values = (magic == "P3") ? (pixel_count * 3) : pixel_count;
std::vector<int> raw_data;
raw_data.reserve(expected_values);
for (std::size_t i = 0; i < expected_values; ++i)
{
std::string token = read_pnm_token(file);
if (token.empty())
{
throw std::runtime_error("Unexpected end of file while reading PNM data.");
}
raw_data.emplace_back(std::stoi(token));
}
TinyDIP::Image<RGB> image(width, height);
std::vector<std::size_t> indices(pixel_count);
std::ranges::iota(indices, 0); // Using C++23 std::ranges::iota
ProcessPPMData processor{ raw_data, magic, shift_bit, width, height, image };
// Dispatch explicitly to the OpenMP implementation
transform_pixel_processing_omp(indices, processor);
return image;
}
// -------------------------------------------------------------------------
// write function implementation
// This function writes an Image<RGB> to a PNM file with specified magic number
// Modern write_pnm for exporting Image<RGB> to PNM files
// -------------------------------------------------------------------------
inline void write(
const TinyDIP::Image<RGB>& image,
const std::filesystem::path& file_path,
const std::string& magic = "P3",
const int max_value = 255)
{
std::ofstream file(file_path, std::ios::binary);
if (!file.is_open())
{
throw std::runtime_error("Could not open file for writing: " + file_path.string());
}
if (magic != "P1" && magic != "P2" && magic != "P3")
{
throw std::invalid_argument("Unsupported magic number for writing. Please use P1, P2, or P3.");
}
const std::size_t width = image.getWidth();
const std::size_t height = image.getHeight();
// Write header information
file << magic << '\n';
file << width << ' ' << height << '\n';
if (magic != "P1")
{
file << max_value << '\n';
}
// Write pixel data sequentially mapped top-to-bottom
for (std::size_t y = 0; y < height; ++y)
{
// Must flip y-axis back to match the standard PPM specification
const std::size_t flipped_y = height - 1 - y;
for (std::size_t x = 0; x < width; ++x)
{
const RGB& pixel = image.at_without_boundary_check(x, flipped_y);
if (magic == "P1")
{
// In P1, '1' traditionally corresponds to black pixel (0 intensity)
const int val = (pixel.channels[0] == 0) ? 1 : 0;
file << val << '\n';
}
else if (magic == "P2")
{
// In P2, write the first channel (grayscale)
file << +pixel.channels[0] << '\n';
}
else if (magic == "P3")
{
// In P3, write all three channels (RGB)
file << +pixel.channels[0] << ' '
<< +pixel.channels[1] << ' '
<< +pixel.channels[2] << '\n';
}
}
}
}
}
int hsv_write_detail(const char* const filename, const int xsize, const int ysize, const double* const image);
int hsv_write(const char* const filename, Image<HSV> input);
Image<HSV> hsv_read(const char* const filename, const bool extension);
}
#endif