how can i take all the whitish pixels from an image and draw them on to a new image with a new color. the code below is how i would do it with python but the majority of the project has been written in ruby so i am trying to stick with it.
from PIL import Image
im = Image.open("image_in.png")
im2 = Image.new("P",im.size,255)
im = im.convert("P")
temp = {}
for x in range(im.size[1]):
for y in range(im.size[0]):
pix = im.getpixel((y,x))
temp[pix] = pix
if pix == 225:
im2.putpixel((y,x),0)
im2.save("image_out.png")
this is what i got so far:
require 'rubygems'
require 'RMagick'
include Magick
image = Magick::Image.read('image_in.png').first
image2 = Image.new(170,40) { self.background_color = "black" }
pixels = []
(0..image.columns).each do |x|
(0..image.rows).each do |y|
pixel = image.pixel_color(x, y)
if pixel == 54227 >> pixels #color value
image2.store_pixels(pixels)
end
end
end
image2.write('image_out.png')
You don't need your pixels
array at all, you can use pixel_color
to set a pixel's color as well as read it. If you say pixel_color(x, y)
then it behaves like getpixel
in your Python code, if you say pixel_color(x, y, color)
then it behaves like putpixel
. So that gets ride of pixels
and store_pixels
.
Then the problem is figuring out if a pixel is white. The pixel_color
method returns you a Pixel
instance. Pixel
has two methods of particular interest here:
Pixel.from_color
class method for converting a color name to a Pixel
.fcmp
instance method for comparing Pixel
s with an optional fuzziness in the comparison.You can get a white Pixel
with white = Pixel.from_color('white')
. Then you can copy white pixels with:
pixel = image.pixel_color(x, y)
if pixel.fcmp(white)
image2.pixel_color(x, y, pixel)
end
If you want to make the comparison fuzzy, then supply the second argument to fcmp
:
if pixel.fcmp(white, 10000)
image2.pixel_color(x, y, pixel)
end
You'll probably have to play around with the fuzz
argument to fcmp
to get something that works for you.