Class: Magick::ExtractObject::Image

Inherits:
Object
  • Object
show all
Defined in:
lib/rmagick/extract_object/image.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Image

Returns a new instance of Image.



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/rmagick/extract_object/image.rb', line 8

def initialize(path)
  @path  = path

  unless config.content_type.include?(type_from_mime_magic)
    raise "invalid content type"
  end

  image_list = Magick::ImageList.new
  image_list.from_blob(blob)
  @image = image_list.first
end

Instance Attribute Details

#imageObject

Returns the value of attribute image.



6
7
8
# File 'lib/rmagick/extract_object/image.rb', line 6

def image
  @image
end

Instance Method Details

#edgeObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rmagick/extract_object/image.rb', line 30

def edge
  white = Magick::Pixel.new(255*256, 255*256, 255*256)
  black = Magick::Pixel.new(0, 0, 0)

  image = @image.copy
  image.columns.times do |x|
    image.rows.times do |y|
      current = image.pixel_color(x, y)
      next_x  = image.pixel_color(x + 1, y)
      next_y  = image.pixel_color(x, y + 1)

      diff_x = { r: current.red - next_x.red, g: current.green - next_x.green, b: current.blue - next_x.blue }
      diff_y = { r: current.red - next_y.red, g: current.green - next_y.green, b: current.blue - next_y.blue }

      slope = [diff_x[:r]**2 + diff_y[:r]**2, diff_x[:r]**2 + diff_y[:r]**2, diff_x[:r]**2 + diff_y[:r]**2]
      if slope.inject(:+) > config.slope
        image.pixel_color(x, y, black)
      else
        image.pixel_color(x, y, white)
      end
    end
  end
  image
end

#maskObject



55
56
57
58
59
60
# File 'lib/rmagick/extract_object/image.rb', line 55

def mask
  image = edge
  image.border!(1, 1, 'white')
  image.fuzz = '10%'
  image.color_floodfill(0, 0, config.mask_color).shave!(1, 1).opaque('black', 'white')
end

#transparent_background(base_image = nil) ⇒ Object



20
21
22
23
24
25
26
27
28
# File 'lib/rmagick/extract_object/image.rb', line 20

def transparent_background(base_image = nil)
  mask_image = mask

  base_image = @image if base_image.nil?

  image = Magick::ImageList.new << base_image
  image.alpha Magick::ActivateAlphaChannel
  image.fx("r", Magick::AlphaChannel).composite(mask_image, Magick::CenterGravity, Magick::CopyAlphaCompositeOp)
end