Goal
I need to check if one image is a "sub set of another image". I am using following two functions, which seem to be working occasionally, but I am looking for some improvements to make it reliable. The functions, I am using are A and B below. Their goal is to check if image X is a subset of Y - or in other words check if Y image contains image X. ( The caller function takes care of which images to pass )
Note: The terminology of super-set, sub-set, union and intersection is adapted from set theory, if it helps to understand the question.
Caveat:
The images may not be "pixel same", but they might look exactly same to naked eye. Hence the functions A and B below are returning a number using
getImageDifference
, where 0 is a perfect absolute match, and non zero numbers are treated relatively by callee function based on what is being returned for other queries.Only Pillow (PIL) and/or NumPy could be used
Functions
- function A : if X is subset of Y, then the intersection of X and Y is X
- function B : if x is subset of Y, then the union of X and Y is Y
Related articles :
https://wildclick.wordpress.com/2016/07/09/python-pil-pillow-numpy-intersect-images/ and https://wildclick.wordpress.com/2016/07/08/python-pil-pillow-numpy-add-images/
Existing Code :
Image Comparer
def getImageDifference(self, x, y):
# Calculate the difference b/w two images, works
return diff3
pass
Function A and B
def A(self, x, y):
'''
check if image X is a subset of Y, using intersection
:param x:
:param y:
:return:
'''
xx = Image.open(self.getImagePathByName(x)).convert(mode='L', dither=Image.NONE)
yy = Image.open(self.getImagePathByName(y)).convert(mode='L', dither=Image.NONE)
pixelThreshold = 200
xx = np.array(xx)
xx = np.where(xx > pixelThreshold, 255, 0)
yy = np.array(yy)
yy = np.where(yy > pixelThreshold, 255, 0)
intersection = (xx + yy)
# if xx is a subset of yy then the intersection of xx and yy, is xx
xx = Image.open(self.getImagePathByName(x)).convert(mode='L', dither=Image.NONE)
intersection = Image.fromarray(intersection.astype(np.uint8)).convert(mode='L', dither=Image.NONE)
difference = self.getImageDifference(xx, intersection)
return difference
pass
def B(self, x, y):
'''
check if image X is a subset of Y, using union
:param x:
:param y:
:return:
'''
xx = Image.open(self.getImagePathByName(x)).convert(mode='L', dither=Image.NONE)
yy = Image.open(self.getImagePathByName(y)).convert(mode='L', dither=Image.NONE)
pixelThreshold = 200
xx = np.array(xx)
xx = np.where(xx > pixelThreshold, 255, 0)
yy = np.array(yy)
yy = np.where(yy > pixelThreshold, 255, 0)
union = (xx + yy) / 2
union = np.where(union > pixelThreshold, 255, 0)
# if xx is a subset of yy then the union of xx and yy, is yy
yy = Image.open(self.getImagePathByName(y)).convert(mode='L', dither=Image.NONE)
union = Image.fromarray(union.astype(np.uint8)).convert(mode='L', dither=Image.NONE)
difference = self.getImageDifference(yy, union)
return difference
pass