ImageOps.py 24 KB

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