Skip to content

Instantly share code, notes, and snippets.

@rakusai
Created June 17, 2014 10:37
Show Gist options
  • Save rakusai/728cd538064c261da052 to your computer and use it in GitHub Desktop.
Save rakusai/728cd538064c261da052 to your computer and use it in GitHub Desktop.
画像が白系かどうかを判定。
require 'RMagick'
NUM_COLORS = 16
HIST_HEIGHT = 200
img = Magick::Image.read('public/upload_images/d1/a5/d1a50562ce7d25930bc5d4b527aec38b.png').first
img = img.quantize(NUM_COLORS, Magick::GRAYColorspace)
#img = img.quantize(NUM_COLORS)
hist = img.color_histogram
# sort pixels by increasing count
pixels = hist.keys {|pixel| hist[pixel] }
pixels.each { |pixel|
puts pixel, hist[pixel]
}
puts "last v"
puts hist[pixels.last]
total = 0
hist.values.each { |v| total += v }
puts "total", total
r = hist[pixels.last].to_f / total.to_f
puts r
if r > 0.2
puts "white base"
else
puts "not white base"
end
scale = HIST_HEIGHT / (hist.values.max*1.025) # put 2.5% air at the top
gc = Magick::Draw.new
gc.stroke_width(1)
gc.affine(1, 0, 0, -scale, 0, HIST_HEIGHT)
# handle images with fewer than NUM_COLORS colors
start = NUM_COLORS - img.number_colors
pixels.each { |pixel|
gc.stroke(pixel.to_color)
gc.line(start, 0, start, hist[pixel])
start = start.succ
}
hatch = Magick::HatchFill.new("white", "gray95")
canvas = Magick::Image.new(NUM_COLORS, HIST_HEIGHT, hatch)
gc.draw(canvas)
text = Magick::Draw.new
#text.annotate(canvas, 0, 0, 0, 20, "Color Frequency\nHistogram") {
# self.pointsize = 10
# self.gravity = Magick::NorthGravity
# self.stroke = 'transparent'
# }
canvas.border!(1, 1, "white")
canvas.border!(1, 1, "black")
canvas.border!(3, 3, "white")
canvas.write("color_histogram.gif")
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment