ImageOps.py 20 KB

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