Created
September 17, 2017 20:35
-
-
Save csetzkorn/5b58794316c1983f85d39c29153034ec to your computer and use it in GitHub Desktop.
Compare pngs in python
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
import os | |
from scipy.misc import imread | |
from scipy.linalg import norm | |
from scipy import sum, average | |
def compare_images(img1, img2): | |
# normalize to compensate for exposure difference, this may be unnecessary | |
# consider disabling it | |
img1 = normalize(img1) | |
img2 = normalize(img2) | |
# calculate the difference and its norms | |
diff = img1 - img2 # elementwise for scipy arrays | |
m_norm = sum(abs(diff)) # Manhattan norm | |
z_norm = norm(diff.ravel(), 0) # Zero norm | |
return (m_norm, z_norm) | |
def to_grayscale(arr): | |
"If arr is a color image (3D array), convert it to grayscale (2D array)." | |
if len(arr.shape) == 3: | |
return average(arr, -1) # average over the last axis (color channels) | |
else: | |
return arr | |
def normalize(arr): | |
rng = arr.max()-arr.min() | |
amin = arr.min() | |
return (arr-amin)*255/rng | |
def main(): | |
path = "D:/PyCharmProjects/EvoArt/Temp" | |
os.chdir(path) | |
img1 = to_grayscale(imread("Pic1.png").astype(float)) | |
img2 = to_grayscale(imread("Pic.png").astype(float)) | |
n_m, n_0 = compare_images(img1, img2) | |
print("Manhattan norm:", n_m, "/ per pixel:", n_m / img1.size) | |
print("Zero norm:", n_0, "/ per pixel:", n_0 * 1.0 / img1.size) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment