ImageOps.py 18 KB

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