def test__new(self): from PIL import ImagePalette im = hopper('RGB') im_p = hopper('P') blank_p = Image.new('P', (10, 10)) blank_pa = Image.new('PA', (10, 10)) blank_p.palette = None blank_pa.palette = None def _make_new(base_image, im, palette_result=None): new_im = base_image._new(im) self.assertEqual(new_im.mode, im.mode) self.assertEqual(new_im.size, im.size) self.assertEqual(new_im.info, base_image.info) if palette_result is not None: self.assertEqual(new_im.palette.tobytes(), palette_result.tobytes()) else: self.assertIsNone(new_im.palette) _make_new(im, im_p, im_p.palette) _make_new(im_p, im, None) _make_new(im, blank_p, ImagePalette.ImagePalette()) _make_new(im, blank_pa, ImagePalette.ImagePalette())
def test_copy(self): croppedCoordinates = (10, 10, 20, 20) croppedSize = (10, 10) for mode in "1", "P", "L", "RGB", "I", "F": # Internal copy method im = hopper(mode) out = im.copy() self.assertEqual(out.mode, im.mode) self.assertEqual(out.size, im.size) # Python's copy method im = hopper(mode) out = copy.copy(im) self.assertEqual(out.mode, im.mode) self.assertEqual(out.size, im.size) # Internal copy method on a cropped image im = hopper(mode) out = im.crop(croppedCoordinates).copy() self.assertEqual(out.mode, im.mode) self.assertEqual(out.size, croppedSize) # Python's copy method on a cropped image im = hopper(mode) out = copy.copy(im.crop(croppedCoordinates)) self.assertEqual(out.mode, im.mode) self.assertEqual(out.size, croppedSize)
def test_subsampling(self): def getsampling(im): layer = im.layer return layer[0][1:3] + layer[1][1:3] + layer[2][1:3] # experimental API im = self.roundtrip(hopper(), subsampling=-1) # default self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling=0) # 4:4:4 self.assertEqual(getsampling(im), (1, 1, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling=1) # 4:2:2 self.assertEqual(getsampling(im), (2, 1, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling=2) # 4:2:0 self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling=3) # default (undefined) self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling="4:4:4") self.assertEqual(getsampling(im), (1, 1, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling="4:2:2") self.assertEqual(getsampling(im), (2, 1, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling="4:2:0") self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) im = self.roundtrip(hopper(), subsampling="4:1:1") self.assertEqual(getsampling(im), (2, 2, 1, 1, 1, 1)) self.assertRaises( TypeError, self.roundtrip, hopper(), subsampling="1:1:1")
def test_auxiliary_channels_isolated(self): # test data in aux channels does not affect non-aux channels aux_channel_formats = [ # format, profile, color-only format, source test image ('RGBA', 'sRGB', 'RGB', hopper('RGBA')), ('RGBX', 'sRGB', 'RGB', hopper('RGBX')), ('LAB', 'LAB', 'LAB', Image.open('Tests/images/hopper.Lab.tif')), ] for src_format in aux_channel_formats: for dst_format in aux_channel_formats: for transform_in_place in [True, False]: # inplace only if format doesn't change if transform_in_place and src_format[0] != dst_format[0]: continue # convert with and without AUX data, test colors are equal source_profile = ImageCms.createProfile(src_format[1]) destination_profile = ImageCms.createProfile(dst_format[1]) source_image = src_format[3] test_transform = ImageCms.buildTransform(source_profile, destination_profile, inMode=src_format[0], outMode=dst_format[0]) # test conversion from aux-ful source if transform_in_place: test_image = source_image.copy() ImageCms.applyTransform(test_image, test_transform, inPlace=True) else: test_image = ImageCms.applyTransform(source_image, test_transform, inPlace=False) # reference conversion from aux-less source reference_transform = ImageCms.buildTransform(source_profile, destination_profile, inMode=src_format[2], outMode=dst_format[2]) reference_image = ImageCms.applyTransform(source_image.convert(src_format[2]), reference_transform) self.assert_image_equal(test_image.convert(dst_format[2]), reference_image)
def test_save_to_bytes(self): output = io.BytesIO() im = hopper() im.save(output, "ico", sizes=[(32, 32), (64, 64)]) # the default image output.seek(0) reloaded = Image.open(output) self.assertEqual(reloaded.info['sizes'], set([(32, 32), (64, 64)])) self.assertEqual(im.mode, reloaded.mode) self.assertEqual((64, 64), reloaded.size) self.assertEqual(reloaded.format, "ICO") self.assert_image_equal(reloaded, hopper().resize((64, 64), Image.LANCZOS)) # the other one output.seek(0) reloaded = Image.open(output) reloaded.size = (32, 32) self.assertEqual(im.mode, reloaded.mode) self.assertEqual((32, 32), reloaded.size) self.assertEqual(reloaded.format, "ICO") self.assert_image_equal(reloaded, hopper().resize((32, 32), Image.LANCZOS))
def test_write_rgb(self): """ Can we write a RGB mode file to webp without error. Does it have the bits we expect? """ temp_file = self.tempfile("temp.webp") hopper("RGB").save(temp_file) image = Image.open(temp_file) image.load() self.assertEqual(image.mode, "RGB") self.assertEqual(image.size, (128, 128)) self.assertEqual(image.format, "WEBP") image.load() image.getdata() # If we're using the exact same version of WebP, this test should pass. # but it doesn't if the WebP is generated on Ubuntu and tested on # Fedora. # generated with: dwebp -ppm temp.webp -o hopper_webp_write.ppm # target = Image.open('Tests/images/hopper_webp_write.ppm') # self.assert_image_equal(image, target) # This test asserts that the images are similar. If the average pixel # difference between the two images is less than the epsilon value, # then we're going to accept that it's a reasonable lossy version of # the image. The old lena images for WebP are showing ~16 on # Ubuntu, the jpegs are showing ~18. target = hopper("RGB") self.assert_image_similar(image, target, 12)
def test_sanity(self): for mode in ('1', 'L', 'P', 'RGB'): self._roundtrip(hopper(mode)) # Test an unsupported mode f = self.tempfile("temp.pcx") self.assertRaises(ValueError, lambda: hopper("RGBA").save(f))
def test_write_rgb(self): """ Can we write a RGB mode file to webp without error. Does it have the bits we expect? """ temp_file = self.tempfile("temp.webp") hopper(self.rgb_mode).save(temp_file) image = Image.open(temp_file) self.assertEqual(image.mode, self.rgb_mode) self.assertEqual(image.size, (128, 128)) self.assertEqual(image.format, "WEBP") image.load() image.getdata() # generated with: dwebp -ppm temp.webp -o hopper_webp_write.ppm self.assert_image_similar_tofile( image, 'Tests/images/hopper_webp_write.ppm', 12.0) # This test asserts that the images are similar. If the average pixel # difference between the two images is less than the epsilon value, # then we're going to accept that it's a reasonable lossy version of # the image. The old lena images for WebP are showing ~16 on # Ubuntu, the jpegs are showing ~18. target = hopper(self.rgb_mode) self.assert_image_similar(image, target, 12.0)
def test_sanity(self): self.roundtrip(hopper()) self.roundtrip(hopper("1")) self.roundtrip(hopper("L")) self.roundtrip(hopper("P")) self.roundtrip(hopper("RGB"))
def test_optimize(self): im1 = self.roundtrip(hopper()) im2 = self.roundtrip(hopper(), optimize=0) im3 = self.roundtrip(hopper(), optimize=1) self.assert_image_equal(im1, im2) self.assert_image_equal(im1, im3) self.assertGreaterEqual(im1.bytes, im2.bytes) self.assertGreaterEqual(im1.bytes, im3.bytes)
def test_rgba_p(self): im = hopper('RGBA') im.putalpha(hopper('L')) converted = im.convert('P') comparable = converted.convert('RGBA') self.assert_image_similar(im, comparable, 20)
def test_sanity(self): # FIXME: assert_image # Implicit asserts no exception: ImageEnhance.Color(hopper()).enhance(0.5) ImageEnhance.Contrast(hopper()).enhance(0.5) ImageEnhance.Brightness(hopper()).enhance(0.5) ImageEnhance.Sharpness(hopper()).enhance(0.5)
def test_p_la(self): im = hopper('RGBA') alpha = hopper('L') im.putalpha(alpha) comparable = im.convert('P').convert('LA').split()[1] self.assert_image_similar(alpha, comparable, 5)
def test_sanity(self): im = hopper() im = im.quantize() self.assert_image(im, "P", im.size) im = hopper() im = im.quantize(palette=hopper("P")) self.assert_image(im, "P", im.size)
def test_convert(self): im = hopper('RGB').convert('HSV') comparable = self.to_hsv_colorsys(hopper('RGB')) self.assert_image_similar(im.getchannel(0), comparable.getchannel(0), 1, "Hue conversion is wrong") self.assert_image_similar(im.getchannel(1), comparable.getchannel(1), 1, "Saturation conversion is wrong") self.assert_image_similar(im.getchannel(2), comparable.getchannel(2), 1, "Value conversion is wrong")
def test_pdf_append_to_bytesio(self): im = hopper("RGB") f = io.BytesIO() im.save(f, format="PDF") initial_size = len(f.getvalue()) self.assertGreater(initial_size, 0) im = hopper("P") f = io.BytesIO(f.getvalue()) im.save(f, format="PDF", append=True) self.assertGreater(len(f.getvalue()), initial_size)
def test_sanity(self): file = self.tempfile("temp.msp") hopper("1").save(file) im = Image.open(file) im.load() self.assertEqual(im.mode, "1") self.assertEqual(im.size, (128, 128)) self.assertEqual(im.format, "MSP")
def test_convolution_modes(self): self.assertRaises(ValueError, self.resize, hopper("1"), (15, 12), Image.BILINEAR) self.assertRaises(ValueError, self.resize, hopper("P"), (15, 12), Image.BILINEAR) self.assertRaises(ValueError, self.resize, hopper("I;16"), (15, 12), Image.BILINEAR) for mode in ["L", "I", "F", "RGB", "RGBA", "CMYK", "YCbCr"]: im = hopper(mode) r = self.resize(im, (15, 12), Image.BILINEAR) self.assertEqual(r.mode, mode) self.assertEqual(r.size, (15, 12)) self.assertEqual(r.im.bands, im.im.bands)
def test_sanity(self): image = hopper() converted = image.quantize() self.assert_image(converted, 'P', converted.size) self.assert_image_similar(converted.convert('RGB'), image, 10) image = hopper() converted = image.quantize(palette=hopper('P')) self.assert_image(converted, 'P', converted.size) self.assert_image_similar(converted.convert('RGB'), image, 60)
def test_progressive(self): im1 = self.roundtrip(hopper()) im2 = self.roundtrip(hopper(), progressive=False) im3 = self.roundtrip(hopper(), progressive=True) self.assertFalse(im1.info.get("progressive")) self.assertFalse(im2.info.get("progressive")) self.assertTrue(im3.info.get("progressive")) self.assert_image_equal(im1, im3) self.assertGreaterEqual(im1.bytes, im3.bytes)
def test_1pxfit(self): # Division by zero in equalize if image is 1 pixel high newimg = ImageOps.fit(hopper("RGB").resize((1, 1)), (35, 35)) self.assertEqual(newimg.size, (35, 35)) newimg = ImageOps.fit(hopper("RGB").resize((1, 100)), (35, 35)) self.assertEqual(newimg.size, (35, 35)) newimg = ImageOps.fit(hopper("RGB").resize((100, 1)), (35, 35)) self.assertEqual(newimg.size, (35, 35))
def test_sanity(self): self.assertRaises(ValueError, lambda: hopper().tobitmap()) im1 = hopper().convert("1") bitmap = im1.tobitmap() self.assertIsInstance(bitmap, bytes) self.assert_image_equal(im1, fromstring(bitmap))
def test_progressive_compat(self): im1 = self.roundtrip(hopper()) im2 = self.roundtrip(hopper(), progressive=1) im3 = self.roundtrip(hopper(), progression=1) # compatibility self.assert_image_equal(im1, im2) self.assert_image_equal(im1, im3) self.assertFalse(im1.info.get("progressive")) self.assertFalse(im1.info.get("progression")) self.assertTrue(im2.info.get("progressive")) self.assertTrue(im2.info.get("progression")) self.assertTrue(im3.info.get("progressive")) self.assertTrue(im3.info.get("progression"))
def test_with_underscores(self): # Arrange: use underscores kwargs = {"resolution_unit": "inch", "x_resolution": 72, "y_resolution": 36} filename = self.tempfile("temp.tif") # Act hopper("RGB").save(filename, **kwargs) # Assert from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION im = Image.open(filename) self.assertEqual(im.tag.tags[X_RESOLUTION][0][0], 72) self.assertEqual(im.tag.tags[Y_RESOLUTION][0][0], 36)
def test_lab_roundtrip(self): # check to see if we're at least internally consistent. pLab = ImageCms.createProfile("LAB") t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB") t2 = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB") i = ImageCms.applyTransform(hopper(), t) self.assertEqual(i.info['icc_profile'], ImageCmsProfile(pLab).tobytes()) out = ImageCms.applyTransform(i, t2) self.assert_image_similar(hopper(), out, 2)
def test_with_underscores(self): kwargs = {'resolution_unit': 'inch', 'x_resolution': 72, 'y_resolution': 36} filename = self.tempfile("temp.tif") hopper("RGB").save(filename, **kwargs) im = Image.open(filename) # legacy interface self.assertEqual(im.tag[X_RESOLUTION][0][0], 72) self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36) # v2 interface self.assertEqual(im.tag_v2[X_RESOLUTION], 72) self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)
def test_write_lossless_rgb(self): temp_file = self.tempfile("temp.webp") hopper(self.rgb_mode).save(temp_file, lossless=True) image = Image.open(temp_file) image.load() self.assertEqual(image.mode, self.rgb_mode) self.assertEqual(image.size, (128, 128)) self.assertEqual(image.format, "WEBP") image.load() image.getdata() self.assert_image_equal(image, hopper(self.rgb_mode))
def test_with_underscores(self): kwargs = {"resolution_unit": "inch", "x_resolution": 72, "y_resolution": 36} filename = self.tempfile("temp.tif") hopper("RGB").save(filename, **kwargs) from PIL.TiffImagePlugin import X_RESOLUTION, Y_RESOLUTION im = Image.open(filename) # legacy interface self.assertEqual(im.tag[X_RESOLUTION][0][0], 72) self.assertEqual(im.tag[Y_RESOLUTION][0][0], 36) # v2 interface self.assertEqual(im.tag_v2[X_RESOLUTION], 72) self.assertEqual(im.tag_v2[Y_RESOLUTION], 36)
def test_split_merge(self): def split_merge(mode): return Image.merge(mode, hopper(mode).split()) self.assert_image_equal(hopper("1"), split_merge("1")) self.assert_image_equal(hopper("L"), split_merge("L")) self.assert_image_equal(hopper("I"), split_merge("I")) self.assert_image_equal(hopper("F"), split_merge("F")) self.assert_image_equal(hopper("P"), split_merge("P")) self.assert_image_equal(hopper("RGB"), split_merge("RGB")) self.assert_image_equal(hopper("RGBA"), split_merge("RGBA")) self.assert_image_equal(hopper("CMYK"), split_merge("CMYK")) self.assert_image_equal(hopper("YCbCr"), split_merge("YCbCr"))
def test_sanity(self): im1 = hopper() im2 = Image.new(im1.mode, im1.size, 0) for y in range(im1.size[1]): for x in range(im1.size[0]): pos = x, y im2.putpixel(pos, im1.getpixel(pos)) self.assert_image_equal(im1, im2) im2 = Image.new(im1.mode, im1.size, 0) im2.readonly = 1 for y in range(im1.size[1]): for x in range(im1.size[0]): pos = x, y im2.putpixel(pos, im1.getpixel(pos)) self.assertFalse(im2.readonly) self.assert_image_equal(im1, im2) im2 = Image.new(im1.mode, im1.size, 0) pix1 = im1.load() pix2 = im2.load() for y in range(im1.size[1]): for x in range(im1.size[0]): pix2[x, y] = pix1[x, y] self.assert_image_equal(im1, im2)
def copy(mode): im = hopper(mode) out = im.copy() self.assertEqual(out.mode, mode) self.assertEqual(out.size, im.size)
def test_sanity(self): data = hopper().tobytes() self.assertIsInstance(data, bytes)
def crop(mode): out = hopper(mode).crop((50, 50, 100, 100)) self.assertEqual(out.mode, mode) self.assertEqual(out.size, (50, 50))
def test_missing_method_data(self): im = hopper() self.assertRaises(ValueError, im.transform, (100, 100), None)
def test_repr_png(self): im = hopper() repr_png = Image.open(BytesIO(im._repr_png_())) self.assertEqual(repr_png.format, 'PNG') self.assert_image_equal(im, repr_png)
def test_remap_palette(self): # Test illegal image mode im = hopper() self.assertRaises(ValueError, im.remap_palette, None)
def test_mode_mismatch(self): im = hopper("RGB").copy() self.assertRaises(ValueError, lambda: ImageDraw.ImageDraw(im, mode="L"))
def test_save_rgba(self): im = hopper("RGBA") outfile = self.tempfile("temp.tif") im.save(outfile)
def test_getbands(self): # Assert self.assertEqual(hopper('RGB').getbands(), ('R', 'G', 'B')) self.assertEqual(hopper('YCbCr').getbands(), ('Y', 'Cb', 'Cr'))
def test_unknown_extension(self): im = hopper() temp_file = self.tempfile("temp.unknown") self.assertRaises(ValueError, im.save, temp_file)
def test_image_mode_not_supported(self): im = hopper("RGBA") tmpfile = self.tempfile('temp.eps') self.assertRaises(ValueError, lambda: im.save(tmpfile))
def split(mode): layers = hopper(mode).split() return [(i.mode, i.size[0], i.size[1]) for i in layers]
def split_open(mode): hopper(mode).save(test_file) im = Image.open(test_file) return len(im.split())
def test_save_unsupported_mode(self): im = hopper("HSV") outfile = self.tempfile("temp.tif") self.assertRaises(IOError, lambda: im.save(outfile))
def test_isatty(self): im = hopper() container = ContainerIO.ContainerIO(im, 0, 0) self.assertEqual(container.isatty(), 0)
def test_sanity(self): filename = self.tempfile("temp.tif") hopper("RGB").save(filename) im = Image.open(filename) im.load() self.assertEqual(im.mode, "RGB") self.assertEqual(im.size, (128, 128)) self.assertEqual(im.format, "TIFF") hopper("1").save(filename) im = Image.open(filename) hopper("L").save(filename) im = Image.open(filename) hopper("P").save(filename) im = Image.open(filename) hopper("RGB").save(filename) im = Image.open(filename) hopper("I").save(filename) im = Image.open(filename)
def _to_array(mode, dtype): img = hopper(mode) np_img = numpy.array(img) self._test_img_equals_nparray(img, np_img) self.assertEqual(np_img.dtype, numpy.dtype(dtype))
def test_unsupported_mode(self): im = hopper("LA") outfile = self.tempfile("temp_LA.pdf") self.assertRaises(ValueError, im.save, outfile)
def test_offset_not_implemented(self): # Arrange im = hopper() # Act / Assert self.assertRaises(NotImplementedError, im.offset, None)
def test_both(self): im = hopper('L') with self.count(2): im.resize((im.size[0] - 10, im.size[1] - 10), Image.BILINEAR)
def _test_image(self): im = hopper('RGB') return im.crop((10, 20, im.width - 10, im.height - 20))
def test_vertical(self): im = hopper('L') with self.count(1): im.resize((im.size[0], im.size[1] - 10), Image.BILINEAR)
def test_getchunks(self): im = hopper() chunks = PngImagePlugin.getchunks(im) self.assertEqual(len(chunks), 3)
def test_horizontal(self): im = hopper('L') with self.count(1): im.resize((im.size[0] - 10, im.size[1]), Image.BILINEAR)
def test_rt_metadata(self): """ Test writing arbitrary metadata into the tiff image directory Use case is ImageJ private tags, one numeric, one arbitrary data. https://github.com/python-pillow/Pillow/issues/291 """ img = hopper() # Behaviour change: re #1416 # Pre ifd rewrite, ImageJMetaData was being written as a string(2), # Post ifd rewrite, it's defined as arbitrary bytes(7). It should # roundtrip with the actual bytes, rather than stripped text # of the premerge tests. # # For text items, we still have to decode('ascii','replace') because # the tiff file format can't take 8 bit bytes in that field. basetextdata = "This is some arbitrary metadata for a text field" bindata = basetextdata.encode('ascii') + b" \xff" textdata = basetextdata + " " + chr(255) reloaded_textdata = basetextdata + " ?" floatdata = 12.345 doubledata = 67.89 info = TiffImagePlugin.ImageFileDirectory() ImageJMetaData = tag_ids['ImageJMetaData'] ImageJMetaDataByteCounts = tag_ids['ImageJMetaDataByteCounts'] ImageDescription = tag_ids['ImageDescription'] info[ImageJMetaDataByteCounts] = len(bindata) info[ImageJMetaData] = bindata info[tag_ids['RollAngle']] = floatdata info.tagtype[tag_ids['RollAngle']] = 11 info[tag_ids['YawAngle']] = doubledata info.tagtype[tag_ids['YawAngle']] = 12 info[ImageDescription] = textdata f = self.tempfile("temp.tif") img.save(f, tiffinfo=info) loaded = Image.open(f) self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (len(bindata), )) self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (len(bindata), )) self.assertEqual(loaded.tag[ImageJMetaData], bindata) self.assertEqual(loaded.tag_v2[ImageJMetaData], bindata) self.assertEqual(loaded.tag[ImageDescription], (reloaded_textdata, )) self.assertEqual(loaded.tag_v2[ImageDescription], reloaded_textdata) loaded_float = loaded.tag[tag_ids['RollAngle']][0] self.assertAlmostEqual(loaded_float, floatdata, places=5) loaded_double = loaded.tag[tag_ids['YawAngle']][0] self.assertAlmostEqual(loaded_double, doubledata) # check with 2 element ImageJMetaDataByteCounts, issue #2006 info[ImageJMetaDataByteCounts] = (8, len(bindata) - 8) img.save(f, tiffinfo=info) loaded = Image.open(f) self.assertEqual(loaded.tag[ImageJMetaDataByteCounts], (8, len(bindata) - 8)) self.assertEqual(loaded.tag_v2[ImageJMetaDataByteCounts], (8, len(bindata) - 8))
def test_sanity(self): im1 = hopper() im2 = Image.frombytes(im1.mode, im1.size, im1.tobytes()) self.assert_image_equal(im1, im2)
def test_sanity(self): # internal version number self.assertRegexpMatches(Image.core.zlib_version, "\d+\.\d+\.\d+(\.\d+)?$") file = self.tempfile("temp.png") hopper("RGB").save(file) im = Image.open(file) im.load() self.assertEqual(im.mode, "RGB") self.assertEqual(im.size, (128, 128)) self.assertEqual(im.format, "PNG") hopper("1").save(file) im = Image.open(file) hopper("L").save(file) im = Image.open(file) hopper("P").save(file) im = Image.open(file) hopper("RGB").save(file) im = Image.open(file) hopper("I").save(file) im = Image.open(file)
def test_both(self): im = hopper('L') count = Image.core.getcount() im.resize((im.size[0] + 10, im.size[1] + 10), Image.BILINEAR) self.assertEqual(Image.core.getcount(), count + 2)
def split_merge(mode): return Image.merge(mode, hopper(mode).split())
def test_not_implemented(self): self.assertIsNone(PyAccess.new(hopper("BGR;15")))