Merge pull request #693 from hugovk/unittest0

Start using unittest for tests
This commit is contained in:
Alex Clark ☺ 2014-06-08 07:02:02 -04:00
commit 001b46c670
118 changed files with 3133 additions and 2388 deletions

View File

@ -14,7 +14,8 @@ python:
install:
- "sudo apt-get -qq install libfreetype6-dev liblcms2-dev python-qt4 ghostscript libffi-dev cmake"
- "pip install cffi"
- "pip install coveralls"
- "pip install coveralls nose"
- if [ "$TRAVIS_PYTHON_VERSION" == "2.6" ]; then pip install unittest2; fi
# webp
- pushd depends && ./install_webp.sh && popd
@ -28,18 +29,23 @@ script:
- python setup.py build_ext --inplace
# Don't cover PyPy: it fails intermittently and is x5.8 slower (#640)
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then python selftest.py; fi
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then python Tests/run.py; fi
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then time python selftest.py; fi
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then time nosetests test/; fi
- if [ "$TRAVIS_PYTHON_VERSION" == "pypy" ]; then time python Tests/run.py; fi
# Cover the others
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then coverage run --append --include=PIL/* selftest.py; fi
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then python Tests/run.py --coverage; fi
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then time coverage run --append --include=PIL/* selftest.py; fi
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then time coverage run --append --include=PIL/* -m nose test/; fi
- if [ "$TRAVIS_PYTHON_VERSION" != "pypy" ]; then time python Tests/run.py --coverage; fi
after_success:
- coverage report
- coveralls
- pip install pep8 pyflakes
- pep8 --statistics --count PIL/*.py
- pep8 --statistics --count Tests/*.py
- pep8 --statistics --count test/*.py
- pep8 --statistics --count Tests/*.py
- pyflakes PIL/*.py | tee >(wc -l)
- pyflakes test/*.py | tee >(wc -l)
- pyflakes Tests/*.py | tee >(wc -l)

View File

@ -1,17 +0,0 @@
import unittest
class PillowTests(unittest.TestCase):
"""
Can we start moving the test suite here?
"""
def test_suite_should_move_here(self):
"""
Great idea!
"""
assert True is True
if __name__ == '__main__':
unittest.main()

View File

@ -1,24 +0,0 @@
from __future__ import print_function
from tester import *
import PIL
import PIL.Image
# Make sure we have the binary extension
im = PIL.Image.core.new("L", (100, 100))
assert PIL.Image.VERSION[:3] == '1.1'
# Create an image and do stuff with it.
im = PIL.Image.new("1", (100, 100))
assert (im.mode, im.size) == ('1', (100, 100))
assert len(im.tobytes()) == 1300
# Create images in all remaining major modes.
im = PIL.Image.new("L", (100, 100))
im = PIL.Image.new("P", (100, 100))
im = PIL.Image.new("RGB", (100, 100))
im = PIL.Image.new("I", (100, 100))
im = PIL.Image.new("F", (100, 100))
print("ok")

View File

@ -1,86 +0,0 @@
from tester import *
from PIL import Image
import os
base = os.path.join('Tests', 'images', 'bmp')
def get_files(d, ext='.bmp'):
return [os.path.join(base,d,f) for f
in os.listdir(os.path.join(base, d)) if ext in f]
def test_bad():
""" These shouldn't crash/dos, but they shouldn't return anything either """
for f in get_files('b'):
try:
im = Image.open(f)
im.load()
except Exception as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_questionable():
""" These shouldn't crash/dos, but its not well defined that these are in spec """
for f in get_files('q'):
try:
im = Image.open(f)
im.load()
except Exception as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_good():
""" These should all work. There's a set of target files in the
html directory that we can compare against. """
# Target files, if they're not just replacing the extension
file_map = { 'pal1wb.bmp': 'pal1.png',
'pal4rle.bmp': 'pal4.png',
'pal8-0.bmp': 'pal8.png',
'pal8rle.bmp': 'pal8.png',
'pal8topdown.bmp': 'pal8.png',
'pal8nonsquare.bmp': 'pal8nonsquare-v.png',
'pal8os2.bmp': 'pal8.png',
'pal8os2sp.bmp': 'pal8.png',
'pal8os2v2.bmp': 'pal8.png',
'pal8os2v2-16.bmp': 'pal8.png',
'pal8v4.bmp': 'pal8.png',
'pal8v5.bmp': 'pal8.png',
'rgb16-565pal.bmp': 'rgb16-565.png',
'rgb24pal.bmp': 'rgb24.png',
'rgb32.bmp': 'rgb24.png',
'rgb32bf.bmp': 'rgb24.png'
}
def get_compare(f):
(head, name) = os.path.split(f)
if name in file_map:
return os.path.join(base, 'html', file_map[name])
(name,ext) = os.path.splitext(name)
return os.path.join(base, 'html', "%s.png"%name)
for f in get_files('g'):
try:
im = Image.open(f)
im.load()
compare = Image.open(get_compare(f))
compare.load()
if im.mode == 'P':
# assert image similar doesn't really work
# with paletized image, since the palette might
# be differently ordered for an equivalent image.
im = im.convert('RGBA')
compare = im.convert('RGBA')
assert_image_similar(im, compare,5)
except Exception as msg:
# there are three here that are unsupported:
unsupported = (os.path.join(base, 'g', 'rgb32bf.bmp'),
os.path.join(base, 'g', 'pal8rle.bmp'),
os.path.join(base, 'g', 'pal4rle.bmp'))
if f not in unsupported:
assert_true(False, "Unsupported Image %s: %s" %(f,msg))

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
# sample ppm stream
file = "Images/lena.fli"
data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "P")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "FLI")

View File

@ -1,66 +0,0 @@
from tester import *
from PIL import Image
# sample icon file
file = "Images/pillow.icns"
data = open(file, "rb").read()
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version')
def test_sanity():
# Loading this icon by default should result in the largest size
# (512x512@2x) being loaded
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGBA")
assert_equal(im.size, (1024, 1024))
assert_equal(im.format, "ICNS")
def test_sizes():
# Check that we can load all of the sizes, and that the final pixel
# dimensions are as expected
im = Image.open(file)
for w,h,r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open(file)
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))
def test_older_icon():
# This icon was made with Icon Composer rather than iconutil; it still
# uses PNG rather than JP2, however (since it was made on 10.9).
im = Image.open('Tests/images/pillow2.icns')
for w,h,r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow2.icns')
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))
def test_jp2_icon():
# This icon was made by using Uli Kusterer's oldiconutil to replace
# the PNG images with JPEG 2000 ones. The advantage of doing this is
# that OS X 10.5 supports JPEG 2000 but not PNG; some commercial
# software therefore does just this.
# (oldiconutil is here: https://github.com/uliwitness/oldiconutil)
if not enable_jpeg2k:
return
im = Image.open('Tests/images/pillow3.icns')
for w,h,r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow3.icns')
im2.size = (w, h, r)
im2.load()
assert_equal(im2.mode, 'RGBA')
assert_equal(im2.size, (wr, hr))

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
# sample ppm stream
file = "Images/lena.ico"
data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGBA")
assert_equal(im.size, (16, 16))
assert_equal(im.format, "ICO")

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
# sample ppm stream
file = "Images/lena.psd"
data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "RGB")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "PSD")

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
# sample ppm stream
file = "Images/lena.xpm"
data = open(file, "rb").read()
def test_sanity():
im = Image.open(file)
im.load()
assert_equal(im.mode, "P")
assert_equal(im.size, (128, 128))
assert_equal(im.format, "XPM")

View File

@ -1,13 +0,0 @@
from tester import *
from PIL import Image, FontFile, BdfFontFile
filename = "Images/courB08.bdf"
def test_sanity():
file = open(filename, "rb")
font = BdfFontFile.BdfFontFile(file)
assert_true(isinstance(font, FontFile.FontFile))
assert_equal(len([_f for _f in font.glyph if _f]), 190)

View File

@ -1,41 +0,0 @@
from tester import *
from PIL import Image
def test_white():
i = Image.open('Tests/images/lab.tif')
bits = i.load()
assert_equal(i.mode, 'LAB')
assert_equal(i.getbands(), ('L','A', 'B'))
k = i.getpixel((0,0))
assert_equal(k, (255,128,128))
L = i.getdata(0)
a = i.getdata(1)
b = i.getdata(2)
assert_equal(list(L), [255]*100)
assert_equal(list(a), [128]*100)
assert_equal(list(b), [128]*100)
def test_green():
# l= 50 (/100), a = -100 (-128 .. 128) b=0 in PS
# == RGB: 0, 152, 117
i = Image.open('Tests/images/lab-green.tif')
k = i.getpixel((0,0))
assert_equal(k, (128,28,128))
def test_red():
# l= 50 (/100), a = 100 (-128 .. 128) b=0 in PS
# == RGB: 255, 0, 124
i = Image.open('Tests/images/lab-red.tif')
k = i.getpixel((0,0))
assert_equal(k, (128,228,128))

View File

@ -1,33 +0,0 @@
from tester import *
from PIL import Image
im = lena().resize((128, 100))
def test_toarray():
def test(mode):
ai = im.convert(mode).__array_interface__
return ai["shape"], ai["typestr"], len(ai["data"])
# assert_equal(test("1"), ((100, 128), '|b1', 1600))
assert_equal(test("L"), ((100, 128), '|u1', 12800))
assert_equal(test("I"), ((100, 128), Image._ENDIAN + 'i4', 51200)) # FIXME: wrong?
assert_equal(test("F"), ((100, 128), Image._ENDIAN + 'f4', 51200)) # FIXME: wrong?
assert_equal(test("RGB"), ((100, 128, 3), '|u1', 38400))
assert_equal(test("RGBA"), ((100, 128, 4), '|u1', 51200))
assert_equal(test("RGBX"), ((100, 128, 4), '|u1', 51200))
def test_fromarray():
def test(mode):
i = im.convert(mode)
a = i.__array_interface__
a["strides"] = 1 # pretend it's non-contigous
i.__array_interface__ = a # patch in new version of attribute
out = Image.fromarray(i)
return out.mode, out.size, list(i.getdata()) == list(out.getdata())
# assert_equal(test("1"), ("1", (128, 100), True))
assert_equal(test("L"), ("L", (128, 100), True))
assert_equal(test("I"), ("I", (128, 100), True))
assert_equal(test("F"), ("F", (128, 100), True))
assert_equal(test("RGB"), ("RGB", (128, 100), True))
assert_equal(test("RGBA"), ("RGBA", (128, 100), True))
assert_equal(test("RGBX"), ("RGBA", (128, 100), True))

View File

@ -1,12 +0,0 @@
from tester import *
from PIL import Image
def test_copy():
def copy(mode):
im = lena(mode)
out = im.copy()
assert_equal(out.mode, mode)
assert_equal(out.size, im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
yield_test(copy, mode)

View File

@ -1,52 +0,0 @@
from tester import *
from PIL import Image
def test_crop():
def crop(mode):
out = lena(mode).crop((50, 50, 100, 100))
assert_equal(out.mode, mode)
assert_equal(out.size, (50, 50))
for mode in "1", "P", "L", "RGB", "I", "F":
yield_test(crop, mode)
def test_wide_crop():
def crop(*bbox):
i = im.crop(bbox)
h = i.histogram()
while h and not h[-1]:
del h[-1]
return tuple(h)
im = Image.new("L", (100, 100), 1)
assert_equal(crop(0, 0, 100, 100), (0, 10000))
assert_equal(crop(25, 25, 75, 75), (0, 2500))
# sides
assert_equal(crop(-25, 0, 25, 50), (1250, 1250))
assert_equal(crop(0, -25, 50, 25), (1250, 1250))
assert_equal(crop(75, 0, 125, 50), (1250, 1250))
assert_equal(crop(0, 75, 50, 125), (1250, 1250))
assert_equal(crop(-25, 25, 125, 75), (2500, 5000))
assert_equal(crop(25, -25, 75, 125), (2500, 5000))
# corners
assert_equal(crop(-25, -25, 25, 25), (1875, 625))
assert_equal(crop(75, -25, 125, 25), (1875, 625))
assert_equal(crop(75, 75, 125, 125), (1875, 625))
assert_equal(crop(-25, 75, 25, 125), (1875, 625))
# --------------------------------------------------------------------
def test_negative_crop():
# Check negative crop size (@PIL171)
im = Image.new("L", (512, 512))
im = im.crop((400, 400, 200, 200))
assert_equal(im.size, (0, 0))
assert_equal(len(im.getdata()), 0)
assert_exception(IndexError, lambda: im.getdata()[0])

View File

@ -1,82 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageFilter
def test_sanity():
def filter(filter):
im = lena("L")
out = im.filter(filter)
assert_equal(out.mode, im.mode)
assert_equal(out.size, im.size)
filter(ImageFilter.BLUR)
filter(ImageFilter.CONTOUR)
filter(ImageFilter.DETAIL)
filter(ImageFilter.EDGE_ENHANCE)
filter(ImageFilter.EDGE_ENHANCE_MORE)
filter(ImageFilter.EMBOSS)
filter(ImageFilter.FIND_EDGES)
filter(ImageFilter.SMOOTH)
filter(ImageFilter.SMOOTH_MORE)
filter(ImageFilter.SHARPEN)
filter(ImageFilter.MaxFilter)
filter(ImageFilter.MedianFilter)
filter(ImageFilter.MinFilter)
filter(ImageFilter.ModeFilter)
filter(ImageFilter.Kernel((3, 3), list(range(9))))
assert_exception(TypeError, lambda: filter("hello"))
def test_crash():
# crashes on small images
im = Image.new("RGB", (1, 1))
assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH))
im = Image.new("RGB", (2, 2))
assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH))
im = Image.new("RGB", (3, 3))
assert_no_exception(lambda: im.filter(ImageFilter.SMOOTH))
def test_modefilter():
def modefilter(mode):
im = Image.new(mode, (3, 3), None)
im.putdata(list(range(9)))
# image is:
# 0 1 2
# 3 4 5
# 6 7 8
mod = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
im.putdata([0, 0, 1, 2, 5, 1, 5, 2, 0]) # mode=0
mod2 = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
return mod, mod2
assert_equal(modefilter("1"), (4, 0))
assert_equal(modefilter("L"), (4, 0))
assert_equal(modefilter("P"), (4, 0))
assert_equal(modefilter("RGB"), ((4, 0, 0), (0, 0, 0)))
def test_rankfilter():
def rankfilter(mode):
im = Image.new(mode, (3, 3), None)
im.putdata(list(range(9)))
# image is:
# 0 1 2
# 3 4 5
# 6 7 8
min = im.filter(ImageFilter.MinFilter).getpixel((1, 1))
med = im.filter(ImageFilter.MedianFilter).getpixel((1, 1))
max = im.filter(ImageFilter.MaxFilter).getpixel((1, 1))
return min, med, max
assert_equal(rankfilter("1"), (0, 4, 8))
assert_equal(rankfilter("L"), (0, 4, 8))
assert_exception(ValueError, lambda: rankfilter("P"))
assert_equal(rankfilter("RGB"), ((0, 0, 0), (4, 0, 0), (8, 0, 0)))
assert_equal(rankfilter("I"), (0, 4, 8))
assert_equal(rankfilter("F"), (0.0, 4.0, 8.0))

View File

@ -1,10 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im1 = lena()
im2 = Image.frombytes(im1.mode, im1.size, im1.tobytes())
assert_image_equal(im1, im2)

View File

@ -1,15 +0,0 @@
from tester import *
from PIL import Image
def test_getbands():
assert_equal(Image.new("1", (1, 1)).getbands(), ("1",))
assert_equal(Image.new("L", (1, 1)).getbands(), ("L",))
assert_equal(Image.new("I", (1, 1)).getbands(), ("I",))
assert_equal(Image.new("F", (1, 1)).getbands(), ("F",))
assert_equal(Image.new("P", (1, 1)).getbands(), ("P",))
assert_equal(Image.new("RGB", (1, 1)).getbands(), ("R", "G", "B"))
assert_equal(Image.new("RGBA", (1, 1)).getbands(), ("R", "G", "B", "A"))
assert_equal(Image.new("CMYK", (1, 1)).getbands(), ("C", "M", "Y", "K"))
assert_equal(Image.new("YCbCr", (1, 1)).getbands(), ("Y", "Cb", "Cr"))

View File

@ -1,36 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
bbox = lena().getbbox()
assert_true(isinstance(bbox, tuple))
def test_bbox():
# 8-bit mode
im = Image.new("L", (100, 100), 0)
assert_equal(im.getbbox(), None)
im.paste(255, (10, 25, 90, 75))
assert_equal(im.getbbox(), (10, 25, 90, 75))
im.paste(255, (25, 10, 75, 90))
assert_equal(im.getbbox(), (10, 10, 90, 90))
im.paste(255, (-10, -10, 110, 110))
assert_equal(im.getbbox(), (0, 0, 100, 100))
# 32-bit mode
im = Image.new("RGB", (100, 100), 0)
assert_equal(im.getbbox(), None)
im.paste(255, (10, 25, 90, 75))
assert_equal(im.getbbox(), (10, 25, 90, 75))
im.paste(255, (25, 10, 75, 90))
assert_equal(im.getbbox(), (10, 10, 90, 90))
im.paste(255, (-10, -10, 110, 110))
assert_equal(im.getbbox(), (0, 0, 100, 100))

View File

@ -1,64 +0,0 @@
from tester import *
from PIL import Image
def test_getcolors():
def getcolors(mode, limit=None):
im = lena(mode)
if limit:
colors = im.getcolors(limit)
else:
colors = im.getcolors()
if colors:
return len(colors)
return None
assert_equal(getcolors("1"), 2)
assert_equal(getcolors("L"), 193)
assert_equal(getcolors("I"), 193)
assert_equal(getcolors("F"), 193)
assert_equal(getcolors("P"), 54) # fixed palette
assert_equal(getcolors("RGB"), None)
assert_equal(getcolors("RGBA"), None)
assert_equal(getcolors("CMYK"), None)
assert_equal(getcolors("YCbCr"), None)
assert_equal(getcolors("L", 128), None)
assert_equal(getcolors("L", 1024), 193)
assert_equal(getcolors("RGB", 8192), None)
assert_equal(getcolors("RGB", 16384), 14836)
assert_equal(getcolors("RGB", 100000), 14836)
assert_equal(getcolors("RGBA", 16384), 14836)
assert_equal(getcolors("CMYK", 16384), 14836)
assert_equal(getcolors("YCbCr", 16384), 11995)
# --------------------------------------------------------------------
def test_pack():
# Pack problems for small tables (@PIL209)
im = lena().quantize(3).convert("RGB")
expected = [(3236, (227, 183, 147)), (6297, (143, 84, 81)), (6851, (208, 143, 112))]
A = im.getcolors(maxcolors=2)
assert_equal(A, None)
A = im.getcolors(maxcolors=3)
A.sort()
assert_equal(A, expected)
A = im.getcolors(maxcolors=4)
A.sort()
assert_equal(A, expected)
A = im.getcolors(maxcolors=8)
A.sort()
assert_equal(A, expected)
A = im.getcolors(maxcolors=16)
A.sort()
assert_equal(A, expected)

View File

@ -1,17 +0,0 @@
from tester import *
from PIL import Image
def test_extrema():
def extrema(mode):
return lena(mode).getextrema()
assert_equal(extrema("1"), (0, 255))
assert_equal(extrema("L"), (40, 235))
assert_equal(extrema("I"), (40, 235))
assert_equal(extrema("F"), (40.0, 235.0))
assert_equal(extrema("P"), (11, 218)) # fixed palette
assert_equal(extrema("RGB"), ((61, 255), (26, 234), (44, 223)))
assert_equal(extrema("RGBA"), ((61, 255), (26, 234), (44, 223), (255, 255)))
assert_equal(extrema("CMYK"), ((0, 194), (21, 229), (32, 211), (0, 0)))

View File

@ -1,14 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im = lena()
type_repr = repr(type(im.getim()))
if py3:
assert_true("PyCapsule" in type_repr)
assert_true(isinstance(im.im.id, int))

View File

@ -1,19 +0,0 @@
from tester import *
from PIL import Image
def test_palette():
def palette(mode):
p = lena(mode).getpalette()
if p:
return p[:10]
return None
assert_equal(palette("1"), None)
assert_equal(palette("L"), None)
assert_equal(palette("I"), None)
assert_equal(palette("F"), None)
assert_equal(palette("P"), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert_equal(palette("RGB"), None)
assert_equal(palette("RGBA"), None)
assert_equal(palette("CMYK"), None)
assert_equal(palette("YCbCr"), None)

View File

@ -1,19 +0,0 @@
from tester import *
from PIL import Image
def test_histogram():
def histogram(mode):
h = lena(mode).histogram()
return len(h), min(h), max(h)
assert_equal(histogram("1"), (256, 0, 8872))
assert_equal(histogram("L"), (256, 0, 199))
assert_equal(histogram("I"), (256, 0, 199))
assert_equal(histogram("F"), (256, 0, 199))
assert_equal(histogram("P"), (256, 0, 2912))
assert_equal(histogram("RGB"), (768, 0, 285))
assert_equal(histogram("RGBA"), (1024, 0, 16384))
assert_equal(histogram("CMYK"), (1024, 0, 16384))
assert_equal(histogram("YCbCr"), (768, 0, 741))

View File

@ -1,27 +0,0 @@
from tester import *
from PIL import Image
import os
def test_sanity():
im = lena()
pix = im.load()
assert_equal(pix[0, 0], (223, 162, 133))
def test_close():
im = Image.open("Images/lena.gif")
assert_no_exception(lambda: im.close())
assert_exception(ValueError, lambda: im.load())
assert_exception(ValueError, lambda: im.getpixel((0,0)))
def test_contextmanager():
fn = None
with Image.open("Images/lena.gif") as im:
fn = im.fp.fileno()
assert_no_exception(lambda: os.fstat(fn))
assert_exception(OSError, lambda: os.fstat(fn))

View File

@ -1,27 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im = lena()
assert_no_exception(lambda: im.mode)
def test_properties():
def check(mode, *result):
signature = (
Image.getmodebase(mode), Image.getmodetype(mode),
Image.getmodebands(mode), Image.getmodebandnames(mode),
)
assert_equal(signature, result)
check("1", "L", "L", 1, ("1",))
check("L", "L", "L", 1, ("L",))
check("P", "RGB", "L", 1, ("P",))
check("I", "L", "I", 1, ("I",))
check("F", "L", "F", 1, ("F",))
check("RGB", "RGB", "L", 3, ("R", "G", "B"))
check("RGBA", "RGB", "L", 4, ("R", "G", "B", "A"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("CMYK", "RGB", "L", 4, ("C", "M", "Y", "K"))
check("YCbCr", "RGB", "L", 3, ("Y", "Cb", "Cr"))

View File

@ -1,16 +0,0 @@
from tester import *
from PIL import Image
def test_offset():
im1 = lena()
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10))
assert_equal(im1.getpixel((0, 0)), im2.getpixel((10, 10)))
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(10, 20))
assert_equal(im1.getpixel((0, 0)), im2.getpixel((10, 20)))
im2 = assert_warning(DeprecationWarning, lambda: im1.offset(20, 20))
assert_equal(im1.getpixel((0, 0)), im2.getpixel((20, 20)))

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,43 +0,0 @@
from tester import *
from PIL import Image
def test_interface():
im = Image.new("RGBA", (1, 1), (1, 2, 3, 0))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 0))
im = Image.new("RGBA", (1, 1), (1, 2, 3))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 255))
im.putalpha(Image.new("L", im.size, 4))
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4))
im.putalpha(5)
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 5))
def test_promote():
im = Image.new("L", (1, 1), 1)
assert_equal(im.getpixel((0, 0)), 1)
im.putalpha(2)
assert_equal(im.mode, 'LA')
assert_equal(im.getpixel((0, 0)), (1, 2))
im = Image.new("RGB", (1, 1), (1, 2, 3))
assert_equal(im.getpixel((0, 0)), (1, 2, 3))
im.putalpha(4)
assert_equal(im.mode, 'RGBA')
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4))
def test_readonly():
im = Image.new("RGB", (1, 1), (1, 2, 3))
im.readonly = 1
im.putalpha(4)
assert_false(im.readonly)
assert_equal(im.mode, 'RGBA')
assert_equal(im.getpixel((0, 0)), (1, 2, 3, 4))

View File

@ -1,40 +0,0 @@
from tester import *
import sys
from PIL import Image
def test_sanity():
im1 = lena()
data = list(im1.getdata())
im2 = Image.new(im1.mode, im1.size, 0)
im2.putdata(data)
assert_image_equal(im1, im2)
# readonly
im2 = Image.new(im1.mode, im2.size, 0)
im2.readonly = 1
im2.putdata(data)
assert_false(im2.readonly)
assert_image_equal(im1, im2)
def test_long_integers():
# see bug-200802-systemerror
def put(value):
im = Image.new("RGBA", (1, 1))
im.putdata([value])
return im.getpixel((0, 0))
assert_equal(put(0xFFFFFFFF), (255, 255, 255, 255))
assert_equal(put(0xFFFFFFFF), (255, 255, 255, 255))
assert_equal(put(-1), (255, 255, 255, 255))
assert_equal(put(-1), (255, 255, 255, 255))
if sys.maxsize > 2**32:
assert_equal(put(sys.maxsize), (255, 255, 255, 255))
else:
assert_equal(put(sys.maxsize), (255, 255, 255, 127))

View File

@ -1,28 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImagePalette
def test_putpalette():
def palette(mode):
im = lena(mode).copy()
im.putpalette(list(range(256))*3)
p = im.getpalette()
if p:
return im.mode, p[:10]
return im.mode
assert_exception(ValueError, lambda: palette("1"))
assert_equal(palette("L"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
assert_equal(palette("P"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
assert_exception(ValueError, lambda: palette("I"))
assert_exception(ValueError, lambda: palette("F"))
assert_exception(ValueError, lambda: palette("RGB"))
assert_exception(ValueError, lambda: palette("RGBA"))
assert_exception(ValueError, lambda: palette("YCbCr"))
def test_imagepalette():
im = lena("P")
assert_no_exception(lambda: im.putpalette(ImagePalette.negative()))
assert_no_exception(lambda: im.putpalette(ImagePalette.random()))
assert_no_exception(lambda: im.putpalette(ImagePalette.sepia()))
assert_no_exception(lambda: im.putpalette(ImagePalette.wedge()))

View File

@ -1,27 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im = lena()
im = im.quantize()
assert_image(im, "P", im.size)
im = lena()
im = im.quantize(palette=lena("P"))
assert_image(im, "P", im.size)
def test_octree_quantize():
im = lena()
im = im.quantize(100, Image.FASTOCTREE)
assert_image(im, "P", im.size)
assert len(im.getcolors()) == 100
def test_rgba_quantize():
im = lena('RGBA')
assert_no_exception(lambda: im.quantize())
assert_exception(Exception, lambda: im.quantize(method=0))

View File

@ -1,12 +0,0 @@
from tester import *
from PIL import Image
def test_resize():
def resize(mode, size):
out = lena(mode).resize(size)
assert_equal(out.mode, mode)
assert_equal(out.size, size)
for mode in "1", "P", "L", "RGB", "I", "F":
yield_test(resize, mode, (100, 100))
yield_test(resize, mode, (200, 200))

View File

@ -1,15 +0,0 @@
from tester import *
from PIL import Image
def test_rotate():
def rotate(mode):
im = lena(mode)
out = im.rotate(45)
assert_equal(out.mode, mode)
assert_equal(out.size, im.size) # default rotate clips output
out = im.rotate(45, expand=1)
assert_equal(out.mode, mode)
assert_true(out.size != im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
yield_test(rotate, mode)

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,36 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
im = lena()
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100))
def test_aspect():
im = lena()
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100))
im = lena().resize((128, 256))
im.thumbnail((100, 100))
assert_image(im, im.mode, (50, 100))
im = lena().resize((128, 256))
im.thumbnail((50, 100))
assert_image(im, im.mode, (50, 100))
im = lena().resize((256, 128))
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 50))
im = lena().resize((256, 128))
im.thumbnail((100, 50))
assert_image(im, im.mode, (100, 50))
im = lena().resize((128, 128))
im.thumbnail((100, 100))
assert_image(im, im.mode, (100, 100))

View File

@ -1,15 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
assert_exception(ValueError, lambda: lena().tobitmap())
assert_no_exception(lambda: lena().convert("1").tobitmap())
im1 = lena().convert("1")
bitmap = im1.tobitmap()
assert_true(isinstance(bitmap, bytes))
assert_image_equal(im1, fromstring(bitmap))

View File

@ -1,7 +0,0 @@
from tester import *
from PIL import Image
def test_sanity():
data = lena().tobytes()
assert_true(isinstance(data, bytes))

View File

@ -1,116 +0,0 @@
from tester import *
from PIL import Image
def test_extent():
im = lena('RGB')
(w,h) = im.size
transformed = im.transform(im.size, Image.EXTENT,
(0,0,
w//2,h//2), # ul -> lr
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0,0,w,h))
assert_image_similar(transformed, scaled, 10) # undone -- precision?
def test_quad():
# one simple quad transform, equivalent to scale & crop upper left quad
im = lena('RGB')
(w,h) = im.size
transformed = im.transform(im.size, Image.QUAD,
(0,0,0,h//2,
w//2,h//2,w//2,0), # ul -> ccw around quad
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0,0,w,h))
assert_image_equal(transformed, scaled)
def test_mesh():
# this should be a checkerboard of halfsized lenas in ul, lr
im = lena('RGBA')
(w,h) = im.size
transformed = im.transform(im.size, Image.MESH,
[((0,0,w//2,h//2), # box
(0,0,0,h,
w,h,w,0)), # ul -> ccw around quad
((w//2,h//2,w,h), # box
(0,0,0,h,
w,h,w,0))], # ul -> ccw around quad
Image.BILINEAR)
#transformed.save('transformed.png')
scaled = im.resize((w//2, h//2), Image.BILINEAR)
checker = Image.new('RGBA', im.size)
checker.paste(scaled, (0,0))
checker.paste(scaled, (w//2,h//2))
assert_image_equal(transformed, checker)
# now, check to see that the extra area is (0,0,0,0)
blank = Image.new('RGBA', (w//2,h//2), (0,0,0,0))
assert_image_equal(blank, transformed.crop((w//2,0,w,h//2)))
assert_image_equal(blank, transformed.crop((0,h//2,w//2,h)))
def _test_alpha_premult(op):
# create image with half white, half black, with the black half transparent.
# do op,
# there should be no darkness in the white section.
im = Image.new('RGBA', (10,10), (0,0,0,0));
im2 = Image.new('RGBA', (5,10), (255,255,255,255));
im.paste(im2, (0,0))
im = op(im, (40,10))
im_background = Image.new('RGB', (40,10), (255,255,255))
im_background.paste(im, (0,0), im)
hist = im_background.histogram()
assert_equal(40*10, hist[-1])
def test_alpha_premult_resize():
def op (im, sz):
return im.resize(sz, Image.LINEAR)
_test_alpha_premult(op)
def test_alpha_premult_transform():
def op(im, sz):
(w,h) = im.size
return im.transform(sz, Image.EXTENT,
(0,0,
w,h),
Image.BILINEAR)
_test_alpha_premult(op)
def test_blank_fill():
# attempting to hit
# https://github.com/python-pillow/Pillow/issues/254 reported
#
# issue is that transforms with transparent overflow area
# contained junk from previous images, especially on systems with
# constrained memory. So, attempt to fill up memory with a
# pattern, free it, and then run the mesh test again. Using a 1Mp
# image with 4 bands, for 4 megs of data allocated, x 64. OMM (64
# bit 12.04 VM with 512 megs available, this fails with Pillow <
# a0eaf06cc5f62a6fb6de556989ac1014ff3348ea
#
# Running by default, but I'd totally understand not doing it in
# the future
foo = [Image.new('RGBA',(1024,1024), (a,a,a,a))
for a in range(1,65)]
# Yeah. Watch some JIT optimize this out.
foo = None
test_mesh()

View File

@ -1,5 +0,0 @@
from tester import *
from PIL import Image
success()

View File

@ -1,56 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageChops
def test_sanity():
im = lena("L")
ImageChops.constant(im, 128)
ImageChops.duplicate(im)
ImageChops.invert(im)
ImageChops.lighter(im, im)
ImageChops.darker(im, im)
ImageChops.difference(im, im)
ImageChops.multiply(im, im)
ImageChops.screen(im, im)
ImageChops.add(im, im)
ImageChops.add(im, im, 2.0)
ImageChops.add(im, im, 2.0, 128)
ImageChops.subtract(im, im)
ImageChops.subtract(im, im, 2.0)
ImageChops.subtract(im, im, 2.0, 128)
ImageChops.add_modulo(im, im)
ImageChops.subtract_modulo(im, im)
ImageChops.blend(im, im, 0.5)
ImageChops.composite(im, im, im)
ImageChops.offset(im, 10)
ImageChops.offset(im, 10, 20)
def test_logical():
def table(op, a, b):
out = []
for x in (a, b):
imx = Image.new("1", (1, 1), x)
for y in (a, b):
imy = Image.new("1", (1, 1), y)
out.append(op(imx, imy).getpixel((0, 0)))
return tuple(out)
assert_equal(table(ImageChops.logical_and, 0, 1), (0, 0, 0, 255))
assert_equal(table(ImageChops.logical_or, 0, 1), (0, 255, 255, 255))
assert_equal(table(ImageChops.logical_xor, 0, 1), (0, 255, 255, 0))
assert_equal(table(ImageChops.logical_and, 0, 128), (0, 0, 0, 255))
assert_equal(table(ImageChops.logical_or, 0, 128), (0, 255, 255, 255))
assert_equal(table(ImageChops.logical_xor, 0, 128), (0, 255, 255, 0))
assert_equal(table(ImageChops.logical_and, 0, 255), (0, 0, 0, 255))
assert_equal(table(ImageChops.logical_or, 0, 255), (0, 255, 255, 255))
assert_equal(table(ImageChops.logical_xor, 0, 255), (0, 255, 255, 0))

View File

@ -1,203 +0,0 @@
from tester import *
from PIL import Image
try:
from PIL import ImageCms
ImageCms.core.profile_open
except ImportError:
skip()
SRGB = "Tests/icc/sRGB.icm"
def test_sanity():
# basic smoke test.
# this mostly follows the cms_test outline.
v = ImageCms.versions() # should return four strings
assert_equal(v[0], '1.0.0 pil')
assert_equal(list(map(type, v)), [str, str, str, str])
# internal version number
assert_match(ImageCms.core.littlecms_version, "\d+\.\d+$")
i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
assert_image(i, "RGB", (128, 128))
i = lena()
ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
assert_image(i, "RGB", (128, 128))
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "RGB", (128, 128))
i = lena()
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
ImageCms.applyTransform(lena(), t, inPlace=True)
assert_image(i, "RGB", (128, 128))
p = ImageCms.createProfile("sRGB")
o = ImageCms.getOpenProfile(SRGB)
t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "RGB", (128, 128))
t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
assert_equal(t.inputMode, "RGB")
assert_equal(t.outputMode, "RGB")
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "RGB", (128, 128))
# test PointTransform convenience API
lena().point(t)
def test_name():
# get profile information for file
assert_equal(ImageCms.getProfileName(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_info():
assert_equal(ImageCms.getProfileInfo(SRGB).splitlines(),
['sRGB IEC61966-2.1', '',
'Copyright (c) 1998 Hewlett-Packard Company', ''])
def test_copyright():
assert_equal(ImageCms.getProfileCopyright(SRGB).strip(),
'Copyright (c) 1998 Hewlett-Packard Company')
def test_manufacturer():
assert_equal(ImageCms.getProfileManufacturer(SRGB).strip(),
'IEC http://www.iec.ch')
def test_model():
assert_equal(ImageCms.getProfileModel(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_description():
assert_equal(ImageCms.getProfileDescription(SRGB).strip(),
'sRGB IEC61966-2.1')
def test_intent():
assert_equal(ImageCms.getDefaultIntent(SRGB), 0)
assert_equal(ImageCms.isIntentSupported(
SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_profile_object():
# same, using profile object
p = ImageCms.createProfile("sRGB")
# assert_equal(ImageCms.getProfileName(p).strip(),
# 'sRGB built-in - (lcms internal)')
# assert_equal(ImageCms.getProfileInfo(p).splitlines(),
# ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
assert_equal(ImageCms.getDefaultIntent(p), 0)
assert_equal(ImageCms.isIntentSupported(
p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_extensions():
# extensions
i = Image.open("Tests/images/rgb.jpg")
p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
assert_equal(ImageCms.getProfileName(p).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_exceptions():
# the procedural pyCMS API uses PyCMSError for all sorts of errors
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.getProfileName(None))
assert_exception(
ImageCms.PyCMSError,
lambda: ImageCms.isIntentSupported(SRGB, None, None))
def test_display_profile():
# try fetching the profile for the current display device
assert_no_exception(lambda: ImageCms.get_display_profile())
def test_lab_color_profile():
ImageCms.createProfile("LAB", 5000)
ImageCms.createProfile("LAB", 6500)
def test_simple_lab():
i = Image.new('RGB', (10, 10), (128, 128, 128))
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
i_lab = ImageCms.applyTransform(i, t)
assert_equal(i_lab.mode, 'LAB')
k = i_lab.getpixel((0, 0))
assert_equal(k, (137, 128, 128)) # not a linear luminance map. so L != 128
L = i_lab.getdata(0)
a = i_lab.getdata(1)
b = i_lab.getdata(2)
assert_equal(list(L), [137] * 100)
assert_equal(list(a), [128] * 100)
assert_equal(list(b), [128] * 100)
def test_lab_color():
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
# Need to add a type mapping for some PIL type to TYPE_Lab_8 in
# findLCMSType, and have that mapping work back to a PIL mode (likely RGB).
i = ImageCms.applyTransform(lena(), t)
assert_image(i, "LAB", (128, 128))
# i.save('temp.lab.tif') # visually verified vs PS.
target = Image.open('Tests/images/lena.Lab.tif')
assert_image_similar(i, target, 30)
def test_lab_srgb():
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
img = Image.open('Tests/images/lena.Lab.tif')
img_srgb = ImageCms.applyTransform(img, t)
# img_srgb.save('temp.srgb.tif') # visually verified vs ps.
assert_image_similar(lena(), img_srgb, 30)
def test_lab_roundtrip():
# 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(lena(), t)
out = ImageCms.applyTransform(i, t2)
assert_image_similar(lena(), out, 2)

View File

@ -1,54 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageColor
# --------------------------------------------------------------------
# sanity
assert_equal((255, 0, 0), ImageColor.getrgb("#f00"))
assert_equal((255, 0, 0), ImageColor.getrgb("#ff0000"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(255,0,0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(255, 0, 0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("rgb(100%,0%,0%)"))
assert_equal((255, 0, 0), ImageColor.getrgb("hsl(0, 100%, 50%)"))
assert_equal((255, 0, 0, 0), ImageColor.getrgb("rgba(255,0,0,0)"))
assert_equal((255, 0, 0, 0), ImageColor.getrgb("rgba(255, 0, 0, 0)"))
assert_equal((255, 0, 0), ImageColor.getrgb("red"))
# --------------------------------------------------------------------
# look for rounding errors (based on code by Tim Hatch)
for color in list(ImageColor.colormap.keys()):
expected = Image.new("RGB", (1, 1), color).convert("L").getpixel((0, 0))
actual = Image.new("L", (1, 1), color).getpixel((0, 0))
assert_equal(expected, actual)
assert_equal((0, 0, 0), ImageColor.getcolor("black", "RGB"))
assert_equal((255, 255, 255), ImageColor.getcolor("white", "RGB"))
assert_equal((0, 255, 115), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGB"))
Image.new("RGB", (1, 1), "white")
assert_equal((0, 0, 0, 255), ImageColor.getcolor("black", "RGBA"))
assert_equal((255, 255, 255, 255), ImageColor.getcolor("white", "RGBA"))
assert_equal((0, 255, 115, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "RGBA"))
Image.new("RGBA", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "L"))
assert_equal(255, ImageColor.getcolor("white", "L"))
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "L"))
Image.new("L", (1, 1), "white")
assert_equal(0, ImageColor.getcolor("black", "1"))
assert_equal(255, ImageColor.getcolor("white", "1"))
# The following test is wrong, but is current behavior
# The correct result should be 255 due to the mode 1
assert_equal(162, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
# Correct behavior
# assert_equal(255, ImageColor.getcolor("rgba(0, 255, 115, 33)", "1"))
Image.new("1", (1, 1), "white")
assert_equal((0, 255), ImageColor.getcolor("black", "LA"))
assert_equal((255, 255), ImageColor.getcolor("white", "LA"))
assert_equal((162, 33), ImageColor.getcolor("rgba(0, 255, 115, 33)", "LA"))
Image.new("LA", (1, 1), "white")

View File

@ -1,270 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageColor
from PIL import ImageDraw
# Image size
w, h = 100, 100
# Bounding box points
x0 = int(w / 4)
x1 = int(x0 * 3)
y0 = int(h / 4)
y1 = int(x0 * 3)
# Two kinds of bounding box
bbox1 = [(x0, y0), (x1, y1)]
bbox2 = [x0, y0, x1, y1]
# Two kinds of coordinate sequences
points1 = [(10, 10), (20, 40), (30, 30)]
points2 = [10, 10, 20, 40, 30, 30]
def test_sanity():
im = lena("RGB").copy()
draw = ImageDraw.ImageDraw(im)
draw = ImageDraw.Draw(im)
draw.ellipse(list(range(4)))
draw.line(list(range(10)))
draw.polygon(list(range(100)))
draw.rectangle(list(range(4)))
success()
def test_deprecated():
im = lena().copy()
draw = ImageDraw.Draw(im)
assert_warning(DeprecationWarning, lambda: draw.setink(0))
assert_warning(DeprecationWarning, lambda: draw.setfill(0))
def helper_arc(bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
# FIXME Fill param should be named outline.
draw.arc(bbox, 0, 180)
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_arc.png"))
def test_arc1():
helper_arc(bbox1)
def test_arc2():
helper_arc(bbox2)
def test_bitmap():
# Arrange
small = Image.open("Tests/images/pil123rgba.png").resize((50, 50))
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.bitmap((10, 10), small)
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_bitmap.png"))
def helper_chord(bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.chord(bbox, 0, 180, fill="red", outline="yellow")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_chord.png"))
def test_chord1():
helper_chord(bbox1)
def test_chord2():
helper_chord(bbox2)
def helper_ellipse(bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.ellipse(bbox, fill="green", outline="blue")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_ellipse.png"))
def test_ellipse1():
helper_ellipse(bbox1)
def test_ellipse2():
helper_ellipse(bbox2)
def helper_line(points):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.line(points1, fill="yellow", width=2)
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_line.png"))
def test_line1():
helper_line(points1)
def test_line2():
helper_line(points2)
def helper_pieslice(bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.pieslice(bbox, -90, 45, fill="white", outline="blue")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_pieslice.png"))
def test_pieslice1():
helper_pieslice(bbox1)
def test_pieslice2():
helper_pieslice(bbox2)
def helper_point(points):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.point(points1, fill="yellow")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_point.png"))
def test_point1():
helper_point(points1)
def test_point2():
helper_point(points2)
def helper_polygon(points):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.polygon(points1, fill="red", outline="blue")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_polygon.png"))
def test_polygon1():
helper_polygon(points1)
def test_polygon2():
helper_polygon(points2)
def helper_rectangle(bbox):
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
# Act
draw.rectangle(bbox, fill="black", outline="green")
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_rectangle.png"))
def test_rectangle1():
helper_rectangle(bbox1)
def test_rectangle2():
helper_rectangle(bbox2)
def test_floodfill():
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
draw.rectangle(bbox2, outline="yellow", fill="green")
centre_point = (int(w/2), int(h/2))
# Act
ImageDraw.floodfill(im, centre_point, ImageColor.getrgb("red"))
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill.png"))
def test_floodfill_border():
# floodfill() is experimental
if hasattr(sys, 'pypy_version_info'):
# Causes fatal RPython error on PyPy
skip()
# Arrange
im = Image.new("RGB", (w, h))
draw = ImageDraw.Draw(im)
draw.rectangle(bbox2, outline="yellow", fill="green")
centre_point = (int(w/2), int(h/2))
# Act
ImageDraw.floodfill(
im, centre_point, ImageColor.getrgb("red"),
border=ImageColor.getrgb("black"))
del draw
# Assert
assert_image_equal(im, Image.open("Tests/images/imagedraw_floodfill2.png"))
# End of file

View File

@ -1,19 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageEnhance
def test_sanity():
# FIXME: assert_image
assert_no_exception(lambda: ImageEnhance.Color(lena()).enhance(0.5))
assert_no_exception(lambda: ImageEnhance.Contrast(lena()).enhance(0.5))
assert_no_exception(lambda: ImageEnhance.Brightness(lena()).enhance(0.5))
assert_no_exception(lambda: ImageEnhance.Sharpness(lena()).enhance(0.5))
def test_crash():
# crashes on small images
im = Image.new("RGB", (1, 1))
assert_no_exception(lambda: ImageEnhance.Sharpness(im).enhance(0.5))

View File

@ -1,24 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageFileIO
def test_fileio():
class DumbFile:
def __init__(self, data):
self.data = data
def read(self, bytes=None):
assert_equal(bytes, None)
return self.data
def close(self):
pass
im1 = lena()
io = ImageFileIO.ImageFileIO(DumbFile(tostring(im1, "PPM")))
im2 = Image.open(io)
assert_image_equal(im1, im2)

View File

@ -1,31 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageFilter
def test_sanity():
# see test_image_filter for more tests
assert_no_exception(lambda: ImageFilter.MaxFilter)
assert_no_exception(lambda: ImageFilter.MedianFilter)
assert_no_exception(lambda: ImageFilter.MinFilter)
assert_no_exception(lambda: ImageFilter.ModeFilter)
assert_no_exception(lambda: ImageFilter.Kernel((3, 3), list(range(9))))
assert_no_exception(lambda: ImageFilter.GaussianBlur)
assert_no_exception(lambda: ImageFilter.GaussianBlur(5))
assert_no_exception(lambda: ImageFilter.UnsharpMask)
assert_no_exception(lambda: ImageFilter.UnsharpMask(10))
assert_no_exception(lambda: ImageFilter.BLUR)
assert_no_exception(lambda: ImageFilter.CONTOUR)
assert_no_exception(lambda: ImageFilter.DETAIL)
assert_no_exception(lambda: ImageFilter.EDGE_ENHANCE)
assert_no_exception(lambda: ImageFilter.EDGE_ENHANCE_MORE)
assert_no_exception(lambda: ImageFilter.EMBOSS)
assert_no_exception(lambda: ImageFilter.FIND_EDGES)
assert_no_exception(lambda: ImageFilter.SMOOTH)
assert_no_exception(lambda: ImageFilter.SMOOTH_MORE)
assert_no_exception(lambda: ImageFilter.SHARPEN)

View File

@ -1,135 +0,0 @@
from tester import *
from PIL import Image
from io import BytesIO
import os
try:
from PIL import ImageFont
ImageFont.core.getfont # check if freetype is available
except ImportError:
skip()
from PIL import ImageDraw
font_path = "Tests/fonts/FreeMono.ttf"
font_size=20
def test_sanity():
assert_match(ImageFont.core.freetype2_version, "\d+\.\d+\.\d+$")
def test_font_with_name():
assert_no_exception(lambda: ImageFont.truetype(font_path, font_size))
assert_no_exception(lambda: _render(font_path))
_clean()
def _font_as_bytes():
with open(font_path, 'rb') as f:
font_bytes = BytesIO(f.read())
return font_bytes
def test_font_with_filelike():
assert_no_exception(lambda: ImageFont.truetype(_font_as_bytes(), font_size))
assert_no_exception(lambda: _render(_font_as_bytes()))
# Usage note: making two fonts from the same buffer fails.
#shared_bytes = _font_as_bytes()
#assert_no_exception(lambda: _render(shared_bytes))
#assert_exception(Exception, lambda: _render(shared_bytes))
_clean()
def test_font_with_open_file():
with open(font_path, 'rb') as f:
assert_no_exception(lambda: _render(f))
_clean()
def test_font_old_parameters():
assert_warning(DeprecationWarning, lambda: ImageFont.truetype(filename=font_path, size=font_size))
def _render(font):
txt = "Hello World!"
ttf = ImageFont.truetype(font, font_size)
w, h = ttf.getsize(txt)
img = Image.new("RGB", (256, 64), "white")
d = ImageDraw.Draw(img)
d.text((10, 10), txt, font=ttf, fill='black')
img.save('font.png')
return img
def _clean():
os.unlink('font.png')
def test_render_equal():
img_path = _render(font_path)
with open(font_path, 'rb') as f:
font_filelike = BytesIO(f.read())
img_filelike = _render(font_filelike)
assert_image_equal(img_path, img_filelike)
_clean()
def test_render_multiline():
im = Image.new(mode='RGB', size=(300,100))
draw = ImageDraw.Draw(im)
ttf = ImageFont.truetype(font_path, font_size)
line_spacing = draw.textsize('A', font=ttf)[1] + 8
lines = ['hey you', 'you are awesome', 'this looks awkward']
y = 0
for line in lines:
draw.text((0, y), line, font=ttf)
y += line_spacing
target = 'Tests/images/multiline_text.png'
target_img = Image.open(target)
# some versions of freetype have different horizontal spacing.
# setting a tight epsilon, I'm showing the original test failure
# at epsilon = ~38.
assert_image_similar(im, target_img,.5)
def test_rotated_transposed_font():
img_grey = Image.new("L", (100, 100))
draw = ImageDraw.Draw(img_grey)
word = "testing"
font = ImageFont.truetype(font_path, font_size)
orientation = Image.ROTATE_90
transposed_font = ImageFont.TransposedFont(font, orientation=orientation)
# Original font
draw.setfont(font)
box_size_a = draw.textsize(word)
# Rotated font
draw.setfont(transposed_font)
box_size_b = draw.textsize(word)
# Check (w,h) of box a is (h,w) of box b
assert_equal(box_size_a[0], box_size_b[1])
assert_equal(box_size_a[1], box_size_b[0])
def test_unrotated_transposed_font():
img_grey = Image.new("L", (100, 100))
draw = ImageDraw.Draw(img_grey)
word = "testing"
font = ImageFont.truetype(font_path, font_size)
orientation = None
transposed_font = ImageFont.TransposedFont(font, orientation=orientation)
# Original font
draw.setfont(font)
box_size_a = draw.textsize(word)
# Rotated font
draw.setfont(transposed_font)
box_size_b = draw.textsize(word)
# Check boxes a and b are same size
assert_equal(box_size_a, box_size_b)

View File

@ -1,13 +0,0 @@
from tester import *
from PIL import Image
try:
from PIL import ImageGrab
except ImportError as v:
skip(v)
def test_grab():
im = ImageGrab.grab()
assert_image(im, im.mode, im.size)

View File

@ -1,62 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageMath
def pixel(im):
if hasattr(im, "im"):
return "%s %r" % (im.mode, im.getpixel((0, 0)))
else:
if isinstance(im, type(0)):
return int(im) # hack to deal with booleans
print(im)
A = Image.new("L", (1, 1), 1)
B = Image.new("L", (1, 1), 2)
F = Image.new("F", (1, 1), 3)
I = Image.new("I", (1, 1), 4)
images = {"A": A, "B": B, "F": F, "I": I}
def test_sanity():
assert_equal(ImageMath.eval("1"), 1)
assert_equal(ImageMath.eval("1+A", A=2), 3)
assert_equal(pixel(ImageMath.eval("A+B", A=A, B=B)), "I 3")
assert_equal(pixel(ImageMath.eval("A+B", images)), "I 3")
assert_equal(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0")
assert_equal(pixel(ImageMath.eval("int(float(A)+B)", images)), "I 3")
def test_ops():
assert_equal(pixel(ImageMath.eval("-A", images)), "I -1")
assert_equal(pixel(ImageMath.eval("+B", images)), "L 2")
assert_equal(pixel(ImageMath.eval("A+B", images)), "I 3")
assert_equal(pixel(ImageMath.eval("A-B", images)), "I -1")
assert_equal(pixel(ImageMath.eval("A*B", images)), "I 2")
assert_equal(pixel(ImageMath.eval("A/B", images)), "I 0")
assert_equal(pixel(ImageMath.eval("B**2", images)), "I 4")
assert_equal(pixel(ImageMath.eval("B**33", images)), "I 2147483647")
assert_equal(pixel(ImageMath.eval("float(A)+B", images)), "F 3.0")
assert_equal(pixel(ImageMath.eval("float(A)-B", images)), "F -1.0")
assert_equal(pixel(ImageMath.eval("float(A)*B", images)), "F 2.0")
assert_equal(pixel(ImageMath.eval("float(A)/B", images)), "F 0.5")
assert_equal(pixel(ImageMath.eval("float(B)**2", images)), "F 4.0")
assert_equal(pixel(ImageMath.eval("float(B)**33", images)), "F 8589934592.0")
def test_logical():
assert_equal(pixel(ImageMath.eval("not A", images)), 0)
assert_equal(pixel(ImageMath.eval("A and B", images)), "L 2")
assert_equal(pixel(ImageMath.eval("A or B", images)), "L 1")
def test_convert():
assert_equal(pixel(ImageMath.eval("convert(A+B, 'L')", images)), "L 3")
assert_equal(pixel(ImageMath.eval("convert(A+B, '1')", images)), "1 0")
assert_equal(pixel(ImageMath.eval("convert(A+B, 'RGB')", images)), "RGB (3, 3, 3)")
def test_compare():
assert_equal(pixel(ImageMath.eval("min(A, B)", images)), "I 1")
assert_equal(pixel(ImageMath.eval("max(A, B)", images)), "I 2")
assert_equal(pixel(ImageMath.eval("A == 1", images)), "I 1")
assert_equal(pixel(ImageMath.eval("A == 2", images)), "I 0")

View File

@ -1,23 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageMode
ImageMode.getmode("1")
ImageMode.getmode("L")
ImageMode.getmode("P")
ImageMode.getmode("RGB")
ImageMode.getmode("I")
ImageMode.getmode("F")
m = ImageMode.getmode("1")
assert_equal(m.mode, "1")
assert_equal(m.bands, ("1",))
assert_equal(m.basemode, "L")
assert_equal(m.basetype, "L")
m = ImageMode.getmode("RGB")
assert_equal(m.mode, "RGB")
assert_equal(m.bands, ("R", "G", "B"))
assert_equal(m.basemode, "RGB")
assert_equal(m.basetype, "L")

View File

@ -1,81 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageOps
class Deformer:
def getmesh(self, im):
x, y = im.size
return [((0, 0, x, y), (0, 0, x, 0, x, y, y, 0))]
deformer = Deformer()
def test_sanity():
ImageOps.autocontrast(lena("L"))
ImageOps.autocontrast(lena("RGB"))
ImageOps.autocontrast(lena("L"), cutoff=10)
ImageOps.autocontrast(lena("L"), ignore=[0, 255])
ImageOps.colorize(lena("L"), (0, 0, 0), (255, 255, 255))
ImageOps.colorize(lena("L"), "black", "white")
ImageOps.crop(lena("L"), 1)
ImageOps.crop(lena("RGB"), 1)
ImageOps.deform(lena("L"), deformer)
ImageOps.deform(lena("RGB"), deformer)
ImageOps.equalize(lena("L"))
ImageOps.equalize(lena("RGB"))
ImageOps.expand(lena("L"), 1)
ImageOps.expand(lena("RGB"), 1)
ImageOps.expand(lena("L"), 2, "blue")
ImageOps.expand(lena("RGB"), 2, "blue")
ImageOps.fit(lena("L"), (128, 128))
ImageOps.fit(lena("RGB"), (128, 128))
ImageOps.flip(lena("L"))
ImageOps.flip(lena("RGB"))
ImageOps.grayscale(lena("L"))
ImageOps.grayscale(lena("RGB"))
ImageOps.invert(lena("L"))
ImageOps.invert(lena("RGB"))
ImageOps.mirror(lena("L"))
ImageOps.mirror(lena("RGB"))
ImageOps.posterize(lena("L"), 4)
ImageOps.posterize(lena("RGB"), 4)
ImageOps.solarize(lena("L"))
ImageOps.solarize(lena("RGB"))
success()
def test_1pxfit():
# Division by zero in equalize if image is 1 pixel high
newimg = ImageOps.fit(lena("RGB").resize((1,1)), (35,35))
assert_equal(newimg.size,(35,35))
newimg = ImageOps.fit(lena("RGB").resize((1,100)), (35,35))
assert_equal(newimg.size,(35,35))
newimg = ImageOps.fit(lena("RGB").resize((100,1)), (35,35))
assert_equal(newimg.size,(35,35))
def test_pil163():
# Division by zero in equalize if < 255 pixels in image (@PIL163)
i = lena("RGB").resize((15, 16))
ImageOps.equalize(i.convert("L"))
ImageOps.equalize(i.convert("P"))
ImageOps.equalize(i.convert("RGB"))
success()

View File

@ -1,6 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageShow
success()

View File

@ -1,52 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageStat
def test_sanity():
im = lena()
st = ImageStat.Stat(im)
st = ImageStat.Stat(im.histogram())
st = ImageStat.Stat(im, Image.new("1", im.size, 1))
assert_no_exception(lambda: st.extrema)
assert_no_exception(lambda: st.sum)
assert_no_exception(lambda: st.mean)
assert_no_exception(lambda: st.median)
assert_no_exception(lambda: st.rms)
assert_no_exception(lambda: st.sum2)
assert_no_exception(lambda: st.var)
assert_no_exception(lambda: st.stddev)
assert_exception(AttributeError, lambda: st.spam)
assert_exception(TypeError, lambda: ImageStat.Stat(1))
def test_lena():
im = lena()
st = ImageStat.Stat(im)
# verify a few values
assert_equal(st.extrema[0], (61, 255))
assert_equal(st.median[0], 197)
assert_equal(st.sum[0], 2954416)
assert_equal(st.sum[1], 2027250)
assert_equal(st.sum[2], 1727331)
def test_constant():
im = Image.new("L", (128, 128), 128)
st = ImageStat.Stat(im)
assert_equal(st.extrema[0], (128, 128))
assert_equal(st.sum[0], 128**3)
assert_equal(st.sum2[0], 128**4)
assert_equal(st.mean[0], 128)
assert_equal(st.median[0], 128)
assert_equal(st.rms[0], 128)
assert_equal(st.var[0], 0)
assert_equal(st.stddev[0], 0)

View File

@ -1,9 +0,0 @@
from tester import *
from PIL import Image
try:
from PIL import ImageTk
except (OSError, ImportError) as v:
skip(v)
success()

View File

@ -1,18 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageTransform
im = Image.new("L", (100, 100))
seq = tuple(range(10))
def test_sanity():
transform = ImageTransform.AffineTransform(seq[:6])
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.ExtentTransform(seq[:4])
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.QuadTransform(seq[:8])
assert_no_exception(lambda: im.transform((100, 100), transform))
transform = ImageTransform.MeshTransform([(seq[:4], seq[:8])])
assert_no_exception(lambda: im.transform((100, 100), transform))

View File

@ -1,6 +0,0 @@
from tester import *
from PIL import Image
from PIL import ImageWin
success()

View File

@ -1,30 +0,0 @@
from tester import *
from PIL import Image
def test_setmode():
im = Image.new("L", (1, 1), 255)
im.im.setmode("1")
assert_equal(im.im.getpixel((0, 0)), 255)
im.im.setmode("L")
assert_equal(im.im.getpixel((0, 0)), 255)
im = Image.new("1", (1, 1), 1)
im.im.setmode("L")
assert_equal(im.im.getpixel((0, 0)), 255)
im.im.setmode("1")
assert_equal(im.im.getpixel((0, 0)), 255)
im = Image.new("RGB", (1, 1), (1, 2, 3))
im.im.setmode("RGB")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3))
im.im.setmode("RGBA")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3, 255))
im.im.setmode("RGBX")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3, 255))
im.im.setmode("RGB")
assert_equal(im.im.getpixel((0, 0)), (1, 2, 3))
assert_exception(ValueError, lambda: im.im.setmode("L"))
assert_exception(ValueError, lambda: im.im.setmode("RGBABCDE"))

View File

@ -1,138 +0,0 @@
from tester import *
from PIL import Image
def pack():
pass # not yet
def test_pack():
def pack(mode, rawmode):
if len(mode) == 1:
im = Image.new(mode, (1, 1), 1)
else:
im = Image.new(mode, (1, 1), (1, 2, 3, 4)[:len(mode)])
if py3:
return list(im.tobytes("raw", rawmode))
else:
return [ord(c) for c in im.tobytes("raw", rawmode)]
order = 1 if Image._ENDIAN == '<' else -1
assert_equal(pack("1", "1"), [128])
assert_equal(pack("1", "1;I"), [0])
assert_equal(pack("1", "1;R"), [1])
assert_equal(pack("1", "1;IR"), [0])
assert_equal(pack("L", "L"), [1])
assert_equal(pack("I", "I"), [1, 0, 0, 0][::order])
assert_equal(pack("F", "F"), [0, 0, 128, 63][::order])
assert_equal(pack("LA", "LA"), [1, 2])
assert_equal(pack("RGB", "RGB"), [1, 2, 3])
assert_equal(pack("RGB", "RGB;L"), [1, 2, 3])
assert_equal(pack("RGB", "BGR"), [3, 2, 1])
assert_equal(pack("RGB", "RGBX"), [1, 2, 3, 255]) # 255?
assert_equal(pack("RGB", "BGRX"), [3, 2, 1, 0])
assert_equal(pack("RGB", "XRGB"), [0, 1, 2, 3])
assert_equal(pack("RGB", "XBGR"), [0, 3, 2, 1])
assert_equal(pack("RGBX", "RGBX"), [1, 2, 3, 4]) # 4->255?
assert_equal(pack("RGBA", "RGBA"), [1, 2, 3, 4])
assert_equal(pack("CMYK", "CMYK"), [1, 2, 3, 4])
assert_equal(pack("YCbCr", "YCbCr"), [1, 2, 3])
def test_unpack():
def unpack(mode, rawmode, bytes_):
im = None
if py3:
data = bytes(range(1,bytes_+1))
else:
data = ''.join(chr(i) for i in range(1,bytes_+1))
im = Image.frombytes(mode, (1, 1), data, "raw", rawmode, 0, 1)
return im.getpixel((0, 0))
def unpack_1(mode, rawmode, value):
assert mode == "1"
im = None
if py3:
im = Image.frombytes(mode, (8, 1), bytes([value]), "raw", rawmode, 0, 1)
else:
im = Image.frombytes(mode, (8, 1), chr(value), "raw", rawmode, 0, 1)
return tuple(im.getdata())
X = 255
assert_equal(unpack_1("1", "1", 1), (0,0,0,0,0,0,0,X))
assert_equal(unpack_1("1", "1;I", 1), (X,X,X,X,X,X,X,0))
assert_equal(unpack_1("1", "1;R", 1), (X,0,0,0,0,0,0,0))
assert_equal(unpack_1("1", "1;IR", 1), (0,X,X,X,X,X,X,X))
assert_equal(unpack_1("1", "1", 170), (X,0,X,0,X,0,X,0))
assert_equal(unpack_1("1", "1;I", 170), (0,X,0,X,0,X,0,X))
assert_equal(unpack_1("1", "1;R", 170), (0,X,0,X,0,X,0,X))
assert_equal(unpack_1("1", "1;IR", 170), (X,0,X,0,X,0,X,0))
assert_equal(unpack("L", "L;2", 1), 0)
assert_equal(unpack("L", "L;4", 1), 0)
assert_equal(unpack("L", "L", 1), 1)
assert_equal(unpack("L", "L;I", 1), 254)
assert_equal(unpack("L", "L;R", 1), 128)
assert_equal(unpack("L", "L;16", 2), 2) # little endian
assert_equal(unpack("L", "L;16B", 2), 1) # big endian
assert_equal(unpack("LA", "LA", 2), (1, 2))
assert_equal(unpack("LA", "LA;L", 2), (1, 2))
assert_equal(unpack("RGB", "RGB", 3), (1, 2, 3))
assert_equal(unpack("RGB", "RGB;L", 3), (1, 2, 3))
assert_equal(unpack("RGB", "RGB;R", 3), (128, 64, 192))
assert_equal(unpack("RGB", "RGB;16B", 6), (1, 3, 5)) # ?
assert_equal(unpack("RGB", "BGR", 3), (3, 2, 1))
assert_equal(unpack("RGB", "RGB;15", 2), (8, 131, 0))
assert_equal(unpack("RGB", "BGR;15", 2), (0, 131, 8))
assert_equal(unpack("RGB", "RGB;16", 2), (8, 64, 0))
assert_equal(unpack("RGB", "BGR;16", 2), (0, 64, 8))
assert_equal(unpack("RGB", "RGB;4B", 2), (17, 0, 34))
assert_equal(unpack("RGB", "RGBX", 4), (1, 2, 3))
assert_equal(unpack("RGB", "BGRX", 4), (3, 2, 1))
assert_equal(unpack("RGB", "XRGB", 4), (2, 3, 4))
assert_equal(unpack("RGB", "XBGR", 4), (4, 3, 2))
assert_equal(unpack("RGBA", "RGBA", 4), (1, 2, 3, 4))
assert_equal(unpack("RGBA", "BGRA", 4), (3, 2, 1, 4))
assert_equal(unpack("RGBA", "ARGB", 4), (2, 3, 4, 1))
assert_equal(unpack("RGBA", "ABGR", 4), (4, 3, 2, 1))
assert_equal(unpack("RGBA", "RGBA;15", 2), (8, 131, 0, 0))
assert_equal(unpack("RGBA", "BGRA;15", 2), (0, 131, 8, 0))
assert_equal(unpack("RGBA", "RGBA;4B", 2), (17, 0, 34, 0))
assert_equal(unpack("RGBX", "RGBX", 4), (1, 2, 3, 4)) # 4->255?
assert_equal(unpack("RGBX", "BGRX", 4), (3, 2, 1, 255))
assert_equal(unpack("RGBX", "XRGB", 4), (2, 3, 4, 255))
assert_equal(unpack("RGBX", "XBGR", 4), (4, 3, 2, 255))
assert_equal(unpack("RGBX", "RGB;15", 2), (8, 131, 0, 255))
assert_equal(unpack("RGBX", "BGR;15", 2), (0, 131, 8, 255))
assert_equal(unpack("RGBX", "RGB;4B", 2), (17, 0, 34, 255))
assert_equal(unpack("CMYK", "CMYK", 4), (1, 2, 3, 4))
assert_equal(unpack("CMYK", "CMYK;I", 4), (254, 253, 252, 251))
assert_exception(ValueError, lambda: unpack("L", "L", 0))
assert_exception(ValueError, lambda: unpack("RGB", "RGB", 2))
assert_exception(ValueError, lambda: unpack("CMYK", "CMYK", 2))
run()

View File

@ -1,31 +0,0 @@
from tester import *
from PIL import Image
import locale
# ref https://github.com/python-pillow/Pillow/issues/272
## on windows, in polish locale:
## import locale
## print locale.setlocale(locale.LC_ALL, 'polish')
## import string
## print len(string.whitespace)
## print ord(string.whitespace[6])
## Polish_Poland.1250
## 7
## 160
# one of string.whitespace is not freely convertable into ascii.
path = "Images/lena.jpg"
def test_sanity():
assert_no_exception(lambda: Image.open(path))
try:
locale.setlocale(locale.LC_ALL, "polish")
except:
skip('polish locale not available')
import string
assert_no_exception(lambda: Image.open(path))

310
test/helper.py Normal file
View File

@ -0,0 +1,310 @@
"""
Helper functions.
"""
from __future__ import print_function
import sys
if sys.version_info[:2] <= (2, 6):
import unittest2 as unittest
else:
import unittest
class PillowTestCase(unittest.TestCase):
def assert_image(self, im, mode, size, msg=None):
if mode is not None:
self.assertEqual(
im.mode, mode,
msg or "got mode %r, expected %r" % (im.mode, mode))
if size is not None:
self.assertEqual(
im.size, size,
msg or "got size %r, expected %r" % (im.size, size))
def assert_image_equal(self, a, b, msg=None):
self.assertEqual(
a.mode, b.mode,
msg or "got mode %r, expected %r" % (a.mode, b.mode))
self.assertEqual(
a.size, b.size,
msg or "got size %r, expected %r" % (a.size, b.size))
self.assertEqual(
a.tobytes(), b.tobytes(),
msg or "got different content")
def assert_image_similar(self, a, b, epsilon, msg=None):
epsilon = float(epsilon)
self.assertEqual(
a.mode, b.mode,
msg or "got mode %r, expected %r" % (a.mode, b.mode))
self.assertEqual(
a.size, b.size,
msg or "got size %r, expected %r" % (a.size, b.size))
diff = 0
try:
ord(b'0')
for abyte, bbyte in zip(a.tobytes(), b.tobytes()):
diff += abs(ord(abyte)-ord(bbyte))
except:
for abyte, bbyte in zip(a.tobytes(), b.tobytes()):
diff += abs(abyte-bbyte)
ave_diff = float(diff)/(a.size[0]*a.size[1])
self.assertGreaterEqual(
epsilon, ave_diff,
msg or "average pixel value difference %.4f > epsilon %.4f" % (
ave_diff, epsilon))
def assert_warning(self, warn_class, func):
import warnings
result = None
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Hopefully trigger a warning.
result = func()
# Verify some things.
self.assertGreaterEqual(len(w), 1)
found = False
for v in w:
if issubclass(v.category, warn_class):
found = True
break
self.assertTrue(found)
return result
# # require that deprecation warnings are triggered
# import warnings
# warnings.simplefilter('default')
# # temporarily turn off resource warnings that warn about unclosed
# # files in the test scripts.
# try:
# warnings.filterwarnings("ignore", category=ResourceWarning)
# except NameError:
# # we expect a NameError on py2.x, since it doesn't have ResourceWarnings.
# pass
import sys
py3 = (sys.version_info >= (3, 0))
# # some test helpers
#
# _target = None
# _tempfiles = []
# _logfile = None
#
#
# def success():
# import sys
# success.count += 1
# if _logfile:
# print(sys.argv[0], success.count, failure.count, file=_logfile)
# return True
#
#
# def failure(msg=None, frame=None):
# import sys
# import linecache
# failure.count += 1
# if _target:
# if frame is None:
# frame = sys._getframe()
# while frame.f_globals.get("__name__") != _target.__name__:
# frame = frame.f_back
# location = (frame.f_code.co_filename, frame.f_lineno)
# prefix = "%s:%d: " % location
# line = linecache.getline(*location)
# print(prefix + line.strip() + " failed:")
# if msg:
# print("- " + msg)
# if _logfile:
# print(sys.argv[0], success.count, failure.count, file=_logfile)
# return False
#
# success.count = failure.count = 0
#
#
# # predicates
#
# def assert_almost_equal(a, b, msg=None, eps=1e-6):
# if abs(a-b) < eps:
# success()
# else:
# failure(msg or "got %r, expected %r" % (a, b))
#
#
# def assert_deep_equal(a, b, msg=None):
# try:
# if len(a) == len(b):
# if all([x == y for x, y in zip(a, b)]):
# success()
# else:
# failure(msg or "got %s, expected %s" % (a, b))
# else:
# failure(msg or "got length %s, expected %s" % (len(a), len(b)))
# except:
# assert_equal(a, b, msg)
#
#
# def assert_match(v, pattern, msg=None):
# import re
# if re.match(pattern, v):
# success()
# else:
# failure(msg or "got %r, doesn't match pattern %r" % (v, pattern))
# helpers
def fromstring(data):
from io import BytesIO
from PIL import Image
return Image.open(BytesIO(data))
def tostring(im, format, **options):
from io import BytesIO
out = BytesIO()
im.save(out, format, **options)
return out.getvalue()
def lena(mode="RGB", cache={}):
from PIL import Image
im = None
# im = cache.get(mode)
if im is None:
if mode == "RGB":
im = Image.open("Images/lena.ppm")
elif mode == "F":
im = lena("L").convert(mode)
elif mode[:4] == "I;16":
im = lena("I").convert(mode)
else:
im = lena("RGB").convert(mode)
# cache[mode] = im
return im
# def assert_image_completely_equal(a, b, msg=None):
# if a != b:
# failure(msg or "images different")
# else:
# success()
#
#
# def tempfile(template, *extra):
# import os
# import os.path
# import sys
# import tempfile
# files = []
# root = os.path.join(tempfile.gettempdir(), 'pillow-tests')
# try:
# os.mkdir(root)
# except OSError:
# pass
# for temp in (template,) + extra:
# assert temp[:5] in ("temp.", "temp_")
# name = os.path.basename(sys.argv[0])
# name = temp[:4] + os.path.splitext(name)[0][4:]
# name = name + "_%d" % len(_tempfiles) + temp[4:]
# name = os.path.join(root, name)
# files.append(name)
# _tempfiles.extend(files)
# return files[0]
#
#
# # test runner
#
# def run():
# global _target, _tests, run
# import sys
# import traceback
# _target = sys.modules["__main__"]
# run = None # no need to run twice
# tests = []
# for name, value in list(vars(_target).items()):
# if name[:5] == "test_" and type(value) is type(success):
# tests.append((value.__code__.co_firstlineno, name, value))
# tests.sort() # sort by line
# for lineno, name, func in tests:
# try:
# _tests = []
# func()
# for func, args in _tests:
# func(*args)
# except:
# t, v, tb = sys.exc_info()
# tb = tb.tb_next
# if tb:
# failure(frame=tb.tb_frame)
# traceback.print_exception(t, v, tb)
# else:
# print("%s:%d: cannot call test function: %s" % (
# sys.argv[0], lineno, v))
# failure.count += 1
#
#
# def yield_test(function, *args):
# # collect delayed/generated tests
# _tests.append((function, args))
#
#
# def skip(msg=None):
# import os
# print("skip")
# os._exit(0) # don't run exit handlers
#
#
# def ignore(pattern):
# """Tells the driver to ignore messages matching the pattern, for the
# duration of the current test."""
# print('ignore: %s' % pattern)
#
#
# def _setup():
# global _logfile
#
# import sys
# if "--coverage" in sys.argv:
# # Temporary: ignore PendingDeprecationWarning from Coverage (Py3.4)
# with warnings.catch_warnings():
# warnings.simplefilter("ignore")
# import coverage
# cov = coverage.coverage(auto_data=True, include="PIL/*")
# cov.start()
#
# def report():
# if run:
# run()
# if success.count and not failure.count:
# print("ok")
# # only clean out tempfiles if test passed
# import os
# import os.path
# import tempfile
# for file in _tempfiles:
# try:
# os.remove(file)
# except OSError:
# pass # report?
# temp_root = os.path.join(tempfile.gettempdir(), 'pillow-tests')
# try:
# os.rmdir(temp_root)
# except OSError:
# pass
#
# import atexit
# atexit.register(report)
#
# if "--log" in sys.argv:
# _logfile = open("test.log", "a")
#
#
# _setup()

32
test/test_000_sanity.py Normal file
View File

@ -0,0 +1,32 @@
from helper import unittest, PillowTestCase
import PIL
import PIL.Image
class TestSanity(PillowTestCase):
def test_sanity(self):
# Make sure we have the binary extension
im = PIL.Image.core.new("L", (100, 100))
self.assertEqual(PIL.Image.VERSION[:3], '1.1')
# Create an image and do stuff with it.
im = PIL.Image.new("1", (100, 100))
self.assertEqual((im.mode, im.size), ('1', (100, 100)))
self.assertEqual(len(im.tobytes()), 1300)
# Create images in all remaining major modes.
im = PIL.Image.new("L", (100, 100))
im = PIL.Image.new("P", (100, 100))
im = PIL.Image.new("RGB", (100, 100))
im = PIL.Image.new("I", (100, 100))
im = PIL.Image.new("F", (100, 100))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,94 @@
from helper import unittest, PillowTestCase
from PIL import Image
import os
base = os.path.join('Tests', 'images', 'bmp')
class TestImage(PillowTestCase):
def get_files(self, d, ext='.bmp'):
return [os.path.join(base, d, f) for f
in os.listdir(os.path.join(base, d)) if ext in f]
def test_bad(self):
""" These shouldn't crash/dos, but they shouldn't return anything
either """
for f in self.get_files('b'):
try:
im = Image.open(f)
im.load()
except Exception: # as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_questionable(self):
""" These shouldn't crash/dos, but its not well defined that these
are in spec """
for f in self.get_files('q'):
try:
im = Image.open(f)
im.load()
except Exception: # as msg:
pass
# print ("Bad Image %s: %s" %(f,msg))
def test_good(self):
""" These should all work. There's a set of target files in the
html directory that we can compare against. """
# Target files, if they're not just replacing the extension
file_map = {'pal1wb.bmp': 'pal1.png',
'pal4rle.bmp': 'pal4.png',
'pal8-0.bmp': 'pal8.png',
'pal8rle.bmp': 'pal8.png',
'pal8topdown.bmp': 'pal8.png',
'pal8nonsquare.bmp': 'pal8nonsquare-v.png',
'pal8os2.bmp': 'pal8.png',
'pal8os2sp.bmp': 'pal8.png',
'pal8os2v2.bmp': 'pal8.png',
'pal8os2v2-16.bmp': 'pal8.png',
'pal8v4.bmp': 'pal8.png',
'pal8v5.bmp': 'pal8.png',
'rgb16-565pal.bmp': 'rgb16-565.png',
'rgb24pal.bmp': 'rgb24.png',
'rgb32.bmp': 'rgb24.png',
'rgb32bf.bmp': 'rgb24.png'
}
def get_compare(f):
(head, name) = os.path.split(f)
if name in file_map:
return os.path.join(base, 'html', file_map[name])
(name, ext) = os.path.splitext(name)
return os.path.join(base, 'html', "%s.png" % name)
for f in self.get_files('g'):
try:
im = Image.open(f)
im.load()
compare = Image.open(get_compare(f))
compare.load()
if im.mode == 'P':
# assert image similar doesn't really work
# with paletized image, since the palette might
# be differently ordered for an equivalent image.
im = im.convert('RGBA')
compare = im.convert('RGBA')
self.assert_image_similar(im, compare, 5)
except Exception as msg:
# there are three here that are unsupported:
unsupported = (os.path.join(base, 'g', 'rgb32bf.bmp'),
os.path.join(base, 'g', 'pal8rle.bmp'),
os.path.join(base, 'g', 'pal4rle.bmp'))
if f not in unsupported:
self.assertTrue(
False, "Unsupported Image %s: %s" % (f, msg))
if __name__ == '__main__':
unittest.main()
# End of file

23
test/test_file_fli.py Normal file
View File

@ -0,0 +1,23 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample ppm stream
file = "Images/lena.fli"
data = open(file, "rb").read()
class TestImage(PillowTestCase):
def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "P")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "FLI")
if __name__ == '__main__':
unittest.main()
# End of file

74
test/test_file_icns.py Normal file
View File

@ -0,0 +1,74 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample icon file
file = "Images/pillow.icns"
data = open(file, "rb").read()
enable_jpeg2k = hasattr(Image.core, 'jp2klib_version')
class TestFileIcns(PillowTestCase):
def test_sanity(self):
# Loading this icon by default should result in the largest size
# (512x512@2x) being loaded
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (1024, 1024))
self.assertEqual(im.format, "ICNS")
def test_sizes(self):
# Check that we can load all of the sizes, and that the final pixel
# dimensions are as expected
im = Image.open(file)
for w, h, r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open(file)
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
def test_older_icon(self):
# This icon was made with Icon Composer rather than iconutil; it still
# uses PNG rather than JP2, however (since it was made on 10.9).
im = Image.open('Tests/images/pillow2.icns')
for w, h, r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow2.icns')
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
def test_jp2_icon(self):
# This icon was made by using Uli Kusterer's oldiconutil to replace
# the PNG images with JPEG 2000 ones. The advantage of doing this is
# that OS X 10.5 supports JPEG 2000 but not PNG; some commercial
# software therefore does just this.
# (oldiconutil is here: https://github.com/uliwitness/oldiconutil)
if not enable_jpeg2k:
return
im = Image.open('Tests/images/pillow3.icns')
for w, h, r in im.info['sizes']:
wr = w * r
hr = h * r
im2 = Image.open('Tests/images/pillow3.icns')
im2.size = (w, h, r)
im2.load()
self.assertEqual(im2.mode, 'RGBA')
self.assertEqual(im2.size, (wr, hr))
if __name__ == '__main__':
unittest.main()
# End of file

23
test/test_file_ico.py Normal file
View File

@ -0,0 +1,23 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample ppm stream
file = "Images/lena.ico"
data = open(file, "rb").read()
class TestFileIco(PillowTestCase):
def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "RGBA")
self.assertEqual(im.size, (16, 16))
self.assertEqual(im.format, "ICO")
if __name__ == '__main__':
unittest.main()
# End of file

23
test/test_file_psd.py Normal file
View File

@ -0,0 +1,23 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample ppm stream
file = "Images/lena.psd"
data = open(file, "rb").read()
class TestImagePsd(PillowTestCase):
def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "RGB")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "PSD")
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -1,4 +1,4 @@
from tester import *
from helper import unittest, PillowTestCase
from PIL import Image
@ -25,10 +25,20 @@ static char basic_bits[] = {
};
"""
def test_pil151():
im = Image.open(BytesIO(PIL151))
class TestFileXbm(PillowTestCase):
assert_no_exception(lambda: im.load())
assert_equal(im.mode, '1')
assert_equal(im.size, (32, 32))
def test_pil151(self):
from io import BytesIO
im = Image.open(BytesIO(PIL151))
im.load()
self.assertEqual(im.mode, '1')
self.assertEqual(im.size, (32, 32))
if __name__ == '__main__':
unittest.main()
# End of file

23
test/test_file_xpm.py Normal file
View File

@ -0,0 +1,23 @@
from helper import unittest, PillowTestCase
from PIL import Image
# sample ppm stream
file = "Images/lena.xpm"
data = open(file, "rb").read()
class TestFileXpm(PillowTestCase):
def test_sanity(self):
im = Image.open(file)
im.load()
self.assertEqual(im.mode, "P")
self.assertEqual(im.size, (128, 128))
self.assertEqual(im.format, "XPM")
if __name__ == '__main__':
unittest.main()
# End of file

22
test/test_font_bdf.py Normal file
View File

@ -0,0 +1,22 @@
from helper import unittest, PillowTestCase
from PIL import FontFile, BdfFontFile
filename = "Images/courB08.bdf"
class TestImage(PillowTestCase):
def test_sanity(self):
file = open(filename, "rb")
font = BdfFontFile.BdfFontFile(file)
self.assertIsInstance(font, FontFile.FontFile)
self.assertEqual(len([_f for _f in font.glyph if _f]), 190)
if __name__ == '__main__':
unittest.main()
# End of file

48
test/test_format_lab.py Normal file
View File

@ -0,0 +1,48 @@
from helper import unittest, PillowTestCase
from PIL import Image
class TestFormatLab(PillowTestCase):
def test_white(self):
i = Image.open('Tests/images/lab.tif')
i.load()
self.assertEqual(i.mode, 'LAB')
self.assertEqual(i.getbands(), ('L', 'A', 'B'))
k = i.getpixel((0, 0))
self.assertEqual(k, (255, 128, 128))
L = i.getdata(0)
a = i.getdata(1)
b = i.getdata(2)
self.assertEqual(list(L), [255]*100)
self.assertEqual(list(a), [128]*100)
self.assertEqual(list(b), [128]*100)
def test_green(self):
# l= 50 (/100), a = -100 (-128 .. 128) b=0 in PS
# == RGB: 0, 152, 117
i = Image.open('Tests/images/lab-green.tif')
k = i.getpixel((0, 0))
self.assertEqual(k, (128, 28, 128))
def test_red(self):
# l= 50 (/100), a = 100 (-128 .. 128) b=0 in PS
# == RGB: 255, 0, 124
i = Image.open('Tests/images/lab-red.tif')
k = i.getpixel((0, 0))
self.assertEqual(k, (128, 228, 128))
if __name__ == '__main__':
unittest.main()
# End of file

46
test/test_image_array.py Normal file
View File

@ -0,0 +1,46 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
im = lena().resize((128, 100))
class TestImageCrop(PillowTestCase):
def test_toarray(self):
def test(mode):
ai = im.convert(mode).__array_interface__
return ai["shape"], ai["typestr"], len(ai["data"])
# self.assertEqual(test("1"), ((100, 128), '|b1', 1600))
self.assertEqual(test("L"), ((100, 128), '|u1', 12800))
# FIXME: wrong?
self.assertEqual(test("I"), ((100, 128), Image._ENDIAN + 'i4', 51200))
# FIXME: wrong?
self.assertEqual(test("F"), ((100, 128), Image._ENDIAN + 'f4', 51200))
self.assertEqual(test("RGB"), ((100, 128, 3), '|u1', 38400))
self.assertEqual(test("RGBA"), ((100, 128, 4), '|u1', 51200))
self.assertEqual(test("RGBX"), ((100, 128, 4), '|u1', 51200))
def test_fromarray(self):
def test(mode):
i = im.convert(mode)
a = i.__array_interface__
a["strides"] = 1 # pretend it's non-contigous
i.__array_interface__ = a # patch in new version of attribute
out = Image.fromarray(i)
return out.mode, out.size, list(i.getdata()) == list(out.getdata())
# self.assertEqual(test("1"), ("1", (128, 100), True))
self.assertEqual(test("L"), ("L", (128, 100), True))
self.assertEqual(test("I"), ("I", (128, 100), True))
self.assertEqual(test("F"), ("F", (128, 100), True))
self.assertEqual(test("RGB"), ("RGB", (128, 100), True))
self.assertEqual(test("RGBA"), ("RGBA", (128, 100), True))
self.assertEqual(test("RGBX"), ("RGBA", (128, 100), True))
if __name__ == '__main__':
unittest.main()
# End of file

20
test/test_image_copy.py Normal file
View File

@ -0,0 +1,20 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImageCopy(PillowTestCase):
def test_copy(self):
def copy(mode):
im = lena(mode)
out = im.copy()
self.assertEqual(out.mode, mode)
self.assertEqual(out.size, im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
copy(mode)
if __name__ == '__main__':
unittest.main()
# End of file

59
test/test_image_crop.py Normal file
View File

@ -0,0 +1,59 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImageCrop(PillowTestCase):
def test_crop(self):
def crop(mode):
out = lena(mode).crop((50, 50, 100, 100))
self.assertEqual(out.mode, mode)
self.assertEqual(out.size, (50, 50))
for mode in "1", "P", "L", "RGB", "I", "F":
crop(mode)
def test_wide_crop(self):
def crop(*bbox):
i = im.crop(bbox)
h = i.histogram()
while h and not h[-1]:
del h[-1]
return tuple(h)
im = Image.new("L", (100, 100), 1)
self.assertEqual(crop(0, 0, 100, 100), (0, 10000))
self.assertEqual(crop(25, 25, 75, 75), (0, 2500))
# sides
self.assertEqual(crop(-25, 0, 25, 50), (1250, 1250))
self.assertEqual(crop(0, -25, 50, 25), (1250, 1250))
self.assertEqual(crop(75, 0, 125, 50), (1250, 1250))
self.assertEqual(crop(0, 75, 50, 125), (1250, 1250))
self.assertEqual(crop(-25, 25, 125, 75), (2500, 5000))
self.assertEqual(crop(25, -25, 75, 125), (2500, 5000))
# corners
self.assertEqual(crop(-25, -25, 25, 25), (1875, 625))
self.assertEqual(crop(75, -25, 125, 25), (1875, 625))
self.assertEqual(crop(75, 75, 125, 125), (1875, 625))
self.assertEqual(crop(-25, 75, 25, 125), (1875, 625))
def test_negative_crop(self):
# Check negative crop size (@PIL171)
im = Image.new("L", (512, 512))
im = im.crop((400, 400, 200, 200))
self.assertEqual(im.size, (0, 0))
self.assertEqual(len(im.getdata()), 0)
self.assertRaises(IndexError, lambda: im.getdata()[0])
if __name__ == '__main__':
unittest.main()
# End of file

91
test/test_image_filter.py Normal file
View File

@ -0,0 +1,91 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
from PIL import ImageFilter
class TestImageFilter(PillowTestCase):
def test_sanity(self):
def filter(filter):
im = lena("L")
out = im.filter(filter)
self.assertEqual(out.mode, im.mode)
self.assertEqual(out.size, im.size)
filter(ImageFilter.BLUR)
filter(ImageFilter.CONTOUR)
filter(ImageFilter.DETAIL)
filter(ImageFilter.EDGE_ENHANCE)
filter(ImageFilter.EDGE_ENHANCE_MORE)
filter(ImageFilter.EMBOSS)
filter(ImageFilter.FIND_EDGES)
filter(ImageFilter.SMOOTH)
filter(ImageFilter.SMOOTH_MORE)
filter(ImageFilter.SHARPEN)
filter(ImageFilter.MaxFilter)
filter(ImageFilter.MedianFilter)
filter(ImageFilter.MinFilter)
filter(ImageFilter.ModeFilter)
filter(ImageFilter.Kernel((3, 3), list(range(9))))
self.assertRaises(TypeError, lambda: filter("hello"))
def test_crash(self):
# crashes on small images
im = Image.new("RGB", (1, 1))
im.filter(ImageFilter.SMOOTH)
im = Image.new("RGB", (2, 2))
im.filter(ImageFilter.SMOOTH)
im = Image.new("RGB", (3, 3))
im.filter(ImageFilter.SMOOTH)
def test_modefilter(self):
def modefilter(mode):
im = Image.new(mode, (3, 3), None)
im.putdata(list(range(9)))
# image is:
# 0 1 2
# 3 4 5
# 6 7 8
mod = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
im.putdata([0, 0, 1, 2, 5, 1, 5, 2, 0]) # mode=0
mod2 = im.filter(ImageFilter.ModeFilter).getpixel((1, 1))
return mod, mod2
self.assertEqual(modefilter("1"), (4, 0))
self.assertEqual(modefilter("L"), (4, 0))
self.assertEqual(modefilter("P"), (4, 0))
self.assertEqual(modefilter("RGB"), ((4, 0, 0), (0, 0, 0)))
def test_rankfilter(self):
def rankfilter(mode):
im = Image.new(mode, (3, 3), None)
im.putdata(list(range(9)))
# image is:
# 0 1 2
# 3 4 5
# 6 7 8
min = im.filter(ImageFilter.MinFilter).getpixel((1, 1))
med = im.filter(ImageFilter.MedianFilter).getpixel((1, 1))
max = im.filter(ImageFilter.MaxFilter).getpixel((1, 1))
return min, med, max
self.assertEqual(rankfilter("1"), (0, 4, 8))
self.assertEqual(rankfilter("L"), (0, 4, 8))
self.assertRaises(ValueError, lambda: rankfilter("P"))
self.assertEqual(rankfilter("RGB"), ((0, 0, 0), (4, 0, 0), (8, 0, 0)))
self.assertEqual(rankfilter("I"), (0, 4, 8))
self.assertEqual(rankfilter("F"), (0.0, 4.0, 8.0))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,18 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImageFromBytes(PillowTestCase):
def test_sanity(self):
im1 = lena()
im2 = Image.frombytes(im1.mode, im1.size, im1.tobytes())
self.assert_image_equal(im1, im2)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,26 @@
from helper import unittest, PillowTestCase
from PIL import Image
class TestImageGetBands(PillowTestCase):
def test_getbands(self):
self.assertEqual(Image.new("1", (1, 1)).getbands(), ("1",))
self.assertEqual(Image.new("L", (1, 1)).getbands(), ("L",))
self.assertEqual(Image.new("I", (1, 1)).getbands(), ("I",))
self.assertEqual(Image.new("F", (1, 1)).getbands(), ("F",))
self.assertEqual(Image.new("P", (1, 1)).getbands(), ("P",))
self.assertEqual(Image.new("RGB", (1, 1)).getbands(), ("R", "G", "B"))
self.assertEqual(
Image.new("RGBA", (1, 1)).getbands(), ("R", "G", "B", "A"))
self.assertEqual(
Image.new("CMYK", (1, 1)).getbands(), ("C", "M", "Y", "K"))
self.assertEqual(
Image.new("YCbCr", (1, 1)).getbands(), ("Y", "Cb", "Cr"))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,45 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImage(PillowTestCase):
def test_sanity(self):
bbox = lena().getbbox()
self.assertIsInstance(bbox, tuple)
def test_bbox(self):
# 8-bit mode
im = Image.new("L", (100, 100), 0)
self.assertEqual(im.getbbox(), None)
im.paste(255, (10, 25, 90, 75))
self.assertEqual(im.getbbox(), (10, 25, 90, 75))
im.paste(255, (25, 10, 75, 90))
self.assertEqual(im.getbbox(), (10, 10, 90, 90))
im.paste(255, (-10, -10, 110, 110))
self.assertEqual(im.getbbox(), (0, 0, 100, 100))
# 32-bit mode
im = Image.new("RGB", (100, 100), 0)
self.assertEqual(im.getbbox(), None)
im.paste(255, (10, 25, 90, 75))
self.assertEqual(im.getbbox(), (10, 25, 90, 75))
im.paste(255, (25, 10, 75, 90))
self.assertEqual(im.getbbox(), (10, 10, 90, 90))
im.paste(255, (-10, -10, 110, 110))
self.assertEqual(im.getbbox(), (0, 0, 100, 100))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,74 @@
from helper import unittest, PillowTestCase, lena
class TestImage(PillowTestCase):
def test_getcolors(self):
def getcolors(mode, limit=None):
im = lena(mode)
if limit:
colors = im.getcolors(limit)
else:
colors = im.getcolors()
if colors:
return len(colors)
return None
self.assertEqual(getcolors("1"), 2)
self.assertEqual(getcolors("L"), 193)
self.assertEqual(getcolors("I"), 193)
self.assertEqual(getcolors("F"), 193)
self.assertEqual(getcolors("P"), 54) # fixed palette
self.assertEqual(getcolors("RGB"), None)
self.assertEqual(getcolors("RGBA"), None)
self.assertEqual(getcolors("CMYK"), None)
self.assertEqual(getcolors("YCbCr"), None)
self.assertEqual(getcolors("L", 128), None)
self.assertEqual(getcolors("L", 1024), 193)
self.assertEqual(getcolors("RGB", 8192), None)
self.assertEqual(getcolors("RGB", 16384), 14836)
self.assertEqual(getcolors("RGB", 100000), 14836)
self.assertEqual(getcolors("RGBA", 16384), 14836)
self.assertEqual(getcolors("CMYK", 16384), 14836)
self.assertEqual(getcolors("YCbCr", 16384), 11995)
# --------------------------------------------------------------------
def test_pack(self):
# Pack problems for small tables (@PIL209)
im = lena().quantize(3).convert("RGB")
expected = [
(3236, (227, 183, 147)),
(6297, (143, 84, 81)),
(6851, (208, 143, 112))]
A = im.getcolors(maxcolors=2)
self.assertEqual(A, None)
A = im.getcolors(maxcolors=3)
A.sort()
self.assertEqual(A, expected)
A = im.getcolors(maxcolors=4)
A.sort()
self.assertEqual(A, expected)
A = im.getcolors(maxcolors=8)
A.sort()
self.assertEqual(A, expected)
A = im.getcolors(maxcolors=16)
A.sort()
self.assertEqual(A, expected)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,27 @@
from helper import unittest, PillowTestCase, lena
class TestImageGetExtrema(PillowTestCase):
def test_extrema(self):
def extrema(mode):
return lena(mode).getextrema()
self.assertEqual(extrema("1"), (0, 255))
self.assertEqual(extrema("L"), (40, 235))
self.assertEqual(extrema("I"), (40, 235))
self.assertEqual(extrema("F"), (40.0, 235.0))
self.assertEqual(extrema("P"), (11, 218)) # fixed palette
self.assertEqual(
extrema("RGB"), ((61, 255), (26, 234), (44, 223)))
self.assertEqual(
extrema("RGBA"), ((61, 255), (26, 234), (44, 223), (255, 255)))
self.assertEqual(
extrema("CMYK"), ((0, 194), (21, 229), (32, 211), (0, 0)))
if __name__ == '__main__':
unittest.main()
# End of file

19
test/test_image_getim.py Normal file
View File

@ -0,0 +1,19 @@
from helper import unittest, PillowTestCase, lena, py3
class TestImageGetIm(PillowTestCase):
def test_sanity(self):
im = lena()
type_repr = repr(type(im.getim()))
if py3:
self.assertIn("PyCapsule", type_repr)
self.assertIsInstance(im.im.id, int)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,26 @@
from helper import unittest, PillowTestCase, lena
class TestImageGetPalette(PillowTestCase):
def test_palette(self):
def palette(mode):
p = lena(mode).getpalette()
if p:
return p[:10]
return None
self.assertEqual(palette("1"), None)
self.assertEqual(palette("L"), None)
self.assertEqual(palette("I"), None)
self.assertEqual(palette("F"), None)
self.assertEqual(palette("P"), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
self.assertEqual(palette("RGB"), None)
self.assertEqual(palette("RGBA"), None)
self.assertEqual(palette("CMYK"), None)
self.assertEqual(palette("YCbCr"), None)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,26 @@
from helper import unittest, PillowTestCase, lena
class TestImageHistogram(PillowTestCase):
def test_histogram(self):
def histogram(mode):
h = lena(mode).histogram()
return len(h), min(h), max(h)
self.assertEqual(histogram("1"), (256, 0, 8872))
self.assertEqual(histogram("L"), (256, 0, 199))
self.assertEqual(histogram("I"), (256, 0, 199))
self.assertEqual(histogram("F"), (256, 0, 199))
self.assertEqual(histogram("P"), (256, 0, 2912))
self.assertEqual(histogram("RGB"), (768, 0, 285))
self.assertEqual(histogram("RGBA"), (1024, 0, 16384))
self.assertEqual(histogram("CMYK"), (1024, 0, 16384))
self.assertEqual(histogram("YCbCr"), (768, 0, 741))
if __name__ == '__main__':
unittest.main()
# End of file

35
test/test_image_load.py Normal file
View File

@ -0,0 +1,35 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
import os
class TestImageLoad(PillowTestCase):
def test_sanity(self):
im = lena()
pix = im.load()
self.assertEqual(pix[0, 0], (223, 162, 133))
def test_close(self):
im = Image.open("Images/lena.gif")
im.close()
self.assertRaises(ValueError, lambda: im.load())
self.assertRaises(ValueError, lambda: im.getpixel((0, 0)))
def test_contextmanager(self):
fn = None
with Image.open("Images/lena.gif") as im:
fn = im.fp.fileno()
os.fstat(fn)
self.assertRaises(OSError, lambda: os.fstat(fn))
if __name__ == '__main__':
unittest.main()
# End of file

36
test/test_image_mode.py Normal file
View File

@ -0,0 +1,36 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImage(PillowTestCase):
def test_sanity(self):
im = lena()
im.mode
def test_properties(self):
def check(mode, *result):
signature = (
Image.getmodebase(mode), Image.getmodetype(mode),
Image.getmodebands(mode), Image.getmodebandnames(mode),
)
self.assertEqual(signature, result)
check("1", "L", "L", 1, ("1",))
check("L", "L", "L", 1, ("L",))
check("P", "RGB", "L", 1, ("P",))
check("I", "L", "I", 1, ("I",))
check("F", "L", "F", 1, ("F",))
check("RGB", "RGB", "L", 3, ("R", "G", "B"))
check("RGBA", "RGB", "L", 4, ("R", "G", "B", "A"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("RGBX", "RGB", "L", 4, ("R", "G", "B", "X"))
check("CMYK", "RGB", "L", 4, ("C", "M", "Y", "K"))
check("YCbCr", "RGB", "L", 3, ("Y", "Cb", "Cr"))
if __name__ == '__main__':
unittest.main()
# End of file

25
test/test_image_offset.py Normal file
View File

@ -0,0 +1,25 @@
from helper import unittest, PillowTestCase, lena
class TestImage(PillowTestCase):
def test_offset(self):
im1 = lena()
im2 = self.assert_warning(DeprecationWarning, lambda: im1.offset(10))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((10, 10)))
im2 = self.assert_warning(
DeprecationWarning, lambda: im1.offset(10, 20))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((10, 20)))
im2 = self.assert_warning(
DeprecationWarning, lambda: im1.offset(20, 20))
self.assertEqual(im1.getpixel((0, 0)), im2.getpixel((20, 20)))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,52 @@
from helper import unittest, PillowTestCase
from PIL import Image
class TestImagePutAlpha(PillowTestCase):
def test_interface(self):
im = Image.new("RGBA", (1, 1), (1, 2, 3, 0))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 0))
im = Image.new("RGBA", (1, 1), (1, 2, 3))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 255))
im.putalpha(Image.new("L", im.size, 4))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
im.putalpha(5)
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 5))
def test_promote(self):
im = Image.new("L", (1, 1), 1)
self.assertEqual(im.getpixel((0, 0)), 1)
im.putalpha(2)
self.assertEqual(im.mode, 'LA')
self.assertEqual(im.getpixel((0, 0)), (1, 2))
im = Image.new("RGB", (1, 1), (1, 2, 3))
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3))
im.putalpha(4)
self.assertEqual(im.mode, 'RGBA')
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
def test_readonly(self):
im = Image.new("RGB", (1, 1), (1, 2, 3))
im.readonly = 1
im.putalpha(4)
self.assertFalse(im.readonly)
self.assertEqual(im.mode, 'RGBA')
self.assertEqual(im.getpixel((0, 0)), (1, 2, 3, 4))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,48 @@
from helper import unittest, PillowTestCase, lena
import sys
from PIL import Image
class TestImagePutData(PillowTestCase):
def test_sanity(self):
im1 = lena()
data = list(im1.getdata())
im2 = Image.new(im1.mode, im1.size, 0)
im2.putdata(data)
self.assert_image_equal(im1, im2)
# readonly
im2 = Image.new(im1.mode, im2.size, 0)
im2.readonly = 1
im2.putdata(data)
self.assertFalse(im2.readonly)
self.assert_image_equal(im1, im2)
def test_long_integers(self):
# see bug-200802-systemerror
def put(value):
im = Image.new("RGBA", (1, 1))
im.putdata([value])
return im.getpixel((0, 0))
self.assertEqual(put(0xFFFFFFFF), (255, 255, 255, 255))
self.assertEqual(put(0xFFFFFFFF), (255, 255, 255, 255))
self.assertEqual(put(-1), (255, 255, 255, 255))
self.assertEqual(put(-1), (255, 255, 255, 255))
if sys.maxsize > 2**32:
self.assertEqual(put(sys.maxsize), (255, 255, 255, 255))
else:
self.assertEqual(put(sys.maxsize), (255, 255, 255, 127))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,36 @@
from helper import unittest, PillowTestCase, lena
from PIL import ImagePalette
class TestImage(PillowTestCase):
def test_putpalette(self):
def palette(mode):
im = lena(mode).copy()
im.putpalette(list(range(256))*3)
p = im.getpalette()
if p:
return im.mode, p[:10]
return im.mode
self.assertRaises(ValueError, lambda: palette("1"))
self.assertEqual(palette("L"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
self.assertEqual(palette("P"), ("P", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
self.assertRaises(ValueError, lambda: palette("I"))
self.assertRaises(ValueError, lambda: palette("F"))
self.assertRaises(ValueError, lambda: palette("RGB"))
self.assertRaises(ValueError, lambda: palette("RGBA"))
self.assertRaises(ValueError, lambda: palette("YCbCr"))
def test_imagepalette(self):
im = lena("P")
im.putpalette(ImagePalette.negative())
im.putpalette(ImagePalette.random())
im.putpalette(ImagePalette.sepia())
im.putpalette(ImagePalette.wedge())
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,35 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImage(PillowTestCase):
def test_sanity(self):
im = lena()
im = im.quantize()
self.assert_image(im, "P", im.size)
im = lena()
im = im.quantize(palette=lena("P"))
self.assert_image(im, "P", im.size)
def test_octree_quantize(self):
im = lena()
im = im.quantize(100, Image.FASTOCTREE)
self.assert_image(im, "P", im.size)
assert len(im.getcolors()) == 100
def test_rgba_quantize(self):
im = lena('RGBA')
im.quantize()
self.assertRaises(Exception, lambda: im.quantize(method=0))
if __name__ == '__main__':
unittest.main()
# End of file

19
test/test_image_resize.py Normal file
View File

@ -0,0 +1,19 @@
from helper import unittest, PillowTestCase, lena
class TestImageResize(PillowTestCase):
def test_resize(self):
def resize(mode, size):
out = lena(mode).resize(size)
self.assertEqual(out.mode, mode)
self.assertEqual(out.size, size)
for mode in "1", "P", "L", "RGB", "I", "F":
resize(mode, (100, 100))
resize(mode, (200, 200))
if __name__ == '__main__':
unittest.main()
# End of file

22
test/test_image_rotate.py Normal file
View File

@ -0,0 +1,22 @@
from helper import unittest, PillowTestCase, lena
class TestImageRotate(PillowTestCase):
def test_rotate(self):
def rotate(mode):
im = lena(mode)
out = im.rotate(45)
self.assertEqual(out.mode, mode)
self.assertEqual(out.size, im.size) # default rotate clips output
out = im.rotate(45, expand=1)
self.assertEqual(out.mode, mode)
self.assertNotEqual(out.size, im.size)
for mode in "1", "P", "L", "RGB", "I", "F":
rotate(mode)
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,43 @@
from helper import unittest, PillowTestCase, lena
class TestImageThumbnail(PillowTestCase):
def test_sanity(self):
im = lena()
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
def test_aspect(self):
im = lena()
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
im = lena().resize((128, 256))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (50, 100))
im = lena().resize((128, 256))
im.thumbnail((50, 100))
self.assert_image(im, im.mode, (50, 100))
im = lena().resize((256, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 50))
im = lena().resize((256, 128))
im.thumbnail((100, 50))
self.assert_image(im, im.mode, (100, 50))
im = lena().resize((128, 128))
im.thumbnail((100, 100))
self.assert_image(im, im.mode, (100, 100))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,22 @@
from helper import unittest, PillowTestCase, lena, fromstring
class TestImage(PillowTestCase):
def test_sanity(self):
self.assertRaises(ValueError, lambda: lena().tobitmap())
lena().convert("1").tobitmap()
im1 = lena().convert("1")
bitmap = im1.tobitmap()
self.assertIsInstance(bitmap, bytes)
self.assert_image_equal(im1, fromstring(bitmap))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,13 @@
from helper import unittest, lena
class TestImageToBytes(unittest.TestCase):
def test_sanity(self):
data = lena().tobytes()
self.assertTrue(isinstance(data, bytes))
if __name__ == '__main__':
unittest.main()
# End of file

View File

@ -0,0 +1,125 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
class TestImageTransform(PillowTestCase):
def test_extent(self):
im = lena('RGB')
(w, h) = im.size
transformed = im.transform(im.size, Image.EXTENT,
(0, 0,
w//2, h//2), # ul -> lr
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0, 0, w, h))
# undone -- precision?
self.assert_image_similar(transformed, scaled, 10)
def test_quad(self):
# one simple quad transform, equivalent to scale & crop upper left quad
im = lena('RGB')
(w, h) = im.size
transformed = im.transform(im.size, Image.QUAD,
(0, 0, 0, h//2,
# ul -> ccw around quad:
w//2, h//2, w//2, 0),
Image.BILINEAR)
scaled = im.resize((w*2, h*2), Image.BILINEAR).crop((0, 0, w, h))
self.assert_image_equal(transformed, scaled)
def test_mesh(self):
# this should be a checkerboard of halfsized lenas in ul, lr
im = lena('RGBA')
(w, h) = im.size
transformed = im.transform(im.size, Image.MESH,
[((0, 0, w//2, h//2), # box
(0, 0, 0, h,
w, h, w, 0)), # ul -> ccw around quad
((w//2, h//2, w, h), # box
(0, 0, 0, h,
w, h, w, 0))], # ul -> ccw around quad
Image.BILINEAR)
# transformed.save('transformed.png')
scaled = im.resize((w//2, h//2), Image.BILINEAR)
checker = Image.new('RGBA', im.size)
checker.paste(scaled, (0, 0))
checker.paste(scaled, (w//2, h//2))
self.assert_image_equal(transformed, checker)
# now, check to see that the extra area is (0, 0, 0, 0)
blank = Image.new('RGBA', (w//2, h//2), (0, 0, 0, 0))
self.assert_image_equal(blank, transformed.crop((w//2, 0, w, h//2)))
self.assert_image_equal(blank, transformed.crop((0, h//2, w//2, h)))
def _test_alpha_premult(self, op):
# create image with half white, half black,
# with the black half transparent.
# do op,
# there should be no darkness in the white section.
im = Image.new('RGBA', (10, 10), (0, 0, 0, 0))
im2 = Image.new('RGBA', (5, 10), (255, 255, 255, 255))
im.paste(im2, (0, 0))
im = op(im, (40, 10))
im_background = Image.new('RGB', (40, 10), (255, 255, 255))
im_background.paste(im, (0, 0), im)
hist = im_background.histogram()
self.assertEqual(40*10, hist[-1])
def test_alpha_premult_resize(self):
def op(im, sz):
return im.resize(sz, Image.LINEAR)
self._test_alpha_premult(op)
def test_alpha_premult_transform(self):
def op(im, sz):
(w, h) = im.size
return im.transform(sz, Image.EXTENT,
(0, 0,
w, h),
Image.BILINEAR)
self._test_alpha_premult(op)
def test_blank_fill(self):
# attempting to hit
# https://github.com/python-pillow/Pillow/issues/254 reported
#
# issue is that transforms with transparent overflow area
# contained junk from previous images, especially on systems with
# constrained memory. So, attempt to fill up memory with a
# pattern, free it, and then run the mesh test again. Using a 1Mp
# image with 4 bands, for 4 megs of data allocated, x 64. OMM (64
# bit 12.04 VM with 512 megs available, this fails with Pillow <
# a0eaf06cc5f62a6fb6de556989ac1014ff3348ea
#
# Running by default, but I'd totally understand not doing it in
# the future
foo = [Image.new('RGBA', (1024, 1024), (a, a, a, a))
for a in range(1, 65)]
# Yeah. Watch some JIT optimize this out.
foo = None
self.test_mesh()
if __name__ == '__main__':
unittest.main()
# End of file

74
test/test_imagechops.py Normal file
View File

@ -0,0 +1,74 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
from PIL import ImageChops
class TestImage(PillowTestCase):
def test_sanity(self):
im = lena("L")
ImageChops.constant(im, 128)
ImageChops.duplicate(im)
ImageChops.invert(im)
ImageChops.lighter(im, im)
ImageChops.darker(im, im)
ImageChops.difference(im, im)
ImageChops.multiply(im, im)
ImageChops.screen(im, im)
ImageChops.add(im, im)
ImageChops.add(im, im, 2.0)
ImageChops.add(im, im, 2.0, 128)
ImageChops.subtract(im, im)
ImageChops.subtract(im, im, 2.0)
ImageChops.subtract(im, im, 2.0, 128)
ImageChops.add_modulo(im, im)
ImageChops.subtract_modulo(im, im)
ImageChops.blend(im, im, 0.5)
ImageChops.composite(im, im, im)
ImageChops.offset(im, 10)
ImageChops.offset(im, 10, 20)
def test_logical(self):
def table(op, a, b):
out = []
for x in (a, b):
imx = Image.new("1", (1, 1), x)
for y in (a, b):
imy = Image.new("1", (1, 1), y)
out.append(op(imx, imy).getpixel((0, 0)))
return tuple(out)
self.assertEqual(
table(ImageChops.logical_and, 0, 1), (0, 0, 0, 255))
self.assertEqual(
table(ImageChops.logical_or, 0, 1), (0, 255, 255, 255))
self.assertEqual(
table(ImageChops.logical_xor, 0, 1), (0, 255, 255, 0))
self.assertEqual(
table(ImageChops.logical_and, 0, 128), (0, 0, 0, 255))
self.assertEqual(
table(ImageChops.logical_or, 0, 128), (0, 255, 255, 255))
self.assertEqual(
table(ImageChops.logical_xor, 0, 128), (0, 255, 255, 0))
self.assertEqual(
table(ImageChops.logical_and, 0, 255), (0, 0, 0, 255))
self.assertEqual(
table(ImageChops.logical_or, 0, 255), (0, 255, 255, 255))
self.assertEqual(
table(ImageChops.logical_xor, 0, 255), (0, 255, 255, 0))
if __name__ == '__main__':
unittest.main()
# End of file

214
test/test_imagecms.py Normal file
View File

@ -0,0 +1,214 @@
from helper import unittest, PillowTestCase, lena
from PIL import Image
try:
from PIL import ImageCms
ImageCms.core.profile_open
except ImportError as v:
# Skipped via setUp()
pass
SRGB = "Tests/icc/sRGB.icm"
class TestImage(PillowTestCase):
def setUp(self):
try:
from PIL import ImageCms
except ImportError as v:
self.skipTest(v)
def test_sanity(self):
# basic smoke test.
# this mostly follows the cms_test outline.
v = ImageCms.versions() # should return four strings
self.assertEqual(v[0], '1.0.0 pil')
self.assertEqual(list(map(type, v)), [str, str, str, str])
# internal version number
self.assertRegexpMatches(ImageCms.core.littlecms_version, "\d+\.\d+$")
i = ImageCms.profileToProfile(lena(), SRGB, SRGB)
self.assert_image(i, "RGB", (128, 128))
i = lena()
ImageCms.profileToProfile(i, SRGB, SRGB, inPlace=True)
self.assert_image(i, "RGB", (128, 128))
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
i = lena()
t = ImageCms.buildTransform(SRGB, SRGB, "RGB", "RGB")
ImageCms.applyTransform(lena(), t, inPlace=True)
self.assert_image(i, "RGB", (128, 128))
p = ImageCms.createProfile("sRGB")
o = ImageCms.getOpenProfile(SRGB)
t = ImageCms.buildTransformFromOpenProfiles(p, o, "RGB", "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
t = ImageCms.buildProofTransform(SRGB, SRGB, SRGB, "RGB", "RGB")
self.assertEqual(t.inputMode, "RGB")
self.assertEqual(t.outputMode, "RGB")
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "RGB", (128, 128))
# test PointTransform convenience API
lena().point(t)
def test_name(self):
# get profile information for file
self.assertEqual(
ImageCms.getProfileName(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_info(self):
self.assertEqual(
ImageCms.getProfileInfo(SRGB).splitlines(), [
'sRGB IEC61966-2.1', '',
'Copyright (c) 1998 Hewlett-Packard Company', ''])
def test_copyright(self):
self.assertEqual(
ImageCms.getProfileCopyright(SRGB).strip(),
'Copyright (c) 1998 Hewlett-Packard Company')
def test_manufacturer(self):
self.assertEqual(
ImageCms.getProfileManufacturer(SRGB).strip(),
'IEC http://www.iec.ch')
def test_model(self):
self.assertEqual(
ImageCms.getProfileModel(SRGB).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_description(self):
self.assertEqual(
ImageCms.getProfileDescription(SRGB).strip(),
'sRGB IEC61966-2.1')
def test_intent(self):
self.assertEqual(ImageCms.getDefaultIntent(SRGB), 0)
self.assertEqual(ImageCms.isIntentSupported(
SRGB, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_profile_object(self):
# same, using profile object
p = ImageCms.createProfile("sRGB")
# self.assertEqual(ImageCms.getProfileName(p).strip(),
# 'sRGB built-in - (lcms internal)')
# self.assertEqual(ImageCms.getProfileInfo(p).splitlines(),
# ['sRGB built-in', '', 'WhitePoint : D65 (daylight)', '', ''])
self.assertEqual(ImageCms.getDefaultIntent(p), 0)
self.assertEqual(ImageCms.isIntentSupported(
p, ImageCms.INTENT_ABSOLUTE_COLORIMETRIC,
ImageCms.DIRECTION_INPUT), 1)
def test_extensions(self):
# extensions
from io import BytesIO
i = Image.open("Tests/images/rgb.jpg")
p = ImageCms.getOpenProfile(BytesIO(i.info["icc_profile"]))
self.assertEqual(
ImageCms.getProfileName(p).strip(),
'IEC 61966-2.1 Default RGB colour space - sRGB')
def test_exceptions(self):
# the procedural pyCMS API uses PyCMSError for all sorts of errors
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.profileToProfile(lena(), "foo", "bar"))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.buildTransform("foo", "bar", "RGB", "RGB"))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.getProfileName(None))
self.assertRaises(
ImageCms.PyCMSError,
lambda: ImageCms.isIntentSupported(SRGB, None, None))
def test_display_profile(self):
# try fetching the profile for the current display device
ImageCms.get_display_profile()
def test_lab_color_profile(self):
ImageCms.createProfile("LAB", 5000)
ImageCms.createProfile("LAB", 6500)
def test_simple_lab(self):
i = Image.new('RGB', (10, 10), (128, 128, 128))
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
i_lab = ImageCms.applyTransform(i, t)
self.assertEqual(i_lab.mode, 'LAB')
k = i_lab.getpixel((0, 0))
# not a linear luminance map. so L != 128:
self.assertEqual(k, (137, 128, 128))
L = i_lab.getdata(0)
a = i_lab.getdata(1)
b = i_lab.getdata(2)
self.assertEqual(list(L), [137] * 100)
self.assertEqual(list(a), [128] * 100)
self.assertEqual(list(b), [128] * 100)
def test_lab_color(self):
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(SRGB, pLab, "RGB", "LAB")
# Need to add a type mapping for some PIL type to TYPE_Lab_8 in
# findLCMSType, and have that mapping work back to a PIL mode
# (likely RGB).
i = ImageCms.applyTransform(lena(), t)
self.assert_image(i, "LAB", (128, 128))
# i.save('temp.lab.tif') # visually verified vs PS.
target = Image.open('Tests/images/lena.Lab.tif')
self.assert_image_similar(i, target, 30)
def test_lab_srgb(self):
pLab = ImageCms.createProfile("LAB")
t = ImageCms.buildTransform(pLab, SRGB, "LAB", "RGB")
img = Image.open('Tests/images/lena.Lab.tif')
img_srgb = ImageCms.applyTransform(img, t)
# img_srgb.save('temp.srgb.tif') # visually verified vs ps.
self.assert_image_similar(lena(), img_srgb, 30)
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(lena(), t)
out = ImageCms.applyTransform(i, t2)
self.assert_image_similar(lena(), out, 2)
if __name__ == '__main__':
unittest.main()
# End of file

Some files were not shown because too many files have changed in this diff Show More