ImageOps.py 22 KB

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