ImageOps.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # standard image operations
  6. #
  7. # History:
  8. # 2001-10-20 fl Created
  9. # 2001-10-23 fl Added autocontrast operator
  10. # 2001-12-18 fl Added Kevin's fit operator
  11. # 2004-03-14 fl Fixed potential division by zero in equalize
  12. # 2005-05-05 fl Fixed equalize for low number of values
  13. #
  14. # Copyright (c) 2001-2004 by Secret Labs AB
  15. # Copyright (c) 2001-2004 by Fredrik Lundh
  16. #
  17. # See the README file for information on usage and redistribution.
  18. #
  19. from __future__ import annotations
  20. __lazy_modules__ = {"re"}
  21. import re
  22. from typing import Protocol, cast, overload
  23. from . import ExifTags, Image, ImagePalette
  24. TYPE_CHECKING = False
  25. if TYPE_CHECKING:
  26. from collections.abc import Sequence
  27. from typing import Literal
  28. #
  29. # helpers
  30. def _border(border: int | tuple[int, ...]) -> tuple[int, int, int, int]:
  31. if isinstance(border, tuple):
  32. if len(border) == 2:
  33. left, top = right, bottom = border
  34. elif len(border) == 4:
  35. left, top, right, bottom = border
  36. else:
  37. msg = "border must be an integer, or a tuple of two or four elements"
  38. raise ValueError(msg)
  39. else:
  40. left = top = right = bottom = border
  41. return left, top, right, bottom
  42. def _color(
  43. color: str | int | tuple[int, ...] | None, mode: str
  44. ) -> int | tuple[int, ...] | None:
  45. if isinstance(color, str):
  46. from . import ImageColor
  47. color = ImageColor.getcolor(color, mode)
  48. return color
  49. def _lut(image: Image.Image, lut: list[int], palette: bool = False) -> Image.Image:
  50. if image.mode == "P":
  51. if not palette:
  52. # The lookup table was built from the palette indexes, not colors
  53. msg = "mode P support coming soon"
  54. raise NotImplementedError(msg)
  55. # The lookup table can be applied to the palette colors
  56. im = image.copy()
  57. assert im.palette is not None
  58. palette_mode = im.palette.mode
  59. channels = len(palette_mode)
  60. colors = im.getpalette(None)
  61. assert colors is not None
  62. im.putpalette(
  63. [
  64. v if palette_mode[i % channels] == "A" else lut[v]
  65. for i, v in enumerate(colors)
  66. ],
  67. palette_mode,
  68. )
  69. return im
  70. elif image.mode in ("L", "RGB"):
  71. if image.mode == "RGB" and len(lut) == 256:
  72. lut = lut + lut + lut
  73. return image.point(lut)
  74. else:
  75. msg = f"not supported for mode {image.mode}"
  76. raise OSError(msg)
  77. #
  78. # actions
  79. def autocontrast(
  80. image: Image.Image,
  81. cutoff: float | tuple[float, float] = 0,
  82. ignore: int | Sequence[int] | None = None,
  83. mask: Image.Image | None = None,
  84. preserve_tone: bool = False,
  85. ) -> Image.Image:
  86. """
  87. Maximize (normalize) image contrast. This function calculates a
  88. histogram of the input image (or mask region), removes ``cutoff`` percent of the
  89. lightest and darkest pixels from the histogram, and remaps the image
  90. so that the darkest pixel becomes black (0), and the lightest
  91. becomes white (255).
  92. :param image: The image to process.
  93. :param cutoff: The percent to cut off from the histogram on the low and
  94. high ends. Either a tuple of (low, high), or a single
  95. number for both.
  96. :param ignore: The background pixel value (use None for no background).
  97. :param mask: Histogram used in contrast operation is computed using pixels
  98. within the mask. If no mask is given the entire image is used
  99. for histogram computation.
  100. :param preserve_tone: Preserve image tone in Photoshop-like style autocontrast.
  101. .. versionadded:: 8.2.0
  102. :return: An image.
  103. """
  104. if preserve_tone:
  105. histogram = image.convert("L").histogram(mask)
  106. else:
  107. histogram = image.histogram(mask)
  108. lut = []
  109. for layer in range(0, len(histogram), 256):
  110. h = histogram[layer : layer + 256]
  111. if ignore is not None:
  112. # get rid of outliers
  113. if isinstance(ignore, int):
  114. h[ignore] = 0
  115. else:
  116. for ix in ignore:
  117. h[ix] = 0
  118. if cutoff:
  119. # cut off pixels from both ends of the histogram
  120. if not isinstance(cutoff, tuple):
  121. cutoff = (cutoff, cutoff)
  122. # get number of pixels
  123. n = sum(h)
  124. # remove cutoff% pixels from the low end
  125. cut = int(n * cutoff[0] // 100)
  126. for lo in range(256):
  127. if cut > h[lo]:
  128. cut = cut - h[lo]
  129. h[lo] = 0
  130. else:
  131. h[lo] -= cut
  132. cut = 0
  133. if cut <= 0:
  134. break
  135. # remove cutoff% samples from the high end
  136. cut = int(n * cutoff[1] // 100)
  137. for hi in range(255, -1, -1):
  138. if cut > h[hi]:
  139. cut = cut - h[hi]
  140. h[hi] = 0
  141. else:
  142. h[hi] -= cut
  143. cut = 0
  144. if cut <= 0:
  145. break
  146. # find lowest/highest samples after preprocessing
  147. for lo in range(256):
  148. if h[lo]:
  149. break
  150. for hi in range(255, -1, -1):
  151. if h[hi]:
  152. break
  153. if hi <= lo:
  154. # don't bother
  155. lut.extend(list(range(256)))
  156. else:
  157. scale = 255.0 / (hi - lo)
  158. offset = -lo * scale
  159. for ix in range(256):
  160. ix = int(ix * scale + offset)
  161. if ix < 0:
  162. ix = 0
  163. elif ix > 255:
  164. ix = 255
  165. lut.append(ix)
  166. return _lut(image, lut)
  167. def colorize(
  168. image: Image.Image,
  169. black: str | tuple[int, ...],
  170. white: str | tuple[int, ...],
  171. mid: str | int | tuple[int, ...] | None = None,
  172. blackpoint: int = 0,
  173. whitepoint: int = 255,
  174. midpoint: int = 127,
  175. ) -> Image.Image:
  176. """
  177. Colorize grayscale image.
  178. This function calculates a color wedge which maps all black pixels in
  179. the source image to the first color and all white pixels to the
  180. second color. If ``mid`` is specified, it uses three-color mapping.
  181. The ``black`` and ``white`` arguments should be RGB tuples or color names;
  182. optionally you can use three-color mapping by also specifying ``mid``.
  183. Mapping positions for any of the colors can be specified
  184. (e.g. ``blackpoint``), where these parameters are the integer
  185. value corresponding to where the corresponding color should be mapped.
  186. These parameters must have logical order, such that
  187. ``blackpoint <= midpoint <= whitepoint`` (if ``mid`` is specified).
  188. :param image: The image to colorize.
  189. :param black: The color to use for black input pixels.
  190. :param white: The color to use for white input pixels.
  191. :param mid: The color to use for midtone input pixels.
  192. :param blackpoint: an int value [0, 255] for the black mapping.
  193. :param whitepoint: an int value [0, 255] for the white mapping.
  194. :param midpoint: an int value [0, 255] for the midtone mapping.
  195. :return: An image.
  196. """
  197. if image.mode != "L":
  198. msg = f"mode must be L, not {image.mode}"
  199. raise ValueError(msg)
  200. if not 0 <= blackpoint <= whitepoint <= 255:
  201. msg = (
  202. "blackpoint and whitepoint must each be between or equal to 0 and 255, "
  203. "with blackpoint less than or equal to whitepoint"
  204. )
  205. raise ValueError(msg)
  206. if mid is not None and not blackpoint <= midpoint <= whitepoint:
  207. msg = "midpoint must be between or equal to blackpoint and whitepoint"
  208. raise ValueError(msg)
  209. # Define colors from arguments
  210. rgb_black = cast("Sequence[int]", _color(black, "RGB"))
  211. rgb_white = cast("Sequence[int]", _color(white, "RGB"))
  212. rgb_mid = cast("Sequence[int]", _color(mid, "RGB")) if mid is not None else None
  213. # Empty lists for the mapping
  214. red = []
  215. green = []
  216. blue = []
  217. # Create the low-end values
  218. for i in range(blackpoint):
  219. red.append(rgb_black[0])
  220. green.append(rgb_black[1])
  221. blue.append(rgb_black[2])
  222. # Create the mapping (2-color)
  223. if rgb_mid is None:
  224. range_map = range(whitepoint - blackpoint)
  225. for i in range_map:
  226. red.append(
  227. rgb_black[0] + i * (rgb_white[0] - rgb_black[0]) // len(range_map)
  228. )
  229. green.append(
  230. rgb_black[1] + i * (rgb_white[1] - rgb_black[1]) // len(range_map)
  231. )
  232. blue.append(
  233. rgb_black[2] + i * (rgb_white[2] - rgb_black[2]) // len(range_map)
  234. )
  235. # Create the mapping (3-color)
  236. else:
  237. range_map1 = range(midpoint - blackpoint)
  238. range_map2 = range(whitepoint - midpoint)
  239. for i in range_map1:
  240. red.append(
  241. rgb_black[0] + i * (rgb_mid[0] - rgb_black[0]) // len(range_map1)
  242. )
  243. green.append(
  244. rgb_black[1] + i * (rgb_mid[1] - rgb_black[1]) // len(range_map1)
  245. )
  246. blue.append(
  247. rgb_black[2] + i * (rgb_mid[2] - rgb_black[2]) // len(range_map1)
  248. )
  249. for i in range_map2:
  250. red.append(rgb_mid[0] + i * (rgb_white[0] - rgb_mid[0]) // len(range_map2))
  251. green.append(
  252. rgb_mid[1] + i * (rgb_white[1] - rgb_mid[1]) // len(range_map2)
  253. )
  254. blue.append(rgb_mid[2] + i * (rgb_white[2] - rgb_mid[2]) // len(range_map2))
  255. # Create the high-end values
  256. for i in range(256 - whitepoint):
  257. red.append(rgb_white[0])
  258. green.append(rgb_white[1])
  259. blue.append(rgb_white[2])
  260. # Return converted image
  261. image = image.convert("RGB")
  262. return _lut(image, red + green + blue)
  263. def contain(
  264. image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
  265. ) -> Image.Image:
  266. """
  267. Returns a resized version of the image, set to the maximum width and height
  268. within the requested size, while maintaining the original aspect ratio.
  269. :param image: The image to resize.
  270. :param size: The requested output size in pixels, given as a
  271. (width, height) tuple.
  272. :param method: Resampling method to use. Default is
  273. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  274. See :ref:`concept-filters`.
  275. :return: An image.
  276. """
  277. if image.height == 0:
  278. return Image.new(image.mode, (size[0], 0))
  279. im_ratio = image.width / image.height
  280. if size[1] == 0:
  281. return Image.new(image.mode, (0, 0))
  282. dest_ratio = size[0] / size[1]
  283. if im_ratio != dest_ratio:
  284. if im_ratio > dest_ratio:
  285. new_height = round(image.height / image.width * size[0])
  286. if new_height != size[1]:
  287. size = (size[0], new_height)
  288. else:
  289. new_width = round(image.width / image.height * size[1])
  290. if new_width != size[0]:
  291. size = (new_width, size[1])
  292. if min(size) == 0:
  293. return Image.new(image.mode, size)
  294. return image.resize(size, resample=method)
  295. def cover(
  296. image: Image.Image, size: tuple[int, int], method: int = Image.Resampling.BICUBIC
  297. ) -> Image.Image:
  298. """
  299. Returns a resized version of the image, so that the requested size is
  300. covered, while maintaining the original aspect ratio.
  301. :param image: The image to resize.
  302. :param size: The requested output size in pixels, given as a
  303. (width, height) tuple.
  304. :param method: Resampling method to use. Default is
  305. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  306. See :ref:`concept-filters`.
  307. :return: An image.
  308. """
  309. if image.height == 0:
  310. return Image.new(image.mode, (size[0], 0))
  311. im_ratio = image.width / image.height
  312. if size[1] == 0:
  313. return Image.new(image.mode, (0, 0))
  314. dest_ratio = size[0] / size[1]
  315. if im_ratio != dest_ratio:
  316. if im_ratio < dest_ratio:
  317. new_height = round(image.height / image.width * size[0])
  318. if new_height != size[1]:
  319. size = (size[0], new_height)
  320. else:
  321. new_width = round(image.width / image.height * size[1])
  322. if new_width != size[0]:
  323. size = (new_width, size[1])
  324. return image.resize(size, resample=method)
  325. def _new_with_fill(
  326. image: Image.Image, size: tuple[int, int], fill: str | int | tuple[int, ...] | None
  327. ) -> Image.Image:
  328. color = _color(fill, image.mode)
  329. if image.palette:
  330. mode = image.palette.mode
  331. palette = ImagePalette.ImagePalette(mode, image.getpalette(mode))
  332. if isinstance(color, tuple) and len(color) in (3, 4):
  333. color = palette.getcolor(color, image)
  334. else:
  335. palette = None
  336. out = Image.new(image.mode, size, color)
  337. if palette:
  338. out.putpalette(palette.palette, mode)
  339. if "transparency" in image.info:
  340. out.info["transparency"] = image.info["transparency"]
  341. return out
  342. def pad(
  343. image: Image.Image,
  344. size: tuple[int, int],
  345. method: int = Image.Resampling.BICUBIC,
  346. color: str | int | tuple[int, ...] | None = None,
  347. centering: tuple[float, float] = (0.5, 0.5),
  348. ) -> Image.Image:
  349. """
  350. Returns a resized and padded version of the image, expanded to fill the
  351. requested aspect ratio and size.
  352. :param image: The image to resize and crop.
  353. :param size: The requested output size in pixels, given as a
  354. (width, height) tuple.
  355. :param method: Resampling method to use. Default is
  356. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  357. See :ref:`concept-filters`.
  358. :param color: The background color of the padded image.
  359. :param centering: Control the position of the original image within the
  360. padded version.
  361. (0.5, 0.5) will keep the image centered
  362. (0, 0) will keep the image aligned to the top left
  363. (1, 1) will keep the image aligned to the bottom
  364. right
  365. :return: An image.
  366. """
  367. resized = contain(image, size, method)
  368. if resized.size == size:
  369. out = resized
  370. else:
  371. out = _new_with_fill(resized, size, color)
  372. if resized.width != size[0]:
  373. x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
  374. out.paste(resized, (x, 0))
  375. else:
  376. y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
  377. out.paste(resized, (0, y))
  378. return out
  379. def crop(image: Image.Image, border: int | tuple[int, ...] = 0) -> Image.Image:
  380. """
  381. Remove border from image. This function works on all image modes.
  382. .. seealso:: :py:meth:`~PIL.Image.Image.crop`
  383. :param image: The image to crop.
  384. :param border: The number of pixels to remove. An integer removes the same
  385. number of pixels from all four sides. A 2-tuple specifies
  386. the number of pixels to remove horizontally and vertically.
  387. A 4-tuple specifies the number of pixels to remove from the
  388. left, top, right and bottom of the image.
  389. :return: An image.
  390. """
  391. left, top, right, bottom = _border(border)
  392. return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
  393. def scale(
  394. image: Image.Image, factor: float, resample: int = Image.Resampling.BICUBIC
  395. ) -> Image.Image:
  396. """
  397. Returns a rescaled image by a specific factor given in parameter.
  398. A factor greater than 1 expands the image, between 0 and 1 contracts the
  399. image.
  400. :param image: The image to rescale.
  401. :param factor: The expansion factor, as a float.
  402. :param resample: Resampling method to use. Default is
  403. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  404. See :ref:`concept-filters`.
  405. :returns: An :py:class:`~PIL.Image.Image` object.
  406. """
  407. if factor == 1:
  408. return image.copy()
  409. elif factor <= 0:
  410. msg = "the factor must be greater than 0"
  411. raise ValueError(msg)
  412. else:
  413. size = (round(factor * image.width), round(factor * image.height))
  414. return image.resize(size, resample)
  415. class SupportsGetMesh(Protocol):
  416. """
  417. An object that supports the ``getmesh`` method, taking an image as an
  418. argument, and returning a list of tuples. Each tuple contains two tuples,
  419. the source box as a tuple of 4 integers, and a tuple of 8 integers for the
  420. final quadrilateral, in order of top left, bottom left, bottom right, top
  421. right.
  422. """
  423. def getmesh(
  424. self, image: Image.Image
  425. ) -> list[
  426. tuple[tuple[int, int, int, int], tuple[int, int, int, int, int, int, int, int]]
  427. ]: ...
  428. def deform(
  429. image: Image.Image,
  430. deformer: SupportsGetMesh,
  431. resample: int = Image.Resampling.BILINEAR,
  432. ) -> Image.Image:
  433. """
  434. Deform the image.
  435. :param image: The image to deform.
  436. :param deformer: A deformer object. Any object that implements a
  437. ``getmesh`` method can be used.
  438. :param resample: An optional resampling filter. Same values possible as
  439. in the PIL.Image.transform function.
  440. :return: An image.
  441. """
  442. return image.transform(
  443. image.size, Image.Transform.MESH, deformer.getmesh(image), resample
  444. )
  445. def equalize(image: Image.Image, mask: Image.Image | None = None) -> Image.Image:
  446. """
  447. Equalize the image histogram. This function applies a non-linear
  448. mapping to the input image, in order to create a uniform
  449. distribution of grayscale values in the output image.
  450. :param image: The image to equalize.
  451. :param mask: An optional mask. If given, only the pixels selected by
  452. the mask are included in the analysis.
  453. :return: An image.
  454. """
  455. if image.mode == "P":
  456. image = image.convert("RGB")
  457. h = image.histogram(mask)
  458. lut = []
  459. for b in range(0, len(h), 256):
  460. histo = [_f for _f in h[b : b + 256] if _f]
  461. if len(histo) <= 1:
  462. lut.extend(list(range(256)))
  463. else:
  464. step = (sum(histo) - histo[-1]) // 255
  465. if not step:
  466. lut.extend(list(range(256)))
  467. else:
  468. n = step // 2
  469. for i in range(256):
  470. lut.append(n // step)
  471. n = n + h[i + b]
  472. return _lut(image, lut)
  473. def expand(
  474. image: Image.Image,
  475. border: int | tuple[int, ...] = 0,
  476. fill: str | int | tuple[int, ...] = 0,
  477. ) -> Image.Image:
  478. """
  479. Add border to the image
  480. :param image: The image to expand.
  481. :param border: Border width, in pixels. An integer adds the same width to
  482. all four sides. A 2-tuple specifies the horizontal and
  483. vertical border widths. A 4-tuple specifies the widths of
  484. the left, top, right and bottom borders.
  485. :param fill: Pixel fill value (a color value). Default is 0 (black).
  486. :return: An image.
  487. """
  488. left, top, right, bottom = _border(border)
  489. width = left + image.size[0] + right
  490. height = top + image.size[1] + bottom
  491. out = _new_with_fill(image, (width, height), fill)
  492. out.paste(image, (left, top))
  493. return out
  494. def fit(
  495. image: Image.Image,
  496. size: tuple[int, int],
  497. method: int = Image.Resampling.BICUBIC,
  498. bleed: float = 0.0,
  499. centering: tuple[float, float] = (0.5, 0.5),
  500. ) -> Image.Image:
  501. """
  502. Returns a resized and cropped version of the image, cropped to the
  503. requested aspect ratio and size.
  504. This function was contributed by Kevin Cazabon.
  505. :param image: The image to resize and crop.
  506. :param size: The requested output size in pixels, given as a
  507. (width, height) tuple.
  508. :param method: Resampling method to use. Default is
  509. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  510. See :ref:`concept-filters`.
  511. :param bleed: Remove a border around the outside of the image from all
  512. four edges. The value is a decimal percentage (use 0.01 for
  513. one percent). The default value is 0 (no border).
  514. Cannot be greater than or equal to 0.5.
  515. :param centering: Control the cropping position. Use (0.5, 0.5) for
  516. center cropping (e.g. if cropping the width, take 50% off
  517. of the left side, and therefore 50% off the right side).
  518. (0.0, 0.0) will crop from the top left corner (i.e. if
  519. cropping the width, take all of the crop off of the right
  520. side, and if cropping the height, take all of it off the
  521. bottom). (1.0, 1.0) will crop from the bottom right
  522. corner, etc. (i.e. if cropping the width, take all of the
  523. crop off the left side, and if cropping the height take
  524. none from the bottom, and therefore all off the top).
  525. :return: An image.
  526. """
  527. # by Kevin Cazabon, Feb 17/2000
  528. # kevin@cazabon.com
  529. # https://www.cazabon.com
  530. if min(size) == 0:
  531. return Image.new(image.mode, size)
  532. centering_x, centering_y = centering
  533. if not 0.0 <= centering_x <= 1.0:
  534. centering_x = 0.5
  535. if not 0.0 <= centering_y <= 1.0:
  536. centering_y = 0.5
  537. if not 0.0 <= bleed < 0.5:
  538. bleed = 0.0
  539. # calculate the area to use for resizing and cropping, subtracting
  540. # the 'bleed' around the edges
  541. # number of pixels to trim off on Top and Bottom, Left and Right
  542. bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
  543. live_size = (
  544. image.size[0] - bleed_pixels[0] * 2,
  545. image.size[1] - bleed_pixels[1] * 2,
  546. )
  547. # calculate the aspect ratio of the live_size
  548. if live_size[1] == 0:
  549. return Image.new(image.mode, size)
  550. live_size_ratio = live_size[0] / live_size[1]
  551. # calculate the aspect ratio of the output image
  552. output_ratio = size[0] / size[1]
  553. # figure out if the sides or top/bottom will be cropped off
  554. if live_size_ratio == output_ratio:
  555. # live_size is already the needed ratio
  556. crop_width = live_size[0]
  557. crop_height = live_size[1]
  558. elif live_size_ratio >= output_ratio:
  559. # live_size is wider than what's needed, crop the sides
  560. crop_width = output_ratio * live_size[1]
  561. crop_height = live_size[1]
  562. else:
  563. # live_size is taller than what's needed, crop the top and bottom
  564. crop_width = live_size[0]
  565. crop_height = live_size[0] / output_ratio
  566. # make the crop
  567. crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering_x
  568. crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering_y
  569. crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
  570. # resize the image and return it
  571. return image.resize(size, method, box=crop)
  572. def flip(image: Image.Image) -> Image.Image:
  573. """
  574. Flip the image vertically (top to bottom).
  575. :param image: The image to flip.
  576. :return: An image.
  577. """
  578. return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
  579. def grayscale(image: Image.Image) -> Image.Image:
  580. """
  581. Convert the image to grayscale.
  582. :param image: The image to convert.
  583. :return: An image.
  584. """
  585. return image.convert("L")
  586. def invert(image: Image.Image) -> Image.Image:
  587. """
  588. Invert (negate) the image.
  589. :param image: The image to invert.
  590. :return: An image.
  591. """
  592. lut = list(range(255, -1, -1))
  593. return image.point(lut) if image.mode == "1" else _lut(image, lut, palette=True)
  594. def mirror(image: Image.Image) -> Image.Image:
  595. """
  596. Flip image horizontally (left to right).
  597. :param image: The image to mirror.
  598. :return: An image.
  599. """
  600. return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
  601. def posterize(image: Image.Image, bits: int) -> Image.Image:
  602. """
  603. Reduce the number of bits for each color channel.
  604. :param image: The image to posterize.
  605. :param bits: The number of bits to keep for each channel (1-8).
  606. :return: An image.
  607. """
  608. if not 1 <= bits <= 8:
  609. msg = "bits must be between or equal to 1 and 8"
  610. raise ValueError(msg)
  611. mask = ~(2 ** (8 - bits) - 1)
  612. lut = [i & mask for i in range(256)]
  613. return _lut(image, lut, palette=True)
  614. def solarize(image: Image.Image, threshold: int = 128) -> Image.Image:
  615. """
  616. Invert all pixel values above a threshold.
  617. :param image: The image to solarize.
  618. :param threshold: All pixels above this grayscale level are inverted.
  619. :return: An image.
  620. """
  621. lut = []
  622. for i in range(256):
  623. if i < threshold:
  624. lut.append(i)
  625. else:
  626. lut.append(255 - i)
  627. return _lut(image, lut, palette=True)
  628. @overload
  629. def exif_transpose(image: Image.Image, *, in_place: Literal[True]) -> None: ...
  630. @overload
  631. def exif_transpose(
  632. image: Image.Image, *, in_place: Literal[False] = False
  633. ) -> Image.Image: ...
  634. def exif_transpose(image: Image.Image, *, in_place: bool = False) -> Image.Image | None:
  635. """
  636. If an image has an EXIF Orientation tag, other than 1, transpose the image
  637. accordingly, and remove the orientation data.
  638. :param image: The image to transpose.
  639. :param in_place: Boolean. Keyword-only argument.
  640. If ``True``, the original image is modified in-place, and ``None`` is returned.
  641. If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
  642. with the transposition applied. If there is no transposition, a copy of the
  643. image will be returned.
  644. """
  645. image.load()
  646. image_exif = image.getexif()
  647. orientation = image_exif.get(ExifTags.Base.Orientation, 1)
  648. method = {
  649. 2: Image.Transpose.FLIP_LEFT_RIGHT,
  650. 3: Image.Transpose.ROTATE_180,
  651. 4: Image.Transpose.FLIP_TOP_BOTTOM,
  652. 5: Image.Transpose.TRANSPOSE,
  653. 6: Image.Transpose.ROTATE_270,
  654. 7: Image.Transpose.TRANSVERSE,
  655. 8: Image.Transpose.ROTATE_90,
  656. }.get(orientation)
  657. if method is not None:
  658. if in_place:
  659. image.im = image.im.transpose(method)
  660. image._size = image.im.size
  661. else:
  662. transposed_image = image.transpose(method)
  663. exif_image = image if in_place else transposed_image
  664. exif = exif_image.getexif()
  665. if ExifTags.Base.Orientation in exif:
  666. del exif[ExifTags.Base.Orientation]
  667. if "exif" in exif_image.info:
  668. exif_image.info["exif"] = exif.tobytes()
  669. elif "Raw profile type exif" in exif_image.info:
  670. data = exif.tobytes()
  671. exif_image.info["Raw profile type exif"] = (
  672. f"\nexif\n{len(data):8}\n{data.hex()}\n"
  673. )
  674. for key in ("XML:com.adobe.xmp", "xmp"):
  675. if key in exif_image.info:
  676. for pattern in (
  677. r'tiff:Orientation="([0-9])"',
  678. r"<tiff:Orientation>([0-9])</tiff:Orientation>",
  679. ):
  680. value = exif_image.info[key]
  681. exif_image.info[key] = (
  682. re.sub(pattern, "", value)
  683. if isinstance(value, str)
  684. else re.sub(pattern.encode(), b"", value)
  685. )
  686. if not in_place:
  687. return transposed_image
  688. elif not in_place:
  689. return image.copy()
  690. return None