From 9026b81439251925a6cc3b15cde71e2938dd0aa7 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 28 Aug 2015 22:54:17 +1000 Subject: [PATCH] Check that images are L mode in ImageMorph methods --- PIL/ImageMorph.py | 9 +++++++++ Tests/test_imagemorph.py | 10 +++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/PIL/ImageMorph.py b/PIL/ImageMorph.py index 6f92e9e67..44a7e8c04 100644 --- a/PIL/ImageMorph.py +++ b/PIL/ImageMorph.py @@ -198,6 +198,9 @@ class MorphOp(object): if self.lut is None: raise Exception('No operator loaded') + if image.mode != 'L': + raise Exception('Image must be binary, meaning it must use mode L') + return outimage = Image.new(image.mode, image.size, None) count = _imagingmorph.apply( bytes(self.lut), image.im.id, outimage.im.id) @@ -212,6 +215,9 @@ class MorphOp(object): if self.lut is None: raise Exception('No operator loaded') + if image.mode != 'L': + raise Exception('Image must be binary, meaning it must use mode L') + return return _imagingmorph.match(bytes(self.lut), image.im.id) def get_on_pixels(self, image): @@ -220,6 +226,9 @@ class MorphOp(object): Returns a list of tuples of (x,y) coordinates of all matching pixels.""" + if image.mode != 'L': + raise Exception('Image must be binary, meaning it must use mode L') + return return _imagingmorph.get_on_pixels(image.im.id) def load_lut(self, filename): diff --git a/Tests/test_imagemorph.py b/Tests/test_imagemorph.py index bbb3ae190..a3d1dd8b1 100644 --- a/Tests/test_imagemorph.py +++ b/Tests/test_imagemorph.py @@ -1,5 +1,5 @@ # Test the ImageMorphology functionality -from helper import unittest, PillowTestCase +from helper import unittest, PillowTestCase, hopper from PIL import Image from PIL import ImageMorph @@ -168,6 +168,14 @@ class MorphTests(PillowTestCase): self.assertEqual(len(coords), 4) self.assertEqual(tuple(coords), ((2, 2), (4, 2), (2, 4), (4, 4))) + def test_non_binary_images(self): + im = hopper('RGB') + mop = ImageMorph.MorphOp(op_name="erosion8") + + self.assertRaises(Exception, lambda: mop.apply(im)) + self.assertRaises(Exception, lambda: mop.match(im)) + self.assertRaises(Exception, lambda: mop.get_on_pixels(im)) + if __name__ == '__main__': unittest.main()