Harrington Web

JRuby Image Comparison

Friday, April 4, 2014

Working on a project to validate some images and I thought this would be a good opportunity to show a simple way to compare 2 images to see if they are equal.

First we need to declare some library's. We will be using JRuby for these examples. If you want to use Java this will look simular.

require 'java'

java_import 'java.awt.event.InputEvent'
java_import 'java.awt.image.BufferedImage'
java_import 'javax.imageio.ImageIO'

Now we need to make a function that will allow us to open an image as a bufferedImage

def get_image(filename)
  file = java::io::File.new(filename)
  return ImageIO::read(file)
end

Lets start figuring out if the images are the same. A good place to start is to define a function that with tell us whether the width and height are the same. If they are equal then the images could be the same.

def compare_size(img1, img2)
  if (img1.getWidth == img2.getWidth && img1.getHeight == img2.getHeight)
    return true
  else
    return false
  end
end

Now we are cooking with grease. The compare_size function above will get the width and height of both images and compare them. If they are equal the function will return a true value. Now that we know that both the images are possibly the same size we need to validate if the images are identical. With buffered images this is not as simple as the example below.

if (img1 == img2)
  puts "Equal"
else
  puts "Not Equal"
end

Nice try!! This don't work. For a simple mundane way of checking images we need to comapre them pixel by pixel with the RGB value.

def compare_pixels(img1, img2)
  (0..img1.getWidth-1).each do |x|
    (0..img1.getHeight-1).each do |y|
      if(img1.getRGB(x, y) != img2.getRGB(x, y))
          return false
      end
    end
  end
  return true
end

Now you have a function to fully check if 2 images are the same pixel by pixel. Please note that if the images have different color profiles or use alpha color this function could still fail. We'll save that lesson for another time.

Lets string these in order to finish the simple program up.

img1 = get_image('example1.png')
img2 = get_image('example2.png')

if (compare_size(img1, img2))
  if (compare_pixels(img1, img2))
    puts "Images are Equal"
  else
    puts "Images are Different"
  end
else
  puts "Images are Not Same Size"
end

Want to download the whole script checkout Github

No comments :

Post a Comment