ImageOps.py 18 KB

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