Skip to content

Instantly share code, notes, and snippets.

@krukid
Last active August 28, 2020 17:43
Show Gist options
  • Save krukid/208a86422543bd7faca0bc05e7ea0cbd to your computer and use it in GitHub Desktop.
Save krukid/208a86422543bd7faca0bc05e7ea0cbd to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# @see https://www.eea.europa.eu/data-and-maps/figures/forest-map-of-europe-1
# @note uses imagemagick histogram to count unique colors
#
COUNTRY_IMAGE=ARGV[0]
COLOR_WEIGHTS={
'#FFFFFF' => 0..1,
'#FFFFBE' => 2..10,
'#D3FFBE' => 11..25,
'#4CE600' => 26..50,
'#38A800' => 51..75,
'#267300' => 76..100,
}
COLORS = COLOR_WEIGHTS.keys
HIST=`convert #{COUNTRY_IMAGE} -define histogram:unique-colors=true -format %c histogram:info:-`
PIXEL_COUNTS = Hash.new(0).merge Hash[
HIST.scan(/^\s+(\d+):.*\s(#[0-9A-F]+)\s.*$/).map do |count, color|
[color, count.to_i]
end
]
TOTAL_PIXELS = COLORS.reduce(0){|s, k| s + PIXEL_COUNTS[k]}
def calc_total_weighted(&method)
COLORS.reduce(0) do |s, k|
r = COLOR_WEIGHTS[k]
m = method.call(r)
w = m / 100.0
s + PIXEL_COUNTS[k] * w
end
end
def calc_total_percent(&method)
(calc_total_weighted(&method) / TOTAL_PIXELS * 100).round
end
min = calc_total_percent{|r| r.min}
max = calc_total_percent{|r| r.max}
avg = calc_total_percent{|r| (r.max + r.min) / 2}
fin0 = calc_total_percent{|r| r.max * 0.925}
puts "total forested: min: #{min} || avg: #{avg} || fin0: #{fin0} || max: #{max}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment