blob: e42f7e16a91e31dd5fd6de748af24f6852f66ee7 [file] [log] [blame]
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Compare two images for equality, subject to a mask."""
from PIL import Image
from PIL import ImageChops
import os.path
def Compare(file1, file2, **kwargs):
"""Compares two images to see if they're identical subject to a mask.
An optional directory containing masks is supplied. If a mask exists
which matches file1's name, areas under the mask where it's black
are ignored.
file1: path to first image to compare
file2: path to second image to compare
kwargs: ["maskdir"] contains the directory holding the masks
None if the images are identical
A tuple of (errorstring, image) if they're not
maskdir = None
if "maskdir" in kwargs:
maskdir = kwargs["maskdir"]
im1 =
im2 =
if im1.size != im2.size:
return ("The images are of different size (%r vs %r)" %
(im1.size, im2.size), im1)
diff = ImageChops.difference(im1, im2)
if maskdir:
maskfile = os.path.join(maskdir, os.path.basename(file1))
if os.path.exists(maskfile):
mask =
if mask.size != im1.size:
return ("The mask is of a different size than the images (%r vs %r)" %
(mask.size, im1.size), mask)
diff = ImageChops.multiply(diff, mask.convert(diff.mode))
if max(diff.getextrema()) != (0, 0):
return ("The images differ", diff)
return None