ImageOps.py 22 KB

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