Percentage difference between images

From Rosetta Code
Revision as of 23:15, 6 December 2008 by rosettacode>IanOsgood (open task up to those without JPEG libraries)
Task
Percentage difference between images
You are encouraged to solve this task according to the task description, using any language you may know.

Compute the percentage of difference between 2 JPEG images of the same size. Alternatively, compare two bitmaps as defined in basic bitmap storage.

Useful for comparing two JPEG images saved with a different compression ratios.

You can use these pictures for testing:

The expected difference for these two images is 1.62125%

MAXScript

fn diffImages =
(
	local img1 = selectBitmap caption:"Select Image 1"
	local img2 = selectBitmap caption:"Select Image 2"
	local totalDiff = 0
	for i in 0 to (img1.height-1) do
	(
		local img1Row = getPixels img1 [0, i] img1.width
		local img2Row = getPixels img2 [0, i] img2.width
		
		for j in 1 to img1.width do
		(
			totalDiff += (abs (img1Row[j].r - img2Row[j].r)) / 255.0
			totalDiff += (abs (img1Row[j].g - img2Row[j].g)) / 255.0
			totalDiff += (abs (img1Row[j].b - img2Row[j].b)) / 255.0
		)
	)
	format "Diff: %\%\n" (totalDiff / ((img1.width * img1.height * 3) as float) * 100)
)

OCaml

<ocaml>#! /usr/bin/env ocaml

  1. directory "+glMLite/"
  2. load "jpeg_loader.cma"
  3. load "bigarray.cma"

open Jpeg_loader

let () =

 let img1, width1, height1, col_comp1, color_space1 = load_img (Filename Sys.argv.(1))
 and img2, width2, height2, col_comp2, color_space2 = load_img (Filename Sys.argv.(2)) in
 assert(width1 = width2);
 assert(height1 = height2);
 assert(col_comp1 = col_comp2);  (* number of color components *)
 assert(color_space1 = color_space2);
 let img1 = Bigarray.array3_of_genarray img1
 and img2 = Bigarray.array3_of_genarray img2 in
 let sum = ref 0.0
 and num = ref 0 in
 for x=0 to pred width1 do
   for y=0 to pred height1 do
     for c=0 to pred col_comp1 do
       let v1 = float img1.{x,y,c}
       and v2 = float img2.{x,y,c} in
       let diff = (abs_float (v1 -. v2)) /. 255. in
       sum := diff +. !sum;
       incr num;
     done;
   done;
 done;
 let diff_percent = !sum /. float !num in
 Printf.printf " diff: %f percent\n" diff_percent;
</ocaml>