Class: Imogen::AutoCrop::Edges

Inherits:
Object
  • Object
show all
Includes:
OpenCV
Defined in:
lib/imogen/auto_crop/edges.rb

Instance Method Summary collapse

Constructor Details

#initialize(src) ⇒ Edges

Returns a new instance of Edges.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/imogen/auto_crop/edges.rb', line 9

def initialize(src)
  @xoffset = 0
  @yoffset = 0
  if src.is_a? FreeImage::Bitmap
    img = src
    @xoffset = img.width.to_f/6
    @yoffset = img.height.to_f/6
    if Imogen::AutoCrop::Box.squarish? img
      @xoffset = @xoffset/2
      @yoffset = @yoffset/2
    end
    @tempfile = Tempfile.new(['crop','.png'])

    img.copy(@xoffset,@yoffset,img.width-@xoffset,img.height-@yoffset) do |crop|
      crop.save(@tempfile.path, :png)
      crop.free
    end
  else
    raise src.class.name 
  end
  # use bigger features on bigger images
  @grayscale = CvMat.load(@tempfile.path, CV_LOAD_IMAGE_GRAYSCALE)
  @xrange = (0..@grayscale.cols)
  @yrange = (0..@grayscale.rows)
end

Instance Method Details

#bound_min(center) ⇒ Object



35
36
37
# File 'lib/imogen/auto_crop/edges.rb', line 35

def bound_min(center)
  [center.x - @xrange.min, @xrange.max - center.x, center.y - @yrange.min, @yrange.max - center.y].min
end

#get(*args) ⇒ Object

returns leftX, topY, rightX, bottomY



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/imogen/auto_crop/edges.rb', line 40

def get(*args)
  c = Imogen::AutoCrop::Box.info(@grayscale)
  r = c.radius.floor
  # adjust the box
  coords = [c.x, c.y]
  min_rad = args.max/2
  unless r >= min_rad && r <= bound_min(c)
    # first adjust to the lesser of max (half short dimension) and min (half requested length) radius
    # this might require upscaling in rare situations to preserve bound safety
    r = min_rad if r < min_rad
    max_rad = [@xrange.max - @xrange.min, @yrange.max - @yrange.min].min / 2
    r = max_rad if r > max_rad
    # now move the center point minimally to accomodate the necessary radius
    coords[0] = @xrange.max - r if (coords[0] + r) > @xrange.max  
    coords[0] = @xrange.min + r if (coords[0] - r) < @xrange.min  
    coords[1] = @yrange.max - r if (coords[1] + r) > @yrange.max  
    coords[1] = @yrange.min + r if (coords[1] - r) < @yrange.min  
  end
  coords = [coords[0] + @xoffset, coords[1] + @yoffset].collect {|i| i.floor}
  c = coords

  return [c[0]-r, c[1]-r, c[0]+r, c[1] + r]
end


63
64
65
# File 'lib/imogen/auto_crop/edges.rb', line 63

def unlink
  @tempfile.unlink
end