Merge pull request #2011 from vlmath/master

Add ImageOps.scale to expand or contract a PIL image by a factor
This commit is contained in:
wiredfool 2016-08-06 22:19:50 +01:00 committed by GitHub
commit ffa18c8efd
2 changed files with 37 additions and 0 deletions

View File

@ -178,6 +178,27 @@ def crop(image, border=0):
)
def scale(image, factor, resample=Image.NEAREST):
"""
Returns a rescaled image by a specific factor given in parameter.
A factor greater than 1 expands the image, between 0 and 1 contracts the
image.
:param factor: The expansion factor, as a float.
:param resample: An optional resampling filter. Same values possible as
in the PIL.Image.resize function.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if factor == 1:
return image.copy()
elif factor <= 0:
raise ValueError("the factor must be greater than 0")
else:
size = (int(round(factor * image.width)),
int(round(factor * image.height)))
return image.resize(size, resample)
def deform(image, deformer, resample=Image.BILINEAR):
"""
Deform the image.

View File

@ -78,6 +78,22 @@ class TestImageOps(PillowTestCase):
ImageOps.equalize(i.convert("P"))
ImageOps.equalize(i.convert("RGB"))
def test_scale(self):
# Test the scaling function
i = hopper("L").resize((50, 50))
with self.assertRaises(ValueError):
ImageOps.scale(i, -1)
newimg = ImageOps.scale(i, 1)
self.assertEqual(newimg.size, (50, 50))
newimg = ImageOps.scale(i, 2)
self.assertEqual(newimg.size, (100, 100))
newimg = ImageOps.scale(i, 0.5)
self.assertEqual(newimg.size, (25, 25))
if __name__ == '__main__':
unittest.main()