-1

我怎样才能从图像中提取所有发白的像素并将它们绘制到具有新颜色的新图像上。下面的代码是我将如何使用 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')
4

2 回答 2

1

您根本不需要您的pixels数组,您可以使用它pixel_color来设置像素的颜色以及读取它。如果你说pixel_color(x, y),那么它的行为就像getpixel在你的 Python 代码中一样,如果你说,pixel_color(x, y, color)那么它的行为就像putpixel. 这样就可以了pixelsstore_pixels

然后问题是确定一个像素是否是白色的。该pixel_color方法返回一个Pixel实例。Pixel这里有两种特别感兴趣的方法:

  1. 用于将Pixel.from_color颜色名称转换为Pixel.
  2. 在比较中将 s 与可选的模糊性进行比较的fcmp实例方法。Pixel

你可以得到一个白色Pixelwhite = 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论点才能fcmp得到适合你的东西。

于 2013-09-13T22:40:33.427 回答
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')
于 2013-09-15T03:41:44.777 回答