Pillow

Форк
0
/
selftest.py 
173 строки · 4.7 Кб
1
#!/usr/bin/env python3
2
# minimal sanity check
3
from __future__ import annotations
4

5
import sys
6

7
from PIL import Image, features
8

9
try:
10
    Image.core.ping
11
except ImportError as v:
12
    print("***", v)
13
    sys.exit()
14
except AttributeError:
15
    pass
16

17

18
def testimage() -> None:
19
    """
20
    PIL lets you create in-memory images with various pixel types:
21

22
    >>> from PIL import Image, ImageDraw, ImageFilter, ImageMath
23
    >>> im = Image.new("1", (128, 128)) # monochrome
24
    >>> def _info(im): return im.format, im.mode, im.size
25
    >>> _info(im)
26
    (None, '1', (128, 128))
27
    >>> _info(Image.new("L", (128, 128))) # grayscale (luminance)
28
    (None, 'L', (128, 128))
29
    >>> _info(Image.new("P", (128, 128))) # palette
30
    (None, 'P', (128, 128))
31
    >>> _info(Image.new("RGB", (128, 128))) # truecolor
32
    (None, 'RGB', (128, 128))
33
    >>> _info(Image.new("I", (128, 128))) # 32-bit integer
34
    (None, 'I', (128, 128))
35
    >>> _info(Image.new("F", (128, 128))) # 32-bit floating point
36
    (None, 'F', (128, 128))
37

38
    Or open existing files:
39

40
    >>> with Image.open("Tests/images/hopper.gif") as im:
41
    ...     _info(im)
42
    ('GIF', 'P', (128, 128))
43
    >>> _info(Image.open("Tests/images/hopper.ppm"))
44
    ('PPM', 'RGB', (128, 128))
45
    >>> try:
46
    ...  _info(Image.open("Tests/images/hopper.jpg"))
47
    ... except OSError as v:
48
    ...  print(v)
49
    ('JPEG', 'RGB', (128, 128))
50

51
    PIL doesn't actually load the image data until it's needed,
52
    or you call the "load" method:
53

54
    >>> im = Image.open("Tests/images/hopper.ppm")
55
    >>> print(im._im) # internal image attribute
56
    None
57
    >>> a = im.load()
58
    >>> type(im.im) # doctest: +ELLIPSIS
59
    <... '...ImagingCore'>
60

61
    You can apply many different operations on images.  Most
62
    operations return a new image:
63

64
    >>> im = Image.open("Tests/images/hopper.ppm")
65
    >>> _info(im.convert("L"))
66
    (None, 'L', (128, 128))
67
    >>> _info(im.copy())
68
    (None, 'RGB', (128, 128))
69
    >>> _info(im.crop((32, 32, 96, 96)))
70
    (None, 'RGB', (64, 64))
71
    >>> _info(im.filter(ImageFilter.BLUR))
72
    (None, 'RGB', (128, 128))
73
    >>> im.getbands()
74
    ('R', 'G', 'B')
75
    >>> im.getbbox()
76
    (0, 0, 128, 128)
77
    >>> len(im.getdata())
78
    16384
79
    >>> im.getextrema()
80
    ((0, 255), (0, 255), (0, 255))
81
    >>> im.getpixel((0, 0))
82
    (20, 20, 70)
83
    >>> len(im.getprojection())
84
    2
85
    >>> len(im.histogram())
86
    768
87
    >>> '%.7f' % im.entropy()
88
    '8.8212866'
89
    >>> _info(im.point(list(range(256))*3))
90
    (None, 'RGB', (128, 128))
91
    >>> _info(im.resize((64, 64)))
92
    (None, 'RGB', (64, 64))
93
    >>> _info(im.rotate(45))
94
    (None, 'RGB', (128, 128))
95
    >>> [_info(ch) for ch in im.split()]
96
    [(None, 'L', (128, 128)), (None, 'L', (128, 128)), (None, 'L', (128, 128))]
97
    >>> len(im.convert("1").tobitmap())
98
    10456
99
    >>> len(im.tobytes())
100
    49152
101
    >>> _info(im.transform((512, 512), Image.Transform.AFFINE, (1,0,0,0,1,0)))
102
    (None, 'RGB', (512, 512))
103
    >>> _info(im.transform((512, 512), Image.Transform.EXTENT, (32,32,96,96)))
104
    (None, 'RGB', (512, 512))
105

106
    The ImageDraw module lets you draw stuff in raster images:
107

108
    >>> im = Image.new("L", (128, 128), 64)
109
    >>> d = ImageDraw.ImageDraw(im)
110
    >>> d.line((0, 0, 128, 128), fill=128)
111
    >>> d.line((0, 128, 128, 0), fill=128)
112
    >>> im.getextrema()
113
    (64, 128)
114

115
    In 1.1.4, you can specify colors in a number of ways:
116

117
    >>> xy = 0, 0, 128, 128
118
    >>> im = Image.new("RGB", (128, 128), 0)
119
    >>> d = ImageDraw.ImageDraw(im)
120
    >>> d.rectangle(xy, "#f00")
121
    >>> im.getpixel((0, 0))
122
    (255, 0, 0)
123
    >>> d.rectangle(xy, "#ff0000")
124
    >>> im.getpixel((0, 0))
125
    (255, 0, 0)
126
    >>> d.rectangle(xy, "rgb(255,0,0)")
127
    >>> im.getpixel((0, 0))
128
    (255, 0, 0)
129
    >>> d.rectangle(xy, "rgb(100%,0%,0%)")
130
    >>> im.getpixel((0, 0))
131
    (255, 0, 0)
132
    >>> d.rectangle(xy, "hsl(0, 100%, 50%)")
133
    >>> im.getpixel((0, 0))
134
    (255, 0, 0)
135
    >>> d.rectangle(xy, "red")
136
    >>> im.getpixel((0, 0))
137
    (255, 0, 0)
138

139
    In 1.1.6, you can use the ImageMath module to do image
140
    calculations.
141

142
    >>> im = ImageMath.lambda_eval( \
143
      lambda args: args["float"](args["im"] + 20), im=im.convert("L") \
144
    )
145
    >>> im.mode, im.size
146
    ('F', (128, 128))
147

148
    PIL can do many other things, but I'll leave that for another
149
    day.
150

151
    Cheers /F
152
    """
153

154

155
if __name__ == "__main__":
156
    # check build sanity
157

158
    exit_status = 0
159

160
    features.pilinfo(sys.stdout, False)
161

162
    # use doctest to make sure the test program behaves as documented!
163
    import doctest
164

165
    print("Running selftest:")
166
    status = doctest.testmod(sys.modules[__name__])
167
    if status[0]:
168
        print(f"*** {status[0]} tests of {status[1]} failed.")
169
        exit_status = 1
170
    else:
171
        print(f"--- {status[1]} tests passed.")
172

173
    sys.exit(exit_status)
174

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.