如何从图像中获取所有白色像素并将其绘制为具有新颜色的新图像。下面的代码是我如何用python做的,但是大部分项目都是用ruby编写的,所以我试着坚持下去。
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")
这是我到目前为止所得到的:
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')
答案 0 :(得分:0)
您根本不需要pixels
数组,您可以使用pixel_color
设置像素的颜色并进行读取。如果您说pixel_color(x, y)
,那么它在您的Python代码中就像getpixel
一样,如果您说pixel_color(x, y, color)
,那么它的行为就像putpixel
。因此可以乘坐pixels
和store_pixels
。
然后问题是弄清楚像素是否为白色。 pixel_color
方法会返回Pixel
个实例。 Pixel
有两种特别感兴趣的方法:
Pixel.from_color
的{{1}}类方法。Pixel
实例方法,用于比较fcmp
s与比较中的可选模糊性。您可以使用Pixel
获得白色Pixel
。然后你可以复制白色像素:
white = Pixel.from_color('white')
如果要使比较模糊,则将第二个参数提供给pixel = image.pixel_color(x, y)
if pixel.fcmp(white)
image2.pixel_color(x, y, pixel)
end
:
fcmp
您可能需要使用if pixel.fcmp(white, 10000)
image2.pixel_color(x, y, pixel)
end
fuzz
参数来获取适合您的内容。
答案 1 :(得分:0)
require 'RMagick'
include Magick
image = Magick::Image.read('image_in.png').first
image2 = Image.new(170,40) # { self.background_color = "black" }
color = Pixel.from_color('#D3D3D3') #color to extract
(0..image.columns).each do |x|
(0..image.rows).each do |y|
pixel = image.pixel_color(x, y)
if pixel.fcmp(color)
image2.pixel_color(x, y, "#000000") #change color to black
end
end
end
image2.write('image_out.png')