Skip to content

Instantly share code, notes, and snippets.

@AlexEne
Created August 6, 2018 23:55
Show Gist options
  • Save AlexEne/79d38c409f94a316fb76aad4d7af3d81 to your computer and use it in GitHub Desktop.
Save AlexEne/79d38c409f94a316fb76aad4d7af3d81 to your computer and use it in GitHub Desktop.
comparing images using PSNR
from PIL import Image
import math
def main():
im1 = Image.open('dwarf.png')
im2 = Image.open('dwarf2.png')
width, height = im1.size
print('{} {}'.format(width, height))
pixels1 = im1.load()
pixels2 = im2.load()
mse = 0
for y in range(0, height):
for x in range(0, width):
r1, g1, b1, _ = pixels1[x, y]
r2, g2, b2, _ = pixels2[x, y]
mse += (r1-r2) ** 2 + (g1-g2) ** 2 + (b1-b2) ** 2
mse = mse / (width*height*3)
psnr = 999999
if mse > 0:
psnr = 10 * math.log10( (255 ** 2) / mse)
print('MSE = {}'.format(mse))
print('PSNR = {}'.format(psnr))
print('Image width={} height={}\n'.format(width, height))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment