Experiments with ruby-processing (processing-2.2.1) and JRubyArt for processing-3.0

Thursday 21 August 2014

Another example of a sketch using map1d in JRubyArt (development version of ruby-processing)

With every sketch that I look at with fresh eyes, the more convinced I am that ruby-processing does not need to (probably should not) ape processing convenience functions, and should where possible use idiomatic ruby. In this sketch we also use ruby array max method (built into ruby) in place of the processing convenience method:-
# Histogram. 
# 
# Calculates and displays the distribution of brightness levels 
# across an image, as a histogram. In this case the x scale is
# used for the brighness levels 0 .. 255, and the y scale is the
# frequency distribution. Note use of map1d function to map the
# ranges. Also for greater efficiency we load the image pixels.

attr_reader :hist

def setup
  size(640, 360)

  # Load an image from the data directory
  # Load a different image by modifying the comments
  img = load_image('frontier.jpg')
  image(img, 0, 0)
  img.load_pixels
  @hist = Array.new(256, 0)

  # Calculate the histogram
  (0 ... img.width).each do |i|
    (0 ... img.height).each do |j|
      bright = (brightness(img.pixels[j * img.width + i]))
      hist[bright] += 1
    end
  end

  # Find the largest value in the histogram using 'ruby' array max function
  hist_max = hist.max

  stroke(255)
  # Draw half of the histogram (skip every second value)
  (0 ... img.width).step(2) do |i|
    # Map i (from 0..img.width) to a location in the histogram (0..255)
    which = map1d(i, (0 .. img.width), (0 .. 255))
    # Convert the histogram value to a location between 
    # the bottom and the top of the picture
    y = map1d(hist[which], (0 .. hist_max), (img.height .. 0))
    line(i, img.height, i, y)
  end
end

No comments:

Post a Comment

Followers

Blog Archive

About Me

My photo
I have developed JRubyArt and propane new versions of ruby-processing for JRuby-9.1.5.0 and processing-3.2.2