Skip to content

Instantly share code, notes, and snippets.

@rogerbraun
Created September 28, 2011 01:15
Show Gist options
  • Save rogerbraun/1246753 to your computer and use it in GitHub Desktop.
Save rogerbraun/1246753 to your computer and use it in GitHub Desktop.
Codebrawl 10 blog post
module ChunkyPNG::Color
# See http://en.wikipedia.org/wiki/Hue#Computing_hue_from_RGB
def self.hue(pixel)
r, g, b = r(pixel), g(pixel), b(pixel)
return 0 if r == b and b == g
((180 / Math::PI * Math.atan2((2 * r) - g - b, Math.sqrt(3) * (g - b))) - 90) % 360
end
# The modular distance, as the hue is circular
def self.distance(pixel, poxel)
hue_pixel, hue_poxel = hue(pixel), hue(poxel)
[(hue_pixel - hue_poxel) % 360, (hue_poxel - hue_pixel) % 360].min
end
end
module SelectiveColor
# Really simple, just change the pixels to grayscale if their distance to a
# reference hue is larger than a delta value.
def to_selective_color!(reference, delta)
pixels.map!{|pixel| ChunkyPNG::Color.distance(pixel, reference) > delta ? ChunkyPNG::Color.to_grayscale(pixel) : pixel}
self
end
end
require "chunky_png"
require "./extensions.rb"
image = ChunkyPNG::Image.from_file("input.png")
image.extend(SelectiveColor)
# Try the other colors if you like!
# keep = ChunkyPNG::Color.rgb(221,57,42)
# keep = ChunkyPNG::Color.rgb(152,216,56)
keep = ChunkyPNG::Color.rgb(0,125,209)
image.to_selective_color!(keep, 15)
image.save("output.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment