Guest User

Untitled

a guest
Nov 14th, 2018
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. require 'mini_magick'
  2. require 'tempfile'
  3.  
  4. class Quality
  5. def initialize(path)
  6. @path = path
  7. end
  8.  
  9. def black_pixels
  10. colours.fetch('#000000')
  11. end
  12.  
  13. def percentage
  14. white_pixels.to_f / total_colour_pixels.to_f
  15. end
  16.  
  17. def white_pixels
  18. colours.fetch('#FFFFFF')
  19. end
  20.  
  21. private
  22.  
  23. def colours
  24. @colours ||= Histogram.new(negated_image_path).colors
  25. end
  26.  
  27. def negated_image_path
  28. Negated.new(@path).path
  29. end
  30.  
  31. def total_colour_pixels
  32. colours.sum { |_colour, pixels| pixels }
  33. end
  34.  
  35. # Retrieves a count of pixels per colour
  36. # magick output.png -format %c histogram:info:-
  37. class Histogram
  38. HEX_REGEX = %r{(?<pixels>\d*)\:.*(?<hex>#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}))}
  39.  
  40. def initialize(path)
  41. @path = path
  42. end
  43.  
  44. def colors
  45. raw.split("\n").each_with_object({}) do |colour, hash|
  46. colour.match(HEX_REGEX) { |m| hash[m['hex']] = m['pixels'].to_i }
  47. end
  48. end
  49.  
  50. private
  51.  
  52. def image
  53. @image ||= MiniMagick::Image.open(@path)
  54. end
  55.  
  56. def raw
  57. image.run_command('convert', image.path, '-format', '%c', 'histogram:info:')
  58. end
  59.  
  60. Colour = Struct.new(:hex, :pixels)
  61. end
  62.  
  63. # Creates a pure black and white image with no transparency. e.g. all coloured pixels become black.
  64. class Negated
  65. def initialize(path)
  66. @path = path
  67. end
  68.  
  69. def path
  70. convert
  71. tempfile.path
  72. end
  73.  
  74. private
  75.  
  76. # magick convert images/e86500ca-8bb9-4e48-b884-d1f1bc684f25_1542111343_screenshot.png -negate -threshold -0 -negate output.png
  77. def convert
  78. MiniMagick::Tool::Convert.new do |convert|
  79. convert << @path
  80. convert.flatten
  81. convert.negate
  82. convert.threshold('-0')
  83. convert.negate
  84. convert << tempfile.path
  85. end
  86. end
  87.  
  88. def tempfile
  89. @tempfile ||= Tempfile.new
  90. end
  91. end
  92. end
Add Comment
Please, Sign In to add comment