Brightness/Contrast

Changing the brightness and/or contrast of an image simply means applying a gain and an offset to the image.  The values need to be clamped before they can be displayed.

#!/usr/bin/env ruby
require 'hornetseye'
include Hornetseye
raise "Syntax: b_c.rb <input file> <output file>" if ARGV.size != 2
img = MultiArray.load_ubytergb ARGV[0]
n = 3
w, h = *img.shape
thumb = img.downsample [ n, n ], [ n - 1, n - 1 ]
result = MultiArray.ubytergb *thumb.shape.collect { |d| d * n }
for y in 0 ... n
  for x in 0 ... n
    brightness = 2 * ( y + 0.5 ) / n - 1
    contrast = 2 * ( x + 0.5 ) / n - 1
    factor = ( contrast + 1.0 ) / ( 1.0 - contrast )
    offset = 128.0 * ( 1.0 + ( brightness -1.0 ) * factor )
    sample = thumb * factor + offset
    result[ w / n * x ... w / n * ( x + 1 ),
            h / n * y ... h / n * ( y + 1 ) ] = sample.clip
  end
end
result.save_ubytergb ARGV[1]
Close