2

ImageMagickコマンドを使用して画像処理を行っていますが、それらをRMagickに移植したいと思います。このタスクの目標は、写真を撮り、プライバシーの目的で特定の領域(1つ以上)をピクセル化することです。

これが私のbashスクリプト( )で、コマンドscript.shを使用すると非常にうまく機能します。convert

convert invoice.png -scale 10% -scale 1000% pixelated.png
convert invoice.png -gamma 0 -fill white -draw "rectangle 35, 110, 215, 250" mask.png
convert invoice.png pixelated.png mask.png -composite result.png

次に、ImageMagickを使用してこのスクリプトのRubyバージョンを作成します。これが私が今持っているものです:

require 'rmagick'

# pixelate_areas('invoice.png', [ [ x1, y1, width, height ] ])
def pixelate_areas(image_path, areas)
  image     = Magick::Image::read(image_path).first
  pixelated = image.scale(0.1).scale(10)
  mask      = Magick::Image.new(image.columns, image.rows) { self.background_color = '#000' }

  areas.each do |coordinates|
    area = Magick::Image.new(coordinates[2], coordinates[3]) { self.background_color = '#fff' }
    mask.composite!(area, coordinates[0], coordinates[1], Magick::OverCompositeOp)
  end

  # Now, how can I merge my 3 images?
  # I need to extract the part of pixelated that overlap with the white part of the mask (everything else must be transparent).
  # Then I have to superpose the resulting image to the original (it's the easy part).
end

ご覧のとおり、私は最後のステップで立ち往生しています。この結果を得るには、元の画像ピクセル化された画像、およびマスクに対してどのような操作を行う必要がありますか?

マスクの白い部分とピクセル化された画像を重ね合わせただけで画像を作成するにはどうすればよいですか。これと同じですが、黒ではなく透明度がありますか?

4

1 に答える 1

2

まず、すでに機能しているものがあるのに、なぜコマンドをRMagickに移植するのですか?bashバージョンは短くてわかりやすいです。これが移植しているより大きなスクリプトの一部である場合は、恐れることはありませんsystem()

そうは言っても、これはあなたがやろうとしていることをより簡単な方法で達成すると私が信じている別の方法です。

require 'RMagick'

def pixelate_area(image_path, x1, y1, x2, y2)
  image          = Magick::Image::read(image_path).first
  sensitive_area = image.crop(x1, y1, x2 - x1, y2 - y1).scale(0.1).scale(10)

  image.composite!(sensitive_area, x1, y1, Magick::AtopCompositeOp)
  image.write('result.png') { self.depth = image.depth }
end

これは、元のbashコマンドと同じように機能するようです。

pixelate_area('invoice.png', 35, 110, 215, 250)

ぼかしを入れるために複数の領域を処理したいように見えるので、次のバージョンは領域の配列を取ります(それぞれとして[x1, y1, x2, y2]):

def pixelate_areas(image_path, areas)
  image = Magick::Image::read(image_path).first

  areas.each do |area|
    x1, y1, x2, y2 = area

    sensitive_area = image.crop(x1, y1, x2 - x1, y2 - y1).scale(0.1).scale(10)
    image.composite!(sensitive_area, x1, y1, Magick::AtopCompositeOp)
  end

  image.write('result.png') { self.depth = image.depth }
end
于 2012-06-29T09:37:26.327 に答える