photo_hash_3.py 647 B

123456789101112131415
  1. def average_hash(image_path, hash_size=8):
  2. """ Compute the average hash of the given image. """
  3. with open(image_path, 'rb') as f:
  4. # Open the image, resize it and convert it to black & white.
  5. image = Image.open(f).resize((hash_size, hash_size), Image.ANTIALIAS).convert('L')
  6. pixels = list(image.getdata())
  7. avg = sum(pixels) / len(pixels)
  8. # Compute the hash based on each pixels value compared to the average.
  9. bits = "".join(map(lambda pixel: '1' if pixel > avg else '0', pixels))
  10. hashformat = "0{hashlength}x".format(hashlength=hash_size ** 2 // 4)
  11. return int(bits, 2).__format__(hashformat)