Created
November 9, 2021 19:39
-
-
Save erm3nda/dffd6302b37607a0f5c45f25f6fb3307 to your computer and use it in GitHub Desktop.
Compares images based on pixel modifications between original file (jpg,png) and converted an resized jpg from that original. Fixed RGBA problem when saving to JPEG with PIL.
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 io | |
from PIL import Image | |
import numpy as np | |
def countDiff(img1, img2): | |
s = 0 | |
if img1.size != img2.size or img1.getbands() != img2.getbands(): | |
return -1 | |
for band_index, band in enumerate(img1.getbands()): | |
m1 = np.array([p[band_index] for p in img1.getdata()]).reshape(*img1.size) | |
m2 = np.array([p[band_index] for p in img2.getdata()]).reshape(*img2.size) | |
s += np.sum(np.abs(m1 - m2)) | |
return s | |
def compare(im1, im2): | |
img1 = Image.open(im1) | |
img2 = Image.open(im2) | |
if img1.size != img2.size: | |
img2 = img2.resize(img1.size, resample=Image.BILINEAR) | |
if img1.format == "PNG": | |
print(img1.format) | |
print("Converting " + img1.format + " image to RGB") | |
buff = io.BytesIO() | |
if img1.mode == "RGBA": | |
img1.load() # required for img1.split() | |
rgb = Image.new("RGB", img1.size, (255, 255, 255)) | |
print("Modo de la nueva imagen creada: " + rgb.mode) | |
print(rgb.mode) | |
rgb.paste(img1, mask=img1.split()[3]) # 3 is the alpha channel | |
rgb.save(buff, 'JPEG', quality=80) | |
# put back everything to original variable img1 | |
img1 = Image.open(buff) # load into Image | |
print("Buffered image mode: " + img1.mode) | |
print("Image should be now JPEG in memory, result: "+ img1.format) | |
else: | |
img1.convert("RGB") | |
print("Waiting result for countDiff()") | |
return countDiff(img1, img2) | |
''' | |
Most of the code gotten from StakOverflow, but had to tweak few things and used io.BytesIO to avoid writting to files. | |
compare("original_image.png", "converted_and_resized_image.jpg") | |
Returns: | |
PNG | |
Converting PNG image to RGB | |
Waiting result for countDiff() | |
36423731 | |
compare("original_image_modified.png", "converted_and_resized_image.jpg") | |
Returns: | |
PNG | |
Converting PNG image to RGB | |
Modo de la nueva imagen creada: RGB | |
RGB | |
Buffered image mode: RGB | |
Image should be now JPEG in memory, result: JPEG | |
Waiting result for countDiff() | |
39863802 | |
This means, that because the value for original_image is lower than original_image_modified, the converted_and_resized_image is much more than the original_image than the original_modified_image, which is totally TRUE | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment