similarity.inc 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. /**
  3. * A very simple algorithm for finding the dissimilarity between images,
  4. * mainly useful for checking lossy compression.
  5. */
  6. /**
  7. * Gets the individual components of an RGB value.
  8. *
  9. * @param int $color
  10. * @param int $red
  11. * @param int $green
  12. * @param int $blue
  13. *
  14. * @return void
  15. */
  16. function get_rgb($color, &$red, &$green, &$blue)
  17. {
  18. // assumes $color is an RGB value
  19. $red = ($color >> 16) & 0xFF;
  20. $green = ($color >> 8) & 0xFF;
  21. $blue = $color & 0xFF;
  22. }
  23. /**
  24. * Calculates the euclidean distance of two RGB values.
  25. *
  26. * @param int $color1
  27. * @param int $color2
  28. *
  29. * @return int
  30. */
  31. function calc_pixel_distance($color1, $color2)
  32. {
  33. get_rgb($color1, $red1, $green1, $blue1);
  34. get_rgb($color2, $red2, $green2, $blue2);
  35. return sqrt(
  36. pow($red1 - $red2, 2) + pow($green1 - $green2, 2) + pow($blue1 - $blue2, 2)
  37. );
  38. }
  39. /**
  40. * Calculates dissimilarity of two images.
  41. *
  42. * @param resource $image1
  43. * @param resource $image2
  44. *
  45. * @return int The dissimilarity. 0 means the images are identical. The higher
  46. * the value, the more dissimilar are the images.
  47. */
  48. function calc_image_dissimilarity($image1, $image2)
  49. {
  50. // assumes image1 and image2 have same width and height
  51. $dissimilarity = 0;
  52. for ($i = 0, $n = imagesx($image1); $i < $n; $i++) {
  53. for ($j = 0, $m = imagesy($image1); $j < $m; $j++) {
  54. $color1 = imagecolorat($image1, $i, $j);
  55. $color2 = imagecolorat($image2, $i, $j);
  56. $dissimilarity += calc_pixel_distance($color1, $color2);
  57. }
  58. }
  59. return $dissimilarity;
  60. }