Skip to content

Instantly share code, notes, and snippets.

@timothyandrew
Created September 12, 2011 17:32
Show Gist options
  • Save timothyandrew/1211850 to your computer and use it in GitHub Desktop.
Save timothyandrew/1211850 to your computer and use it in GitHub Desktop.
Codebrawl #10
#!/usr/bin/env ruby
require 'chunky_png'
# Convert the RGB coordinates to polar form (HSV) and get the hue.
# Formula from: http://en.wikipedia.org/wiki/Hue#Computing_hue_from_RGB
# Doesn't handle all the cases (R >= B > G, for example), but it gets the job done.
def get_hue(r,g,b)
max = [r,g,b].max
if max == r
hue = 0.0 + 60.0 * (g - b)
if(hue < 0.0)
hue += 360.0
end
elsif max == g
hue = 120.0 + 60.0 * (b-r)
else
hue= 240+60*(r-g)
end
return hue
end
image = ChunkyPNG::Image.from_file('input.png')
# The hue of the color we want to select
color = 204
req_range = color-34..color+34
# Iterate over the pixels in the image.
# If the hue for the pixel is NOT in the required range, convert that pixel to grayscale.
# The required range is 20 degrees +/- a single hue.
# Here blue has hue of 240, so our range is 220 -> 260.
for i in 0...image.width
for j in 0...image.height
pixel = image.get_pixel(i,j)
r = ChunkyPNG::Color.r(pixel).to_f
g = ChunkyPNG::Color.g(pixel).to_f
b = ChunkyPNG::Color.b(pixel).to_f
hue = get_hue(r/255,g/255,b/255) # Convert co-ordinates to be between 0 and 1
if not req_range.include?(hue)
image.set_pixel(i,j,ChunkyPNG::Color.to_grayscale(pixel))
end
end
end
image.save('output.png')
@theodorton
Copy link

Got to your solution by Googling, dunno if your Gist is public.

@timothyandrew
Copy link
Author

Oops, this the first real gist I've written; I'm not sure! Shouldn't it be public?

@theodorton
Copy link

Should be private :)

@timothyandrew
Copy link
Author

Doesn't that mean that only I can view this gist?

@theodorton
Copy link

I'm quite sure you can submit a Private one. You need to connect your GitHub account to Codebrawl.

Alternatively, check with https://github.com/jeffkreeftmeijer

@timothyandrew
Copy link
Author

All right, I will check. Thanks for the heads up!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment