qualpal 2.3.0
Loading...
Searching...
No Matches
color_difference.h
Go to the documentation of this file.
1
9#pragma once
10
11#include <cmath>
12#include <qualpal/matrix.h>
13#include <qualpal/metrics.h>
14#include <qualpal/threads.h>
15#include <vector>
16
17#ifdef _OPENMP
18#include <omp.h>
19#endif
20
21namespace qualpal {
22namespace detail {
23
24inline std::size_t
25estimateMatrixMemory(std::size_t n)
26{
27 return n * n * sizeof(double);
28}
29
30inline bool
31checkMatrixSize(std::size_t n, double max_gb = 1.0)
32{
33 double estimated_gb = estimateMatrixMemory(n) / (1024.0 * 1024.0 * 1024.0);
34 return estimated_gb <= max_gb;
35}
36} // namespace detail
37
48template<typename ColorType, typename Metric = metrics::DIN99d>
49Matrix<double>
50colorDifferenceMatrix(const std::vector<ColorType>& colors,
51 const Metric& metric = Metric{},
52 const double max_memory = 1)
53{
54 using namespace detail;
55
56 const std::size_t n_colors = colors.size();
57
58 if (n_colors < 1) {
59 throw std::invalid_argument("At least one color is required to compute "
60 "a color difference matrix.");
61 }
62
63 if (!checkMatrixSize(n_colors, max_memory)) {
64 throw std::runtime_error(
65 "Color difference matrix would require " +
66 std::to_string(estimateMatrixMemory(n_colors) /
67 (1024.0 * 1024.0 * 1024.0)) +
68 " GB, which exceeds the limit of " + std::to_string(max_memory) +
69 " GB. Reduce the number of colors or increase the memory limit.");
70 }
71
72 Matrix<double> result(n_colors, n_colors);
73
74#ifdef _OPENMP
75#pragma omp parallel for num_threads(Threads::get())
76#endif
77 for (std::size_t i = 0; i < n_colors; ++i) {
78 result(i, i) = 0.0;
79#ifdef _OPENMP
80#pragma omp simd
81#endif
82 for (std::size_t j = i + 1; j < n_colors; ++j) {
83 double d = metric(colors[i], colors[j]);
84 result(i, j) = d;
85 result(j, i) = d;
86 }
87 }
88 return result;
89}
90
101Matrix<double>
102colorDifferenceMatrix(const std::vector<colors::XYZ>& colors,
103 const metrics::MetricType& metric_type,
104 const double max_memory = 1);
105
106} // namespace qualpal
Matrix classes for qualpal.
Color difference metrics for qualpal.
MetricType
Supported color difference metrics for palette generation.
Definition metrics.h:83
Qualitative color palette generation library.
Definition analyze.h:19
Matrix< double > colorDifferenceMatrix(const std::vector< ColorType > &colors, const Metric &metric=Metric{}, const double max_memory=1)
Generate a color difference matrix.
Thread management for parallel computations.