colordom 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e428a11ebd273b9e3f8867468f74eff34cc681426e97133ec4cbce666c9006ce
4
+ data.tar.gz: e7d31a241c15cdd96b078f60ae8ae302d81206f691b0d50ff8208b2d526803e9
5
+ SHA512:
6
+ metadata.gz: 5545da4d90450efee71fb4b1d078760d4820a703497a2cc7c3ba785f6be6f8caef49e218dcf011052c8ee6affbb1cf6b736b5be5210e0209ef4d5179a3ff73e1
7
+ data.tar.gz: 78350ba55457fc55e4429854b343a10a639137a8daeb3379e431425da93d48580bce4efed1707c744dd911a56b160664c0db6980eebe20802238d7e3d4ee3211
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
10
+
11
+ # Added by cargo
12
+
13
+ /target
14
+ Cargo.lock
15
+
16
+ /lib/*.so
17
+ /mkmf.log
data/.travis.yml ADDED
@@ -0,0 +1,13 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.7.2
6
+ env:
7
+ global:
8
+ - RUST_VERSION=stable
9
+ before_install:
10
+ - if [ ! -e "$HOME/.cargo/bin" ]; then curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain $RUST_VERSION -y; fi
11
+ - export PATH="$HOME/.cargo/bin:$PATH"
12
+ - rustup default $RUST_VERSION
13
+ - gem install bundler -v 2.1.4
data/Cargo.toml ADDED
@@ -0,0 +1,25 @@
1
+ [package]
2
+ name = "colordom"
3
+ version = "0.1.0"
4
+ authors = ["Jonian Guveli <jonian@hardpixel.eu>"]
5
+ edition = "2018"
6
+
7
+ # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8
+ [dependencies]
9
+ image = "0.24"
10
+ dominant_color = "0.3"
11
+ palette_extract = "0.1"
12
+
13
+ [dependencies.kmeans_colors]
14
+ version = "0.5"
15
+ default-features = false
16
+ features = ["palette_color"]
17
+
18
+ [dependencies.palette]
19
+ version = "0.6"
20
+ default-features = false
21
+ features = ["std"]
22
+
23
+ [lib]
24
+ name = "colordom"
25
+ crate-type = ["cdylib"]
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in colordom.gemspec
4
+ gemspec
5
+
6
+ gem 'benchmark-ips'
7
+ gem 'benchmark-memory'
8
+ gem 'camalian'
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 jonian
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,53 @@
1
+ # Colordom
2
+
3
+ Ruby gem to extract color palettes from images implemented in Rust. Rust must be available on your system to install this gem.
4
+
5
+ [![Gem Version](https://badge.fury.io/rb/colordom.svg)](https://badge.fury.io/rb/colordom)
6
+ [![Build Status](https://travis-ci.org/hardpixel/colordom.svg?branch=master)](https://travis-ci.org/hardpixel/colordom)
7
+ [![Maintainability](https://api.codeclimate.com/v1/badges/7e307214d3c2e4d2056d/maintainability)](https://codeclimate.com/github/hardpixel/colordom/maintainability)
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'colordom'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle install
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install colordom
24
+
25
+ ## Usage
26
+
27
+ ```ruby
28
+ require 'colordom'
29
+
30
+ # Get colors using histogram algorithm
31
+ Colordom.histogram(image_path)
32
+
33
+ # Get colors using median cut algorithm
34
+ Colordom.mediancut(image_path)
35
+
36
+ # Get colors using kmeans algorithm
37
+ Colordom.kmeans(image_path)
38
+ ```
39
+
40
+ ## Development
41
+
42
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
43
+
44
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
45
+
46
+ ## Contributing
47
+
48
+ Bug reports and pull requests are welcome on GitHub at https://github.com/hardpixel/colordom.
49
+
50
+
51
+ ## License
52
+
53
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,13 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rake/testtask'
3
+ require 'thermite/tasks'
4
+
5
+ Thermite::Tasks.new
6
+
7
+ Rake::TestTask.new(:test) do |t|
8
+ t.libs << 'test'
9
+ t.libs << 'lib'
10
+ t.test_files = FileList['test/**/*_test.rb']
11
+ end
12
+
13
+ task default: %w[thermite:build test]
data/bin/benchmark ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+
5
+ require 'benchmark/ips'
6
+ require 'benchmark/memory'
7
+
8
+ require 'colordom'
9
+ require 'camalian'
10
+
11
+ COUNT = 5
12
+ IMAGE = File.join(__dir__, '..', 'samples/sample.png')
13
+
14
+ def camalian(quant)
15
+ img = Camalian::load(IMAGE)
16
+ img.prominent_colors(COUNT, quantization: quant)
17
+ end
18
+
19
+ reports = lambda do |x|
20
+ x.report('colordom (HST)') do
21
+ Colordom.histogram(IMAGE, COUNT)
22
+ end
23
+
24
+ x.report('colordom (MCQ)') do
25
+ Colordom.mediancut(IMAGE, COUNT)
26
+ end
27
+
28
+ x.report('colordom (KMS)') do
29
+ Colordom.kmeans(IMAGE, COUNT)
30
+ end
31
+
32
+ x.report('camalian (HST)') do
33
+ camalian(Camalian::QUANTIZATION_HISTOGRAM)
34
+ end
35
+
36
+ x.report('camalian (MCQ)') do
37
+ camalian(Camalian::QUANTIZATION_MEDIAN_CUT)
38
+ end
39
+
40
+ x.report('camalian (KMS)') do
41
+ camalian(Camalian::QUANTIZATION_K_MEANS)
42
+ end
43
+ end
44
+
45
+ Benchmark.ips do |x|
46
+ reports.call(x)
47
+ x.compare!
48
+ end
49
+
50
+ Benchmark.memory do |x|
51
+ reports.call(x)
52
+ x.compare!
53
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'colordom'
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require 'pry'
11
+ # Pry.start
12
+
13
+ require 'irb'
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/colordom.gemspec ADDED
@@ -0,0 +1,29 @@
1
+ require_relative 'lib/colordom/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = 'colordom'
5
+ spec.version = Colordom::VERSION
6
+ spec.authors = ['Jonian Guveli']
7
+ spec.email = ['jonian@hardpixel.eu']
8
+
9
+ spec.summary = %q{Ruby wrapper for dominant color utilities in Rust}
10
+ spec.description = %q{This project is a wrapper for dominant color utilities implemented in Rust.}
11
+ spec.homepage = 'https://github.com/hardpixel/colordom'
12
+ spec.license = 'MIT'
13
+
14
+ # Specify which files should be added to the gem when it is released.
15
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
16
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
17
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|samples)/}) }
18
+ end
19
+
20
+ spec.extensions = ['ext/Rakefile']
21
+ spec.require_paths = ['lib']
22
+
23
+ spec.add_runtime_dependency 'ffi'
24
+ spec.add_runtime_dependency 'thermite'
25
+
26
+ spec.add_development_dependency 'bundler', '~> 2.0'
27
+ spec.add_development_dependency 'minitest', '~> 5.0'
28
+ spec.add_development_dependency 'rake', '~> 13.0'
29
+ end
data/ext/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'thermite/tasks'
2
+
3
+ project_dir = File.dirname(File.dirname(__FILE__))
4
+
5
+ Thermite::Tasks.new(
6
+ cargo_project_path: project_dir,
7
+ ruby_project_path: project_dir
8
+ )
9
+
10
+ task default: %w[thermite:build]
@@ -0,0 +1,27 @@
1
+ module Colordom
2
+ class Color
3
+ attr_reader :r, :g, :b
4
+
5
+ def initialize(red, green, blue)
6
+ @r, @g, @b = [red, green, blue].map(&:to_i)
7
+ end
8
+
9
+ def ==(other)
10
+ other.is_a?(self.class) &&
11
+ rgb == other.rgb
12
+ end
13
+
14
+ def rgb
15
+ [r, g, b]
16
+ end
17
+
18
+ def hex
19
+ rgb.inject('#') do |str, val|
20
+ str + val.to_s(16).rjust(2, '0').upcase
21
+ end
22
+ end
23
+
24
+ alias to_rgb rgb
25
+ alias to_hex hex
26
+ end
27
+ end
@@ -0,0 +1,4 @@
1
+ module Colordom
2
+ class Error < StandardError
3
+ end
4
+ end
@@ -0,0 +1,16 @@
1
+ module Colordom
2
+ module Native
3
+ extend FFI::Library
4
+
5
+ LIBNAME = "colordom.#{FFI::Platform::LIBSUFFIX}".freeze
6
+ LIBPATH = File.expand_path('..', __dir__).freeze
7
+
8
+ ffi_lib File.expand_path(LIBNAME, LIBPATH)
9
+
10
+ attach_function :to_histogram, :to_histogram, [:string], Result
11
+ attach_function :to_mediancut, :to_mediancut, [:string, :uint8], Result
12
+ attach_function :to_kmeans, :to_kmeans, [:string, :uint8], Result
13
+
14
+ attach_function :free, :free_result, [Result], :void
15
+ end
16
+ end
@@ -0,0 +1,9 @@
1
+ module Colordom
2
+ class Result < FFI::AutoPointer
3
+ class << self
4
+ def release(ptr)
5
+ Native.free(ptr)
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,3 @@
1
+ module Colordom
2
+ VERSION = '0.1.0'.freeze
3
+ end
data/lib/colordom.rb ADDED
@@ -0,0 +1,56 @@
1
+ require 'ffi'
2
+
3
+ require 'colordom/result'
4
+ require 'colordom/native'
5
+ require 'colordom/error'
6
+ require 'colordom/color'
7
+ require 'colordom/version'
8
+
9
+ module Colordom
10
+ class << self
11
+ def histogram(path, max_colors = 5)
12
+ regex = /(\d+), (\d+), (\d+)/
13
+ value = call(:to_histogram, path)
14
+
15
+ parse(value, regex, max_colors)
16
+ end
17
+
18
+ def mediancut(path, max_colors = 5)
19
+ regex = /r: (\d+), g: (\d+), b: (\d+)/
20
+ value = call(:to_mediancut, path, max_colors)
21
+
22
+ parse(value, regex, max_colors)
23
+ end
24
+
25
+ def kmeans(path, max_colors = 5)
26
+ regex = /red: (\d+), green: (\d+), blue: (\d+)/
27
+ value = call(:to_kmeans, path, max_colors)
28
+
29
+ parse(value, regex)
30
+ end
31
+
32
+ private
33
+
34
+ def call(method, path, *args)
35
+ return if path.nil?
36
+
37
+ result = Native.send(method, path, *args)
38
+ result = result.read_string.force_encoding('UTF-8')
39
+
40
+ raise Error, result if result.start_with?(Error.name)
41
+
42
+ result
43
+ end
44
+
45
+ def parse(result, regex, limit = nil)
46
+ return [] if result.nil?
47
+
48
+ colors = result.scan(regex)
49
+ colors = colors.first(limit) if limit && limit.positive?
50
+
51
+ colors.map do |values|
52
+ Color.new(*values)
53
+ end
54
+ end
55
+ end
56
+ end
data/src/lib.rs ADDED
@@ -0,0 +1,100 @@
1
+ use std::os::raw::c_char;
2
+ use std::ffi::{CStr, CString};
3
+
4
+ use image;
5
+ use dominant_color;
6
+ use kmeans_colors;
7
+
8
+ use palette_extract::{Quality, MaxColors, PixelEncoding, PixelFilter};
9
+ use palette::{FromColor, IntoColor, Lab, Pixel, Srgb};
10
+
11
+ fn to_string(unsafe_string: *const c_char) -> String {
12
+ unsafe { CStr::from_ptr(unsafe_string) }.to_str().unwrap().to_string()
13
+ }
14
+
15
+ fn to_char(string: String) -> *mut c_char {
16
+ CString::new(string).unwrap().into_raw()
17
+ }
18
+
19
+ #[no_mangle]
20
+ pub extern "C" fn to_histogram(path: *const c_char) -> *mut c_char {
21
+ let img = match image::open(&to_string(path)) {
22
+ Ok(res) => res,
23
+ Err(ex) => return to_char(format!("Colordom::Error {:?}", ex.to_string()))
24
+ };
25
+
26
+
27
+ let has_alpha = match img.color() {
28
+ image::ColorType::Rgba8 => true,
29
+ image::ColorType::Rgba16 => true,
30
+ image::ColorType::Rgba32F => true,
31
+ _ => false
32
+ };
33
+
34
+ let pixels = img.as_bytes();
35
+ let result = dominant_color::get_colors(&pixels, has_alpha);
36
+
37
+ return to_char(format!("{:?}", result));
38
+ }
39
+
40
+ #[no_mangle]
41
+ pub extern "C" fn to_mediancut(path: *const c_char, max_colors: u8) -> *mut c_char {
42
+ let img = match image::open(&to_string(path)) {
43
+ Ok(res) => res,
44
+ Err(ex) => return to_char(format!("Colordom::Error {:?}", ex.to_string()))
45
+ };
46
+
47
+ let pixels = img.as_bytes();
48
+ let result = palette_extract::get_palette_with_options(
49
+ &pixels,
50
+ PixelEncoding::Rgb,
51
+ Quality::default(),
52
+ MaxColors::new(max_colors),
53
+ PixelFilter::None
54
+ );
55
+
56
+ return to_char(format!("{:?}", result))
57
+ }
58
+
59
+ #[no_mangle]
60
+ pub extern "C" fn to_kmeans(path: *const c_char, max_colors: u8) -> *mut c_char {
61
+ let img = match image::open(&to_string(path)) {
62
+ Ok(res) => res,
63
+ Err(ex) => return to_char(format!("Colordom::Error {:?}", ex.to_string()))
64
+ };
65
+
66
+ let pixels = img.as_bytes();
67
+ let max_iterations = 20;
68
+ let converge = 1.0;
69
+ let verbose = false;
70
+ let seed: u64 = 0;
71
+
72
+ let lab: Vec<Lab> = Srgb::from_raw_slice(&pixels)
73
+ .iter()
74
+ .map(|x| x.into_format().into_color())
75
+ .collect();
76
+
77
+ let run_result = kmeans_colors::get_kmeans_hamerly(
78
+ max_colors.into(),
79
+ max_iterations,
80
+ converge,
81
+ verbose,
82
+ &lab,
83
+ seed
84
+ );
85
+
86
+ let result = &run_result.centroids
87
+ .iter()
88
+ .map(|x| Srgb::from_color(*x).into_format())
89
+ .collect::<Vec<Srgb<u8>>>();
90
+
91
+ return to_char(format!("{:?}", result))
92
+ }
93
+
94
+ #[no_mangle]
95
+ pub extern "C" fn free_result(string: *mut c_char) {
96
+ unsafe {
97
+ if string.is_null() { return }
98
+ CString::from_raw(string)
99
+ };
100
+ }
metadata ADDED
@@ -0,0 +1,134 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: colordom
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jonian Guveli
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-05-19 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: ffi
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: thermite
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '5.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '5.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rake
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '13.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '13.0'
83
+ description: This project is a wrapper for dominant color utilities implemented in
84
+ Rust.
85
+ email:
86
+ - jonian@hardpixel.eu
87
+ executables: []
88
+ extensions:
89
+ - ext/Rakefile
90
+ extra_rdoc_files: []
91
+ files:
92
+ - ".gitignore"
93
+ - ".travis.yml"
94
+ - Cargo.toml
95
+ - Gemfile
96
+ - LICENSE.txt
97
+ - README.md
98
+ - Rakefile
99
+ - bin/benchmark
100
+ - bin/console
101
+ - bin/setup
102
+ - colordom.gemspec
103
+ - ext/Rakefile
104
+ - lib/colordom.rb
105
+ - lib/colordom/color.rb
106
+ - lib/colordom/error.rb
107
+ - lib/colordom/native.rb
108
+ - lib/colordom/result.rb
109
+ - lib/colordom/version.rb
110
+ - src/lib.rs
111
+ homepage: https://github.com/hardpixel/colordom
112
+ licenses:
113
+ - MIT
114
+ metadata: {}
115
+ post_install_message:
116
+ rdoc_options: []
117
+ require_paths:
118
+ - lib
119
+ required_ruby_version: !ruby/object:Gem::Requirement
120
+ requirements:
121
+ - - ">="
122
+ - !ruby/object:Gem::Version
123
+ version: '0'
124
+ required_rubygems_version: !ruby/object:Gem::Requirement
125
+ requirements:
126
+ - - ">="
127
+ - !ruby/object:Gem::Version
128
+ version: '0'
129
+ requirements: []
130
+ rubygems_version: 3.1.6
131
+ signing_key:
132
+ specification_version: 4
133
+ summary: Ruby wrapper for dominant color utilities in Rust
134
+ test_files: []