view graster/graster/lib/graster/image.rb @ 11:f952052e37b7

trying a fix.
author Robert McIntyre <rlm@mit.edu>
date Tue, 24 Aug 2010 19:06:45 -0400
parents
children
line wrap: on
line source
1 class Graster
2 class Image
3 PROPS = [:filename,:size,:pixels]
5 def initialize(props)
6 PROPS.each do |p|
7 raise "required image property :#{p} missing" unless props[p]
8 instance_variable_set "@#{p}", props[p]
9 end
10 end
12 PROPS.each{|p| attr_reader p }
14 def self.from_file pathname
15 raise "file not found #{pathname}" unless File.exist? pathname
16 img = Magick::Image.read(pathname)
17 raise "bad image data in #{pathname}" unless img = img[0]
18 new :filename => File.basename(pathname),
19 :size => [img.columns,img.rows],
20 :pixels => img.export_pixels(0,0,img.columns,img.rows,"I")
21 end
23 # get pixel(s) from x,y coords
24 # 0,0 is bottom,left
25 # image[x,y] => pixel at x,y
26 # image[y] => row at y
27 def [] y, x=nil
28 if x
29 @pixels[(@size[1]-y)*@size[0]+x]
30 else
31 @pixels[(@size[1]-y)*@size[0],@size[0]]
32 end
33 end
35 def each_row &block
36 @pixels.chars.each_slice(@size[0]).each_with_index &block
37 end
39 # "encode" a float 0..1 to a pixel
40 def self.f_to_pix f
41 (f*65535).round
42 end
44 # "decode" an encoded pixel to a float 0..1
45 def self.pix_to_f pix
46 pix/65535.0
47 end
50 # convert bitmap data to spans (or runs) of contiguous pixels
51 # also invert the Y axis
52 def build_spans on_range
53 # TODO: rewrite in terms of each_row
54 @spans = Array.new @size[1]
56 @size[1].times do |y|
57 spans = []
58 left = (@size[1]-y-1)*@size[0]
59 start = nil
61 @size[0].times do |x|
62 d = on_range.include?(@pixels[left+x])
64 if !start && d
65 start = x
66 elsif start && !d
67 spans << [start, x]
68 start = nil
69 end
70 end
72 spans << [start, @size[0]] if start
73 @spans[y] = spans
74 end
75 end
77 attr_reader :spans
79 def hash
80 [@pixels,@width,@height].hash
81 end
82 end
83 end