Pillow/selftest.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

174 lines
4.7 KiB
Python
Raw Normal View History

2021-04-09 12:10:36 +03:00
#!/usr/bin/env python3
2010-07-31 06:52:47 +04:00
# minimal sanity check
from __future__ import annotations
import sys
from PIL import Image, features
2010-07-31 06:52:47 +04:00
try:
Image.core.ping
except ImportError as v:
print("***", v)
2010-07-31 06:52:47 +04:00
sys.exit()
except AttributeError:
pass
2023-12-26 14:26:11 +03:00
def testimage() -> None:
2010-07-31 06:52:47 +04:00
"""
PIL lets you create in-memory images with various pixel types:
2018-10-18 19:46:20 +03:00
>>> from PIL import Image, ImageDraw, ImageFilter, ImageMath
2010-07-31 06:52:47 +04:00
>>> im = Image.new("1", (128, 128)) # monochrome
2022-04-10 19:25:40 +03:00
>>> def _info(im): return im.format, im.mode, im.size
2010-07-31 06:52:47 +04:00
>>> _info(im)
(None, '1', (128, 128))
>>> _info(Image.new("L", (128, 128))) # grayscale (luminance)
(None, 'L', (128, 128))
>>> _info(Image.new("P", (128, 128))) # palette
(None, 'P', (128, 128))
>>> _info(Image.new("RGB", (128, 128))) # truecolor
(None, 'RGB', (128, 128))
>>> _info(Image.new("I", (128, 128))) # 32-bit integer
(None, 'I', (128, 128))
>>> _info(Image.new("F", (128, 128))) # 32-bit floating point
(None, 'F', (128, 128))
Or open existing files:
Improve handling of file resources Follow Python's file object semantics. User code is responsible for closing resources (usually through a context manager) in a deterministic way. To achieve this, remove __del__ functions. These functions used to closed open file handlers in an attempt to silence Python ResourceWarnings. However, using __del__ has the following drawbacks: - __del__ isn't called until the object's reference count reaches 0. Therefore, resource handlers remain open or in use longer than necessary. - The __del__ method isn't guaranteed to execute on system exit. See the Python documentation: https://docs.python.org/3/reference/datamodel.html#object.__del__ > It is not guaranteed that __del__() methods are called for objects > that still exist when the interpreter exits. - Exceptions that occur inside __del__ are ignored instead of raised. This has the potential of hiding bugs. This is also in the Python documentation: > Warning: Due to the precarious circumstances under which __del__() > methods are invoked, exceptions that occur during their execution > are ignored, and a warning is printed to sys.stderr instead. Instead, always close resource handlers when they are no longer in use. This will close the file handler at a specified point in the user's code and not wait until the interpreter chooses to. It is always guaranteed to run. And, if an exception occurs while closing the file handler, the bug will not be ignored. Now, when code receives a ResourceWarning, it will highlight an area that is mishandling resources. It should not simply be silenced, but fixed by closing resources with a context manager. All warnings that were emitted during tests have been cleaned up. To enable warnings, I passed the `-Wa` CLI option to Python. This exposed some mishandling of resources in ImageFile.__init__() and SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
>>> with Image.open("Tests/images/hopper.gif") as im:
... _info(im)
2010-07-31 06:52:47 +04:00
('GIF', 'P', (128, 128))
2016-03-29 14:53:48 +03:00
>>> _info(Image.open("Tests/images/hopper.ppm"))
2010-07-31 06:52:47 +04:00
('PPM', 'RGB', (128, 128))
>>> try:
2016-03-29 14:53:48 +03:00
... _info(Image.open("Tests/images/hopper.jpg"))
... except OSError as v:
... print(v)
2010-07-31 06:52:47 +04:00
('JPEG', 'RGB', (128, 128))
PIL doesn't actually load the image data until it's needed,
or you call the "load" method:
2016-03-29 14:53:48 +03:00
>>> im = Image.open("Tests/images/hopper.ppm")
2024-08-10 03:20:08 +03:00
>>> print(im._im) # internal image attribute
2010-07-31 06:52:47 +04:00
None
>>> a = im.load()
>>> type(im.im) # doctest: +ELLIPSIS
<... '...ImagingCore'>
2010-07-31 06:52:47 +04:00
You can apply many different operations on images. Most
operations return a new image:
2016-03-29 14:53:48 +03:00
>>> im = Image.open("Tests/images/hopper.ppm")
2010-07-31 06:52:47 +04:00
>>> _info(im.convert("L"))
(None, 'L', (128, 128))
>>> _info(im.copy())
(None, 'RGB', (128, 128))
>>> _info(im.crop((32, 32, 96, 96)))
(None, 'RGB', (64, 64))
>>> _info(im.filter(ImageFilter.BLUR))
(None, 'RGB', (128, 128))
>>> im.getbands()
('R', 'G', 'B')
>>> im.getbbox()
(0, 0, 128, 128)
>>> len(im.getdata())
16384
>>> im.getextrema()
2014-09-04 10:50:47 +04:00
((0, 255), (0, 255), (0, 255))
2010-07-31 06:52:47 +04:00
>>> im.getpixel((0, 0))
2014-09-04 10:50:47 +04:00
(20, 20, 70)
2010-07-31 06:52:47 +04:00
>>> len(im.getprojection())
2
>>> len(im.histogram())
768
Added an `image.entropy()` method This calculates the entropy for the image, based on the histogram. Because this uses image histogram data directly, the existing C function underpinning the `image.histogram()` method was abstracted into a static function to parse extrema tuple arguments, and a new C function was added to calculate image entropy, making use of the new static extrema function. The extrema-parsing function was written by @homm, based on the macro abstraction I wrote, during the discussion of my first entropy-method pull request: https://git.io/fhodS The new `image.entropy()` method is based on `image.histogram()`, and will accept the same arguments to calculate the histogram data it will use to assess the entropy of the image. The algorithm and methodology is based on existing Python code: * https://git.io/fhmIU ... A test case in the `Tests/` directory, and doctest lines in `selftest.py`, have both been added and checked. Changes proposed in this pull request: * Added “math.h” include to _imaging.c * The addition of an `image.entropy()` method to the `Image` Python class, * The abstraction of the extrema-parsing logic of of the C function `_histogram` into a static function, and * The use of that static function in both the `_histogram` and `_entropy` C functions. * Minor documentation addenda in the docstrings for both the `image.entropy()` and `image.histogram()` methods were also added. * Removed outdated boilerplate from testing code * Removed unused “unittest” import
2019-01-25 20:38:11 +03:00
>>> '%.7f' % im.entropy()
'8.8212866'
>>> _info(im.point(list(range(256))*3))
2010-07-31 06:52:47 +04:00
(None, 'RGB', (128, 128))
>>> _info(im.resize((64, 64)))
(None, 'RGB', (64, 64))
>>> _info(im.rotate(45))
(None, 'RGB', (128, 128))
>>> [_info(ch) for ch in im.split()]
2010-07-31 06:52:47 +04:00
[(None, 'L', (128, 128)), (None, 'L', (128, 128)), (None, 'L', (128, 128))]
>>> len(im.convert("1").tobitmap())
10456
>>> len(im.tobytes())
2010-07-31 06:52:47 +04:00
49152
2022-01-15 01:02:31 +03:00
>>> _info(im.transform((512, 512), Image.Transform.AFFINE, (1,0,0,0,1,0)))
2010-07-31 06:52:47 +04:00
(None, 'RGB', (512, 512))
2022-01-15 01:02:31 +03:00
>>> _info(im.transform((512, 512), Image.Transform.EXTENT, (32,32,96,96)))
2010-07-31 06:52:47 +04:00
(None, 'RGB', (512, 512))
The ImageDraw module lets you draw stuff in raster images:
>>> im = Image.new("L", (128, 128), 64)
>>> d = ImageDraw.ImageDraw(im)
>>> d.line((0, 0, 128, 128), fill=128)
>>> d.line((0, 128, 128, 0), fill=128)
>>> im.getextrema()
(64, 128)
In 1.1.4, you can specify colors in a number of ways:
>>> xy = 0, 0, 128, 128
>>> im = Image.new("RGB", (128, 128), 0)
>>> d = ImageDraw.ImageDraw(im)
>>> d.rectangle(xy, "#f00")
>>> im.getpixel((0, 0))
(255, 0, 0)
>>> d.rectangle(xy, "#ff0000")
>>> im.getpixel((0, 0))
(255, 0, 0)
>>> d.rectangle(xy, "rgb(255,0,0)")
>>> im.getpixel((0, 0))
(255, 0, 0)
>>> d.rectangle(xy, "rgb(100%,0%,0%)")
>>> im.getpixel((0, 0))
(255, 0, 0)
>>> d.rectangle(xy, "hsl(0, 100%, 50%)")
>>> im.getpixel((0, 0))
(255, 0, 0)
>>> d.rectangle(xy, "red")
>>> im.getpixel((0, 0))
(255, 0, 0)
In 1.1.6, you can use the ImageMath module to do image
calculations.
>>> im = ImageMath.lambda_eval( \
lambda args: args["float"](args["im"] + 20), im=im.convert("L") \
)
2010-07-31 06:52:47 +04:00
>>> im.mode, im.size
('F', (128, 128))
PIL can do many other things, but I'll leave that for another
2021-01-10 00:26:45 +03:00
day.
2010-07-31 06:52:47 +04:00
Cheers /F
"""
if __name__ == "__main__":
# check build sanity
exit_status = 0
features.pilinfo(sys.stdout, False)
2010-07-31 06:52:47 +04:00
# use doctest to make sure the test program behaves as documented!
import doctest
2019-06-13 18:54:57 +03:00
print("Running selftest:")
status = doctest.testmod(sys.modules[__name__])
2010-07-31 06:52:47 +04:00
if status[0]:
2024-05-07 07:01:08 +03:00
print(f"*** {status[0]} tests of {status[1]} failed.")
2010-07-31 06:52:47 +04:00
exit_status = 1
else:
2024-05-07 07:01:08 +03:00
print(f"--- {status[1]} tests passed.")
2010-07-31 06:52:47 +04:00
sys.exit(exit_status)