Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'mini_magick'
- require 'tempfile'
- class Quality
- def initialize(path)
- @path = path
- end
- def black_pixels
- colours.fetch('#000000')
- end
- def percentage
- white_pixels.to_f / total_colour_pixels.to_f
- end
- def white_pixels
- colours.fetch('#FFFFFF')
- end
- private
- def colours
- @colours ||= Histogram.new(negated_image_path).colors
- end
- def negated_image_path
- Negated.new(@path).path
- end
- def total_colour_pixels
- colours.sum { |_colour, pixels| pixels }
- end
- # Retrieves a count of pixels per colour
- # magick output.png -format %c histogram:info:-
- class Histogram
- HEX_REGEX = %r{(?<pixels>\d*)\:.*(?<hex>#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}))}
- def initialize(path)
- @path = path
- end
- def colors
- raw.split("\n").each_with_object({}) do |colour, hash|
- colour.match(HEX_REGEX) { |m| hash[m['hex']] = m['pixels'].to_i }
- end
- end
- private
- def image
- @image ||= MiniMagick::Image.open(@path)
- end
- def raw
- image.run_command('convert', image.path, '-format', '%c', 'histogram:info:')
- end
- Colour = Struct.new(:hex, :pixels)
- end
- # Creates a pure black and white image with no transparency. e.g. all coloured pixels become black.
- class Negated
- def initialize(path)
- @path = path
- end
- def path
- convert
- tempfile.path
- end
- private
- # magick convert images/e86500ca-8bb9-4e48-b884-d1f1bc684f25_1542111343_screenshot.png -negate -threshold -0 -negate output.png
- def convert
- MiniMagick::Tool::Convert.new do |convert|
- convert << @path
- convert.flatten
- convert.negate
- convert.threshold('-0')
- convert.negate
- convert << tempfile.path
- end
- end
- def tempfile
- @tempfile ||= Tempfile.new
- end
- end
- end
Add Comment
Please, Sign In to add comment