okmain 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b1c82cf5cfc87c588329a84ccb9b8118f7f27d7818a45150b021310dc28e2049
4
+ data.tar.gz: bef38f1590b89386ec4c8c9287edb55b5bb08255c787ec7b75d3ac45a6a81580
5
+ SHA512:
6
+ metadata.gz: dba390c347ccd57cd71ee46b03ae5699614c6754802e8c465cf700025d078eeca8982374a575705f810469801190310e14c11c379df2808b6cce6a8eff13e0d3
7
+ data.tar.gz: b740152ded762d8bea52e83d81ee6eab78aab7ccc3a41ecbdf1be6e253051315dbd3f92fe553dc8df609adf0dcf7027ad7842c97cc54d7993dcbf7161b72d33e
data/LICENSE-APACHE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
data/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 okmain-ruby contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # okmain
2
+
3
+ A Ruby gem that extracts dominant colors from images using adaptive K-means clustering in the [Oklab](https://bottosson.github.io/posts/oklab/) perceptual color space.
4
+
5
+ This is a port of the Rust [okmain](https://github.com/si14/okmain) crate by [Dan Groshev](https://github.com/si14). See also his [blog post](https://dgroshev.com/blog/okmain/) about the project.
6
+
7
+ ## Installation
8
+
9
+ Add to your Gemfile:
10
+
11
+ ```ruby
12
+ gem "okmain"
13
+ ```
14
+
15
+ Or install directly:
16
+
17
+ ```
18
+ gem install okmain
19
+ ```
20
+
21
+ Requires [libvips](https://www.libvips.org/) to be installed on your system:
22
+
23
+ ```
24
+ # macOS
25
+ brew install vips
26
+
27
+ # Debian/Ubuntu
28
+ apt install libvips-dev
29
+
30
+ # Fedora
31
+ dnf install vips-devel
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ```ruby
37
+ require "okmain"
38
+
39
+ # Extract up to 4 dominant colors from an image file
40
+ colors = Okmain.colors("photo.jpg")
41
+ # => [[r, g, b], [r, g, b], ...]
42
+
43
+ # Also accepts a Vips::Image
44
+ require "vips"
45
+ image = Vips::Image.new_from_file("photo.jpg")
46
+ colors = Okmain.colors(image)
47
+
48
+ # Customize scoring weights
49
+ config = Okmain::Config.new(
50
+ chroma_weight: 0.5, # weight for color vividness (default: 0.7)
51
+ mask_weighted_counts_weight: 0.5 # weight for pixel count/position (default: 0.3)
52
+ )
53
+ colors = Okmain.colors("photo.jpg", config: config)
54
+ ```
55
+
56
+ Colors are returned as `[r, g, b]` arrays (0-255), sorted by score descending. The number of colors returned (up to 4) is determined adaptively — similar clusters are merged.
57
+
58
+ ## How it works
59
+
60
+ 1. **Sample** — Large images are block-averaged down to ~250k pixels using libvips, then converted from sRGB to Oklab
61
+ 2. **Cluster** — Adaptive K-means in Oklab space (K-means++ initialization, Lloyd's iterations, merging similar centroids)
62
+ 3. **Score** — Centroids ranked by a weighted combination of pixel count (with center-priority mask) and chroma
63
+ 4. **Return** — Up to 4 `[r, g, b]` arrays sorted by score
64
+
65
+ ## Credits
66
+
67
+ Based on the Rust [okmain](https://github.com/si14/okmain) crate (v0.2.0) by Dan Groshev and okmain contributors.
68
+
69
+ ## License
70
+
71
+ Licensed under either of
72
+
73
+ - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
74
+ - MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
75
+
76
+ at your option.
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Okmain
4
+ class Config
5
+ attr_reader :chroma_weight, :mask_weighted_counts_weight
6
+
7
+ def initialize(chroma_weight: 0.7, mask_weighted_counts_weight: 0.3)
8
+ raise ArgumentError, "chroma_weight must be between 0 and 1" unless (0.0..1.0).cover?(chroma_weight)
9
+ raise ArgumentError, "mask_weighted_counts_weight must be between 0 and 1" unless (0.0..1.0).cover?(mask_weighted_counts_weight)
10
+
11
+ @chroma_weight = chroma_weight.to_f
12
+ @mask_weighted_counts_weight = mask_weighted_counts_weight.to_f
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Okmain
4
+ module DistanceMask
5
+ SATURATED_THRESHOLD = 0.75
6
+
7
+ module_function
8
+
9
+ # Returns a flat Array of mask values (0.1..1.0) for each pixel, matching Rust's rectangular mask.
10
+ # Center pixels get 1.0, corner pixels get 0.1, with a linear ramp.
11
+ def compute(width, height)
12
+ half_w = width * 0.5
13
+ half_h = height * 0.5
14
+ x_threshold = half_w * SATURATED_THRESHOLD
15
+ y_threshold = half_h * SATURATED_THRESHOLD
16
+
17
+ mask = Array.new(width * height)
18
+ y = 0
19
+ while y < height
20
+ # Distance from nearest y-edge (0 at edge, half_h at center)
21
+ my = y < half_h ? y.to_f : (height - 1 - y).to_f
22
+ y_contrib = if y_threshold > 0.0
23
+ v = 0.1 + 0.9 * (my / y_threshold)
24
+ v < 1.0 ? v : 1.0
25
+ else
26
+ 1.0
27
+ end
28
+
29
+ row_offset = y * width
30
+ x = 0
31
+ while x < width
32
+ # Distance from nearest x-edge (0 at edge, half_w at center)
33
+ mx = x < half_w ? x.to_f : (width - 1 - x).to_f
34
+ x_contrib = if x_threshold > 0.0
35
+ v = 0.1 + 0.9 * (mx / x_threshold)
36
+ v < 1.0 ? v : 1.0
37
+ else
38
+ 1.0
39
+ end
40
+
41
+ mask[row_offset + x] = x_contrib < y_contrib ? x_contrib : y_contrib
42
+ x += 1
43
+ end
44
+ y += 1
45
+ end
46
+
47
+ mask
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,176 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Okmain
4
+ module KMeans
5
+ MAX_CENTROIDS = 4
6
+ LLOYDS_MAX_ITERATIONS = 300
7
+ LLOYDS_CONVERGENCE_TOL = 1e-3
8
+ SIMILAR_CLUSTER_DISTANCE_SQ = 0.005
9
+ KMEANSPP_CANDIDATES = 3
10
+
11
+ module_function
12
+
13
+ # Returns [centroids, assignments] where centroids is Array of [L, a, b]
14
+ # and assignments is Array of centroid indices per pixel.
15
+ def cluster(pixels, k: MAX_CENTROIDS)
16
+ rng = Random.new(42)
17
+ n = pixels.size
18
+ return [pixels.dup, Array.new(n) { |i| i }] if n <= k
19
+
20
+ loop do
21
+ centroids = init_plusplus(pixels, k, rng)
22
+ assignments = Array.new(n, 0)
23
+
24
+ centroids, assignments = lloyds(pixels, centroids, assignments, k, rng)
25
+
26
+ # Adaptive reduction: merge similar centroids
27
+ merged = false
28
+ i = 0
29
+ while i < k - 1 && !merged
30
+ j = i + 1
31
+ while j < k && !merged
32
+ if distance_sq(centroids[i], centroids[j]) < SIMILAR_CLUSTER_DISTANCE_SQ
33
+ k -= 1
34
+ merged = true
35
+ end
36
+ j += 1
37
+ end
38
+ i += 1
39
+ end
40
+
41
+ return [centroids, assignments] unless merged
42
+ end
43
+ end
44
+
45
+ # K-means++ initialization with 3 candidates per step
46
+ def init_plusplus(pixels, k, rng)
47
+ n = pixels.size
48
+ centroids = [pixels[rng.rand(n)].dup]
49
+
50
+ dist_sq = Array.new(n, Float::INFINITY)
51
+
52
+ (1...k).each do
53
+ # Update distances to nearest centroid
54
+ last = centroids.last
55
+ i = 0
56
+ while i < n
57
+ d = distance_sq(pixels[i], last)
58
+ dist_sq[i] = d if d < dist_sq[i]
59
+ i += 1
60
+ end
61
+
62
+ total = dist_sq.sum
63
+ best_candidate = nil
64
+ best_potential = Float::INFINITY
65
+
66
+ KMEANSPP_CANDIDATES.times do
67
+ # Weighted random selection
68
+ r = rng.rand * total
69
+ cumulative = 0.0
70
+ idx = 0
71
+ while idx < n
72
+ cumulative += dist_sq[idx]
73
+ if cumulative >= r
74
+ break
75
+ end
76
+ idx += 1
77
+ end
78
+ idx = n - 1 if idx >= n
79
+
80
+ # Compute potential for this candidate
81
+ candidate = pixels[idx]
82
+ potential = 0.0
83
+ i = 0
84
+ while i < n
85
+ d = distance_sq(pixels[i], candidate)
86
+ potential += d < dist_sq[i] ? d : dist_sq[i]
87
+ i += 1
88
+ end
89
+
90
+ if potential < best_potential
91
+ best_potential = potential
92
+ best_candidate = candidate
93
+ end
94
+ end
95
+
96
+ centroids << best_candidate.dup
97
+ end
98
+
99
+ centroids
100
+ end
101
+
102
+ def lloyds(pixels, centroids, assignments, k, rng)
103
+ n = pixels.size
104
+
105
+ LLOYDS_MAX_ITERATIONS.times do
106
+ # Assignment step
107
+ i = 0
108
+ while i < n
109
+ px = pixels[i]
110
+ best = 0
111
+ best_d = distance_sq(px, centroids[0])
112
+ c = 1
113
+ while c < k
114
+ d = distance_sq(px, centroids[c])
115
+ if d < best_d
116
+ best_d = d
117
+ best = c
118
+ end
119
+ c += 1
120
+ end
121
+ assignments[i] = best
122
+ i += 1
123
+ end
124
+
125
+ # Update step
126
+ new_centroids = Array.new(k) { [0.0, 0.0, 0.0] }
127
+ counts = Array.new(k, 0)
128
+
129
+ i = 0
130
+ while i < n
131
+ c = assignments[i]
132
+ px = pixels[i]
133
+ nc = new_centroids[c]
134
+ nc[0] += px[0]
135
+ nc[1] += px[1]
136
+ nc[2] += px[2]
137
+ counts[c] += 1
138
+ i += 1
139
+ end
140
+
141
+ shift_sq = 0.0
142
+ c = 0
143
+ while c < k
144
+ if counts[c] == 0
145
+ # Reassign empty cluster to random data point
146
+ ri = rng.rand(n)
147
+ new_centroids[c] = pixels[ri].dup
148
+ else
149
+ inv = 1.0 / counts[c]
150
+ nc = new_centroids[c]
151
+ nc[0] *= inv
152
+ nc[1] *= inv
153
+ nc[2] *= inv
154
+ end
155
+ dl = new_centroids[c][0] - centroids[c][0]
156
+ da = new_centroids[c][1] - centroids[c][1]
157
+ db = new_centroids[c][2] - centroids[c][2]
158
+ shift_sq += dl * dl + da * da + db * db
159
+ c += 1
160
+ end
161
+
162
+ centroids = new_centroids
163
+ break if shift_sq < LLOYDS_CONVERGENCE_TOL
164
+ end
165
+
166
+ [centroids, assignments]
167
+ end
168
+
169
+ def distance_sq(a, b)
170
+ dl = a[0] - b[0]
171
+ da = a[1] - b[1]
172
+ db = a[2] - b[2]
173
+ dl * dl + da * da + db * db
174
+ end
175
+ end
176
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Okmain
4
+ module Oklab
5
+ module_function
6
+
7
+ # Linear RGB (0..1) → Oklab [L, a, b]
8
+ def linear_rgb_to_oklab(r, g, b)
9
+ l_ = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b
10
+ m_ = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b
11
+ s_ = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b
12
+
13
+ l_cbrt = Math.cbrt(l_)
14
+ m_cbrt = Math.cbrt(m_)
15
+ s_cbrt = Math.cbrt(s_)
16
+
17
+ l = 0.2104542553 * l_cbrt + 0.7936177850 * m_cbrt - 0.0040720468 * s_cbrt
18
+ a = 1.9779984951 * l_cbrt - 2.4285922050 * m_cbrt + 0.4505937099 * s_cbrt
19
+ b_ = 0.0259040371 * l_cbrt + 0.7827717662 * m_cbrt - 0.8086757660 * s_cbrt
20
+
21
+ [l, a, b_]
22
+ end
23
+
24
+ # Oklab [L, a, b] → linear RGB (0..1)
25
+ def oklab_to_linear_rgb(l, a, b)
26
+ l_ = l + 0.3963377774 * a + 0.2158037573 * b
27
+ m_ = l - 0.1055613458 * a - 0.0638541728 * b
28
+ s_ = l - 0.0894841775 * a - 1.2914855480 * b
29
+
30
+ l_cubed = l_ * l_ * l_
31
+ m_cubed = m_ * m_ * m_
32
+ s_cubed = s_ * s_ * s_
33
+
34
+ r = 4.0767416621 * l_cubed - 3.3077115913 * m_cubed + 0.2309699292 * s_cubed
35
+ g = -1.2684380046 * l_cubed + 2.6097574011 * m_cubed - 0.3413193965 * s_cubed
36
+ b_ = -0.0041960863 * l_cubed - 0.7034186147 * m_cubed + 1.7076147010 * s_cubed
37
+
38
+ [r, g, b_]
39
+ end
40
+
41
+ # sRGB component (0..255) → linear (0..1)
42
+ def srgb_to_linear(c)
43
+ c = c / 255.0
44
+ if c <= 0.04045
45
+ c / 12.92
46
+ else
47
+ ((c + 0.055) / 1.055)**2.4
48
+ end
49
+ end
50
+
51
+ # Linear (0..1) → sRGB component (0..255), clamped
52
+ def linear_to_srgb(c)
53
+ c = c.clamp(0.0, 1.0)
54
+ c = if c <= 0.0031308
55
+ 12.92 * c
56
+ else
57
+ 1.055 * (c**(1.0 / 2.4)) - 0.055
58
+ end
59
+ (c * 255.0).round.clamp(0, 255)
60
+ end
61
+
62
+ # Oklab → sRGB [r, g, b] (0..255)
63
+ def oklab_to_srgb8(l, a, b)
64
+ r, g, b_ = oklab_to_linear_rgb(l, a, b)
65
+ [linear_to_srgb(r), linear_to_srgb(g), linear_to_srgb(b_)]
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "vips"
4
+
5
+ module Okmain
6
+ module Sampler
7
+ MAX_SAMPLE_SIZE = 250_000
8
+
9
+ module_function
10
+
11
+ # Returns [pixels, width, height] where pixels is an Array of [L, a, b] triples.
12
+ def sample(input)
13
+ image = if input.is_a?(Vips::Image)
14
+ input
15
+ else
16
+ Vips::Image.new_from_file(input.to_s, access: :sequential)
17
+ end
18
+
19
+ # Flatten alpha to white background
20
+ image = image.flatten(background: [255, 255, 255]) if image.has_alpha?
21
+
22
+ # Convert to scRGB (linear float) for accurate block averaging
23
+ image = image.colourspace(:scrgb)
24
+
25
+ total = image.width * image.height
26
+ block_size = compute_block_size(total)
27
+
28
+ if block_size > 1
29
+ image = image.shrink(block_size, block_size)
30
+ end
31
+
32
+ width = image.width
33
+ height = image.height
34
+
35
+ # Extract float pixel data [r, g, b] in linear space
36
+ floats = image.write_to_memory.unpack("f*")
37
+ bands = image.bands
38
+ pixel_count = width * height
39
+
40
+ pixels = Array.new(pixel_count)
41
+ i = 0
42
+ while i < pixel_count
43
+ offset = i * bands
44
+ r = floats[offset]
45
+ g = floats[offset + 1]
46
+ b = floats[offset + 2]
47
+ pixels[i] = Oklab.linear_rgb_to_oklab(r, g, b)
48
+ i += 1
49
+ end
50
+
51
+ [pixels, width, height]
52
+ end
53
+
54
+ def compute_block_size(total)
55
+ return 1 if total <= MAX_SAMPLE_SIZE
56
+
57
+ bs = Math.sqrt(total.to_f / MAX_SAMPLE_SIZE).ceil
58
+ # Round up to multiple of 4
59
+ remainder = bs % 4
60
+ bs += (4 - remainder) if remainder != 0
61
+ bs
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Okmain
4
+ module Scorer
5
+ MAX_SRGB_OKLAB_CHROMA = 0.32
6
+
7
+ module_function
8
+
9
+ # Returns Array of [r, g, b] (0..255) sorted by score descending.
10
+ def score(centroids, assignments, mask, config)
11
+ k = centroids.size
12
+ n = assignments.size
13
+ mask_w = config.mask_weighted_counts_weight
14
+ chroma_w = config.chroma_weight
15
+
16
+ # Weighted counts per centroid
17
+ weighted_counts = Array.new(k, 0.0)
18
+ i = 0
19
+ while i < n
20
+ c = assignments[i]
21
+ w = 1.0 - mask_w * (1.0 - mask[i])
22
+ weighted_counts[c] += w
23
+ i += 1
24
+ end
25
+
26
+ # Normalize to sum to 1.0
27
+ total = weighted_counts.sum
28
+ if total > 0
29
+ inv = 1.0 / total
30
+ j = 0
31
+ while j < k
32
+ weighted_counts[j] *= inv
33
+ j += 1
34
+ end
35
+ end
36
+
37
+ # Score each centroid
38
+ scored = centroids.each_with_index.map do |centroid, idx|
39
+ chroma = Math.sqrt(centroid[1] * centroid[1] + centroid[2] * centroid[2]) / MAX_SRGB_OKLAB_CHROMA
40
+ score = (1.0 - chroma_w) * weighted_counts[idx] + chroma_w * chroma
41
+ [score, centroid]
42
+ end
43
+
44
+ scored.sort_by! { |s, _| -s }
45
+ scored.map { |_, centroid| Oklab.oklab_to_srgb8(centroid[0], centroid[1], centroid[2]) }
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Okmain
4
+ VERSION = "0.1.0"
5
+ end
data/lib/okmain.rb ADDED
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "okmain/version"
4
+ require_relative "okmain/config"
5
+ require_relative "okmain/oklab"
6
+ require_relative "okmain/sampler"
7
+ require_relative "okmain/distance_mask"
8
+ require_relative "okmain/kmeans"
9
+ require_relative "okmain/scorer"
10
+
11
+ module Okmain
12
+ module_function
13
+
14
+ # Extract up to 4 dominant colors from an image.
15
+ #
16
+ # @param input [String, Vips::Image] file path or preloaded vips image
17
+ # @param config [Okmain::Config] optional scoring config
18
+ # @return [Array<Array<Integer>>] up to 4 [r, g, b] arrays sorted by score
19
+ def colors(input, config: Config.new)
20
+ pixels, width, height = Sampler.sample(input)
21
+ mask = DistanceMask.compute(width, height)
22
+ centroids, assignments = KMeans.cluster(pixels)
23
+ Scorer.score(centroids, assignments, mask, config)
24
+ end
25
+ end
data/okmain.gemspec ADDED
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/okmain/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "okmain"
7
+ spec.version = Okmain::VERSION
8
+ spec.authors = ["Joshua Paine"]
9
+ spec.summary = "Extract dominant colors from images using adaptive K-means in Oklab space"
10
+ spec.homepage = "https://github.com/midnightmonster/okmain-ruby"
11
+ spec.licenses = ["MIT", "Apache-2.0"]
12
+ spec.required_ruby_version = ">= 3.0"
13
+
14
+ spec.metadata["homepage_uri"] = spec.homepage
15
+ spec.metadata["source_code_uri"] = spec.homepage
16
+
17
+ spec.files = Dir["lib/**/*.rb"] + ["okmain.gemspec", "README.md", "LICENSE-MIT", "LICENSE-APACHE"]
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_dependency "ruby-vips", "~> 2.1"
21
+ end
metadata ADDED
@@ -0,0 +1,66 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: okmain
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Joshua Paine
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: ruby-vips
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '2.1'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '2.1'
26
+ executables: []
27
+ extensions: []
28
+ extra_rdoc_files: []
29
+ files:
30
+ - LICENSE-APACHE
31
+ - LICENSE-MIT
32
+ - README.md
33
+ - lib/okmain.rb
34
+ - lib/okmain/config.rb
35
+ - lib/okmain/distance_mask.rb
36
+ - lib/okmain/kmeans.rb
37
+ - lib/okmain/oklab.rb
38
+ - lib/okmain/sampler.rb
39
+ - lib/okmain/scorer.rb
40
+ - lib/okmain/version.rb
41
+ - okmain.gemspec
42
+ homepage: https://github.com/midnightmonster/okmain-ruby
43
+ licenses:
44
+ - MIT
45
+ - Apache-2.0
46
+ metadata:
47
+ homepage_uri: https://github.com/midnightmonster/okmain-ruby
48
+ source_code_uri: https://github.com/midnightmonster/okmain-ruby
49
+ rdoc_options: []
50
+ require_paths:
51
+ - lib
52
+ required_ruby_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '3.0'
57
+ required_rubygems_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ requirements: []
63
+ rubygems_version: 3.6.9
64
+ specification_version: 4
65
+ summary: Extract dominant colors from images using adaptive K-means in Oklab space
66
+ test_files: []