Question

EDIT: I believe I didn't state correctly my question, so here is the edit.

I want to be able to compare (and score) a set of images with one image in terms of width and height.

Ideally, I would have a BASE_SCORE value (for example 100) that would be used in order to score each image depending on how close they look to the main image (in terms of width and height).

So, if for example, the main image looks like {:width => 100, :height => 100}, and set_images look like [{:width => 100, :height => 100}, {:width => 10, :height => 40}], the first element would have a score of BASE_SCORE, because they look exactly the same.

I fail to see how to compare width/heights in order to score each element of set_images.

Was it helpful?

Solution

Is there a problem with just using the Euclidean distance? Zero represents equality:

def euclidean_distance(a, b)
  dx = a[:width] - b[:width]
  dy = a[:height] - b[:height]
  Math.sqrt((dx * dx) + (dy * dy))
end

test_subject = { width: 200, height: 50 }
samples = [
  { width: 100, height: 100 },
  { width: 80,  height: 200 },
  { width: 200, height: 50 },
  { width: 10,  height: 10 }
]

distances = samples.map { |s| euclidean_distance(test_subject, s) }

samples.zip(distances) { |img, dist| puts "#{img[:width]}x#{img[:height]} => #{dist}" }

Output:

100x100 => 111.80339887498948
80x200 => 192.09372712298546
200x50 => 0.0
10x10 => 194.164878389476

You can then use sort easily enough:

sorted = samples.sort { |a, b| euclidean_distance(test_subject, a) <=> euclidean_distance(test_subject, b) }

OTHER TIPS

Something like this seems to work. Excuse the formatting...

$ cat foo.rb
require 'pp'

main_image = {:width => 100, :height => 50}
set_of_images = [{:width => 200, :height => 300, :id => 2}, 
                 {:width => 100, :height => 50, :id => 9}]

aspect_ratio = main_image[:width] / main_image[:height].to_f

sorted_images = set_of_images.
                  map{|i| i[:score] = (aspect_ratio - i[:width]/i[:height].to_f).abs; i}.
                  sort_by{|i| i[:score]}

pp sorted_images

$ ruby foo.rb
[{:width=>100, :height=>50, :id=>9, :score=>0.0},
 {:width=>200, :height=>300, :id=>2, :score=>1.3333333333333335}]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top