|
| 1 | +#!/usr/bin/env jruby |
| 2 | +# After an idea by Kevin Workman and processing.py example by Jorg Kantel |
| 3 | +# https://happycoding.io/examples/p5js/images/image-palette |
| 4 | +# http://blog.schockwellenreiter.de/2021/08/2021080401.html |
| 5 | + |
| 6 | +require 'picrate' |
| 7 | + |
| 8 | +class ImagePalette < Processing::App |
| 9 | + WIDTH = 800 |
| 10 | + HALF = 400 |
| 11 | + HEIGHT = 640 |
| 12 | + attr_reader :img, :img2, :palette, :pixel_array |
| 13 | + MIN = 999_999 |
| 14 | + WEB = %w[#264653 #2a9d8f #e9c46a #f4a261 #e76f51].freeze |
| 15 | + |
| 16 | + def settings |
| 17 | + size(WIDTH, HEIGHT) |
| 18 | + end |
| 19 | + |
| 20 | + def setup |
| 21 | + sketch_title('Image Palette') |
| 22 | + @img = load_image(data_path('akt.jpg')) |
| 23 | + @img2 = create_image(HALF, height, RGB) |
| 24 | + @palette = web_to_color_array(WEB) |
| 25 | + img.load_pixels |
| 26 | + img2.load_pixels |
| 27 | + no_loop |
| 28 | + end |
| 29 | + |
| 30 | + def draw |
| 31 | + grid(HALF, height) do |x, y| |
| 32 | + img_color = img.pixels[x + y * HALF] |
| 33 | + img2.pixels[x + y * HALF] = get_palette_color(img_color) |
| 34 | + end |
| 35 | + image(img, 0, 0) |
| 36 | + image(img2, HALF, 0) |
| 37 | + end |
| 38 | + |
| 39 | + def get_palette_color(img_color) |
| 40 | + min_distance = MIN |
| 41 | + img_r = img_color >> 16 & 0xFF |
| 42 | + img_g = img_color >> 8 & 0xFF |
| 43 | + img_b = img_color & 0xFF |
| 44 | + target_color = 0 |
| 45 | + palette.each do |c| |
| 46 | + palette_r = c >> 16 & 0xFF |
| 47 | + palette_g = c >> 8 & 0xFF |
| 48 | + palette_b = c & 0xFF |
| 49 | + color_distance = dist(img_r, img_g, img_b, |
| 50 | + palette_r, palette_g, palette_b) |
| 51 | + if color_distance < min_distance |
| 52 | + target_color = c |
| 53 | + min_distance = color_distance |
| 54 | + end |
| 55 | + end |
| 56 | + target_color |
| 57 | + end |
| 58 | +end |
| 59 | + |
| 60 | +ImagePalette.new |
0 commit comments