Skip to content

Instantly share code, notes, and snippets.

@EliteMasterEric
Created November 6, 2016 22:00
Show Gist options
  • Select an option

  • Save EliteMasterEric/e5786d2720ef43e261ab93437fc9947c to your computer and use it in GitHub Desktop.

Select an option

Save EliteMasterEric/e5786d2720ef43e261ab93437fc9947c to your computer and use it in GitHub Desktop.
Simple perceptual hashing in Python.
# Import the Python Image Library.
from PIL import Image
# Constant values for image locations, etc.
IMAGE_INPUT = "Square.png"
IMAGE_OUTPUT_GRAY = "Gray.png"
IMAGE_OUTPUT_SCALED = "Scaled.png"
IMAGE_OUTPUT_HASH = "Hashed.png"
# The size of the scaled image used for hashing, in pixels.
IMAGE_WIDTH = 16
IMAGE_HEIGHT = 16
# Open the image file in the local directory.
image = Image.open(IMAGE_INPUT)
# Print some information about the image.
print("Image format: ", image.format, image.size, image.mode)
# Convert the image to "luminance" mode, or grayscale.
image = image.convert("L")
# Save the converted image to the local folder.
image.save(IMAGE_OUTPUT_GRAY)
# Resize the image.
image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT), Image.ANTIALIAS)
# Save the converted image to the local folder.
image.save(IMAGE_OUTPUT_SCALED)
# Get the list of pixels in the image.
pixels = list(image.getdata())
# Determine the average value of the pixels.
average = sum(pixels) / len(pixels)
print ("The average pixel value is ", average)
# Get the list of pixels in the image.
loaded = image.load()
# For each row in the image,
for row in range(0, IMAGE_WIDTH):
# and for each pixel in the row,
for column in range(0, IMAGE_HEIGHT):
# If the pixel is lighter than the average, set it to white.
if(loaded[row, column] > average):
loaded[row, column] = 255
# If the pixel is darker than the average, set it to white.
else:
loaded[row, column] = 0
# Save the converted image to the local folder.
image.save(IMAGE_OUTPUT_HASH)
# Create a hexadecimal string from the image.
# For each byte in the list of bytes, if the pixel is darker than average, add 1 to the bit string, else add 0.
bits = "".join(map(lambda pixel: '1' if pixel > average else '0', pixels))
print("Image hash as bits: ", bits)
# Convert the bit string into the hexadecimal string.
hexadecimal = int(bits, 2).__format__('016x').upper()
print("Image hash as hexadecimal: ", hexadecimal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment