Last active
July 9, 2016 16:42
-
-
Save aarshtalati/99fa5470439caf05d845be049449098a to your computer and use it in GitHub Desktop.
Python: PIL ( Pillow ) NumPy add images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import izip | |
from PIL import Image | |
import numpy as np | |
def getImageDifference(x, y): | |
diff3 = 1.0 | |
# http://rosettacode.org/wiki/Percentage_difference_between_images#Python | |
if x.size == y.size: | |
pairs = izip(x.getdata(), y.getdata()) | |
if len(x.getbands()) == 1: | |
# for gray-scale jpegs | |
diff3 = sum(abs(p1 - p2) for p1, p2 in pairs) | |
else: | |
diff3 = sum(abs(c1 - c2) for p1, p2 in pairs for c1, c2 in zip(p1, p2)) | |
ncomponents = x.size[0] * x.size[1] * 3 | |
diff3 = (diff3 / 255.0 * 100) / ncomponents | |
return diff3 | |
i1 = Image.open('1.png').convert(mode='L', dither=Image.NONE) | |
i2 = Image.open('2.png').convert(mode='L', dither=Image.NONE) | |
cc = Image.open('C.png').convert(mode='L', dither=Image.NONE) | |
# Variation 1 | |
pixelThreshold = 200 | |
i1 = np.array(i1) | |
i1 = np.where(i1 > pixelThreshold, 255, 0) | |
i2 = np.array(i2) | |
i2 = np.where(i2 > pixelThreshold, 255, 0) | |
final1 = (i1+i2)/2 | |
final1 = np.where(final1 > pixelThreshold, 255, 0) | |
final1 = Image.fromarray(final1.astype(np.uint8)) | |
final1.show() | |
print getImageDifference(final1, cc) # ==> 0.12561853664 | |
# # Variation 2 | |
# pixelThreshold = 200 | |
# i1 = np.array(i1) | |
# i1 = np.where(i1 > pixelThreshold, 255, 0) | |
# i2 = np.array(i2) | |
# i2 = np.where(i2 > pixelThreshold, 255, 0) | |
# final1 = np.minimum((i1+i2),256) | |
# final1 = Image.fromarray(final1) | |
# final1.show() | |
# | |
# # Variation 3 | |
# pixelThreshold = 200 | |
# i1 = np.array(i1) | |
# i1 = np.where(i1 > pixelThreshold, 255, 0) | |
# i2 = np.array(i2) | |
# i2 = np.where(i2 > pixelThreshold, 255, 0) | |
# final1 = (i1+i2)/2 | |
# final1[final1>256]=256 | |
# final1 = Image.fromarray(final1) | |
# final1.show() | |
# | |
# # Variation 4 | |
i1 = Image.open('1.png').convert(mode='L', dither=Image.NONE) | |
i2 = Image.open('2.png').convert(mode='L', dither=Image.NONE) | |
# final2 = Image.blend(i1, i2, 0.5) | |
# print getImageDifference(final2, cc) # ==> 0.661266633307 | |
# # Variation 5 | |
final2 = Image.composite(i1, i2, i2) | |
final2.show() | |
print getImageDifference(final2, cc) # ==> 0.0380851773602 | |
# courtsey : https://stackoverflow.com/questions/524930/numpy-pil-adding-an-image/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment