You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

632 lines
20 KiB

4 years ago
  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 . import Image
  20. from ._util import isStringType
  21. import operator
  22. import functools
  23. import warnings
  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 isStringType(color):
  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. raise NotImplementedError("mode P support coming soon")
  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. raise IOError("not supported for this image mode")
  50. #
  51. # actions
  52. def autocontrast(image, cutoff=0, ignore=None):
  53. """
  54. Maximize (normalize) image contrast. This function calculates a
  55. histogram of the input image, removes **cutoff** percent of the
  56. lightest and darkest pixels from the histogram, and remaps the image
  57. so that the darkest pixel becomes black (0), and the lightest
  58. becomes white (255).
  59. :param image: The image to process.
  60. :param cutoff: How many percent to cut off from the histogram.
  61. :param ignore: The background pixel value (use None for no background).
  62. :return: An image.
  63. """
  64. histogram = image.histogram()
  65. lut = []
  66. for layer in range(0, len(histogram), 256):
  67. h = histogram[layer:layer+256]
  68. if ignore is not None:
  69. # get rid of outliers
  70. try:
  71. h[ignore] = 0
  72. except TypeError:
  73. # assume sequence
  74. for ix in ignore:
  75. h[ix] = 0
  76. if cutoff:
  77. # cut off pixels from both ends of the histogram
  78. # get number of pixels
  79. n = 0
  80. for ix in range(256):
  81. n = n + h[ix]
  82. # remove cutoff% pixels from the low end
  83. cut = n * cutoff // 100
  84. for lo in range(256):
  85. if cut > h[lo]:
  86. cut = cut - h[lo]
  87. h[lo] = 0
  88. else:
  89. h[lo] -= cut
  90. cut = 0
  91. if cut <= 0:
  92. break
  93. # remove cutoff% samples from the hi end
  94. cut = n * cutoff // 100
  95. for hi in range(255, -1, -1):
  96. if cut > h[hi]:
  97. cut = cut - h[hi]
  98. h[hi] = 0
  99. else:
  100. h[hi] -= cut
  101. cut = 0
  102. if cut <= 0:
  103. break
  104. # find lowest/highest samples after preprocessing
  105. for lo in range(256):
  106. if h[lo]:
  107. break
  108. for hi in range(255, -1, -1):
  109. if h[hi]:
  110. break
  111. if hi <= lo:
  112. # don't bother
  113. lut.extend(list(range(256)))
  114. else:
  115. scale = 255.0 / (hi - lo)
  116. offset = -lo * scale
  117. for ix in range(256):
  118. ix = int(ix * scale + offset)
  119. if ix < 0:
  120. ix = 0
  121. elif ix > 255:
  122. ix = 255
  123. lut.append(ix)
  124. return _lut(image, lut)
  125. def colorize(image, black, white, mid=None, blackpoint=0,
  126. whitepoint=255, midpoint=127):
  127. """
  128. Colorize grayscale image.
  129. This function calculates a color wedge which maps all black pixels in
  130. the source image to the first color and all white pixels to the
  131. second color. If **mid** is specified, it uses three-color mapping.
  132. The **black** and **white** arguments should be RGB tuples or color names;
  133. optionally you can use three-color mapping by also specifying **mid**.
  134. Mapping positions for any of the colors can be specified
  135. (e.g. **blackpoint**), where these parameters are the integer
  136. value corresponding to where the corresponding color should be mapped.
  137. These parameters must have logical order, such that
  138. **blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).
  139. :param image: The image to colorize.
  140. :param black: The color to use for black input pixels.
  141. :param white: The color to use for white input pixels.
  142. :param mid: The color to use for midtone input pixels.
  143. :param blackpoint: an int value [0, 255] for the black mapping.
  144. :param whitepoint: an int value [0, 255] for the white mapping.
  145. :param midpoint: an int value [0, 255] for the midtone mapping.
  146. :return: An image.
  147. """
  148. # Initial asserts
  149. assert image.mode == "L"
  150. if mid is None:
  151. assert 0 <= blackpoint <= whitepoint <= 255
  152. else:
  153. assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
  154. # Define colors from arguments
  155. black = _color(black, "RGB")
  156. white = _color(white, "RGB")
  157. if mid is not None:
  158. mid = _color(mid, "RGB")
  159. # Empty lists for the mapping
  160. red = []
  161. green = []
  162. blue = []
  163. # Create the low-end values
  164. for i in range(0, blackpoint):
  165. red.append(black[0])
  166. green.append(black[1])
  167. blue.append(black[2])
  168. # Create the mapping (2-color)
  169. if mid is None:
  170. range_map = range(0, whitepoint - blackpoint)
  171. for i in range_map:
  172. red.append(black[0] + i * (white[0] - black[0]) // len(range_map))
  173. green.append(black[1] + i * (white[1] - black[1]) // len(range_map))
  174. blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))
  175. # Create the mapping (3-color)
  176. else:
  177. range_map1 = range(0, midpoint - blackpoint)
  178. range_map2 = range(0, whitepoint - midpoint)
  179. for i in range_map1:
  180. red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))
  181. green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))
  182. blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))
  183. for i in range_map2:
  184. red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))
  185. green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))
  186. blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))
  187. # Create the high-end values
  188. for i in range(0, 256 - whitepoint):
  189. red.append(white[0])
  190. green.append(white[1])
  191. blue.append(white[2])
  192. # Return converted image
  193. image = image.convert("RGB")
  194. return _lut(image, red + green + blue)
  195. def pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):
  196. """
  197. Returns a sized and padded version of the image, expanded to fill the
  198. requested aspect ratio and size.
  199. :param image: The image to size and crop.
  200. :param size: The requested output size in pixels, given as a
  201. (width, height) tuple.
  202. :param method: What resampling method to use. Default is
  203. :py:attr:`PIL.Image.NEAREST`.
  204. :param color: The background color of the padded image.
  205. :param centering: Control the position of the original image within the
  206. padded version.
  207. (0.5, 0.5) will keep the image centered
  208. (0, 0) will keep the image aligned to the top left
  209. (1, 1) will keep the image aligned to the bottom
  210. right
  211. :return: An image.
  212. """
  213. im_ratio = image.width / image.height
  214. dest_ratio = float(size[0]) / size[1]
  215. if im_ratio == dest_ratio:
  216. out = image.resize(size, resample=method)
  217. else:
  218. out = Image.new(image.mode, size, color)
  219. if im_ratio > dest_ratio:
  220. new_height = int(image.height / image.width * size[0])
  221. if new_height != size[1]:
  222. image = image.resize((size[0], new_height), resample=method)
  223. y = int((size[1] - new_height) * max(0, min(centering[1], 1)))
  224. out.paste(image, (0, y))
  225. else:
  226. new_width = int(image.width / image.height * size[1])
  227. if new_width != size[0]:
  228. image = image.resize((new_width, size[1]), resample=method)
  229. x = int((size[0] - new_width) * max(0, min(centering[0], 1)))
  230. out.paste(image, (x, 0))
  231. return out
  232. def crop(image, border=0):
  233. """
  234. Remove border from image. The same amount of pixels are removed
  235. from all four sides. This function works on all image modes.
  236. .. seealso:: :py:meth:`~PIL.Image.Image.crop`
  237. :param image: The image to crop.
  238. :param border: The number of pixels to remove.
  239. :return: An image.
  240. """
  241. left, top, right, bottom = _border(border)
  242. return image.crop(
  243. (left, top, image.size[0]-right, image.size[1]-bottom)
  244. )
  245. def scale(image, factor, resample=Image.NEAREST):
  246. """
  247. Returns a rescaled image by a specific factor given in parameter.
  248. A factor greater than 1 expands the image, between 0 and 1 contracts the
  249. image.
  250. :param image: The image to rescale.
  251. :param factor: The expansion factor, as a float.
  252. :param resample: An optional resampling filter. Same values possible as
  253. in the PIL.Image.resize function.
  254. :returns: An :py:class:`~PIL.Image.Image` object.
  255. """
  256. if factor == 1:
  257. return image.copy()
  258. elif factor <= 0:
  259. raise ValueError("the factor must be greater than 0")
  260. else:
  261. size = (int(round(factor * image.width)),
  262. int(round(factor * image.height)))
  263. return image.resize(size, resample)
  264. def deform(image, deformer, resample=Image.BILINEAR):
  265. """
  266. Deform the image.
  267. :param image: The image to deform.
  268. :param deformer: A deformer object. Any object that implements a
  269. **getmesh** method can be used.
  270. :param resample: An optional resampling filter. Same values possible as
  271. in the PIL.Image.transform function.
  272. :return: An image.
  273. """
  274. return image.transform(
  275. image.size, Image.MESH, deformer.getmesh(image), resample
  276. )
  277. def equalize(image, mask=None):
  278. """
  279. Equalize the image histogram. This function applies a non-linear
  280. mapping to the input image, in order to create a uniform
  281. distribution of grayscale values in the output image.
  282. :param image: The image to equalize.
  283. :param mask: An optional mask. If given, only the pixels selected by
  284. the mask are included in the analysis.
  285. :return: An image.
  286. """
  287. if image.mode == "P":
  288. image = image.convert("RGB")
  289. h = image.histogram(mask)
  290. lut = []
  291. for b in range(0, len(h), 256):
  292. histo = [_f for _f in h[b:b+256] if _f]
  293. if len(histo) <= 1:
  294. lut.extend(list(range(256)))
  295. else:
  296. step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
  297. if not step:
  298. lut.extend(list(range(256)))
  299. else:
  300. n = step // 2
  301. for i in range(256):
  302. lut.append(n // step)
  303. n = n + h[i+b]
  304. return _lut(image, lut)
  305. def expand(image, border=0, fill=0):
  306. """
  307. Add border to the image
  308. :param image: The image to expand.
  309. :param border: Border width, in pixels.
  310. :param fill: Pixel fill value (a color value). Default is 0 (black).
  311. :return: An image.
  312. """
  313. left, top, right, bottom = _border(border)
  314. width = left + image.size[0] + right
  315. height = top + image.size[1] + bottom
  316. out = Image.new(image.mode, (width, height), _color(fill, image.mode))
  317. out.paste(image, (left, top))
  318. return out
  319. def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
  320. """
  321. Returns a sized and cropped version of the image, cropped to the
  322. requested aspect ratio and size.
  323. This function was contributed by Kevin Cazabon.
  324. :param image: The image to size and crop.
  325. :param size: The requested output size in pixels, given as a
  326. (width, height) tuple.
  327. :param method: What resampling method to use. Default is
  328. :py:attr:`PIL.Image.NEAREST`.
  329. :param bleed: Remove a border around the outside of the image (from all
  330. four edges. The value is a decimal percentage (use 0.01 for
  331. one percent). The default value is 0 (no border).
  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 inputs are valid
  348. if not isinstance(centering, list):
  349. centering = [centering[0], centering[1]]
  350. if centering[0] > 1.0 or centering[0] < 0.0:
  351. centering[0] = 0.50
  352. if centering[1] > 1.0 or centering[1] < 0.0:
  353. centering[1] = 0.50
  354. if bleed > 0.49999 or bleed < 0.0:
  355. bleed = 0.0
  356. # calculate the area to use for resizing and cropping, subtracting
  357. # the 'bleed' around the edges
  358. # number of pixels to trim off on Top and Bottom, Left and Right
  359. bleedPixels = (
  360. int((float(bleed) * float(image.size[0])) + 0.5),
  361. int((float(bleed) * float(image.size[1])) + 0.5)
  362. )
  363. liveArea = (0, 0, image.size[0], image.size[1])
  364. if bleed > 0.0:
  365. liveArea = (
  366. bleedPixels[0], bleedPixels[1], image.size[0] - bleedPixels[0] - 1,
  367. image.size[1] - bleedPixels[1] - 1
  368. )
  369. liveSize = (liveArea[2] - liveArea[0], liveArea[3] - liveArea[1])
  370. # calculate the aspect ratio of the liveArea
  371. liveAreaAspectRatio = float(liveSize[0])/float(liveSize[1])
  372. # calculate the aspect ratio of the output image
  373. aspectRatio = float(size[0]) / float(size[1])
  374. # figure out if the sides or top/bottom will be cropped off
  375. if liveAreaAspectRatio >= aspectRatio:
  376. # liveArea is wider than what's needed, crop the sides
  377. cropWidth = int((aspectRatio * float(liveSize[1])) + 0.5)
  378. cropHeight = liveSize[1]
  379. else:
  380. # liveArea is taller than what's needed, crop the top and bottom
  381. cropWidth = liveSize[0]
  382. cropHeight = int((float(liveSize[0])/aspectRatio) + 0.5)
  383. # make the crop
  384. leftSide = int(liveArea[0] + (float(liveSize[0]-cropWidth) * centering[0]))
  385. if leftSide < 0:
  386. leftSide = 0
  387. topSide = int(liveArea[1] + (float(liveSize[1]-cropHeight) * centering[1]))
  388. if topSide < 0:
  389. topSide = 0
  390. out = image.crop(
  391. (leftSide, topSide, leftSide + cropWidth, topSide + cropHeight)
  392. )
  393. # resize the image and return it
  394. return out.resize(size, method)
  395. def flip(image):
  396. """
  397. Flip the image vertically (top to bottom).
  398. :param image: The image to flip.
  399. :return: An image.
  400. """
  401. return image.transpose(Image.FLIP_TOP_BOTTOM)
  402. def grayscale(image):
  403. """
  404. Convert the image to grayscale.
  405. :param image: The image to convert.
  406. :return: An image.
  407. """
  408. return image.convert("L")
  409. def invert(image):
  410. """
  411. Invert (negate) the image.
  412. :param image: The image to invert.
  413. :return: An image.
  414. """
  415. lut = []
  416. for i in range(256):
  417. lut.append(255-i)
  418. return _lut(image, lut)
  419. def mirror(image):
  420. """
  421. Flip image horizontally (left to right).
  422. :param image: The image to mirror.
  423. :return: An image.
  424. """
  425. return image.transpose(Image.FLIP_LEFT_RIGHT)
  426. def posterize(image, bits):
  427. """
  428. Reduce the number of bits for each color channel.
  429. :param image: The image to posterize.
  430. :param bits: The number of bits to keep for each channel (1-8).
  431. :return: An image.
  432. """
  433. lut = []
  434. mask = ~(2**(8-bits)-1)
  435. for i in range(256):
  436. lut.append(i & mask)
  437. return _lut(image, lut)
  438. def solarize(image, threshold=128):
  439. """
  440. Invert all pixel values above a threshold.
  441. :param image: The image to solarize.
  442. :param threshold: All pixels above this greyscale level are inverted.
  443. :return: An image.
  444. """
  445. lut = []
  446. for i in range(256):
  447. if i < threshold:
  448. lut.append(i)
  449. else:
  450. lut.append(255-i)
  451. return _lut(image, lut)
  452. # --------------------------------------------------------------------
  453. # PIL USM components, from Kevin Cazabon.
  454. def gaussian_blur(im, radius=None):
  455. """ PIL_usm.gblur(im, [radius])"""
  456. warnings.warn(
  457. 'PIL.ImageOps.gaussian_blur is deprecated. '
  458. 'Use PIL.ImageFilter.GaussianBlur instead. '
  459. 'This function will be removed in a future version.',
  460. DeprecationWarning
  461. )
  462. if radius is None:
  463. radius = 5.0
  464. im.load()
  465. return im.im.gaussian_blur(radius)
  466. def gblur(im, radius=None):
  467. """ PIL_usm.gblur(im, [radius])"""
  468. warnings.warn(
  469. 'PIL.ImageOps.gblur is deprecated. '
  470. 'Use PIL.ImageFilter.GaussianBlur instead. '
  471. 'This function will be removed in a future version.',
  472. DeprecationWarning
  473. )
  474. return gaussian_blur(im, radius)
  475. def unsharp_mask(im, radius=None, percent=None, threshold=None):
  476. """ PIL_usm.usm(im, [radius, percent, threshold])"""
  477. warnings.warn(
  478. 'PIL.ImageOps.unsharp_mask is deprecated. '
  479. 'Use PIL.ImageFilter.UnsharpMask instead. '
  480. 'This function will be removed in a future version.',
  481. DeprecationWarning
  482. )
  483. if radius is None:
  484. radius = 5.0
  485. if percent is None:
  486. percent = 150
  487. if threshold is None:
  488. threshold = 3
  489. im.load()
  490. return im.im.unsharp_mask(radius, percent, threshold)
  491. def usm(im, radius=None, percent=None, threshold=None):
  492. """ PIL_usm.usm(im, [radius, percent, threshold])"""
  493. warnings.warn(
  494. 'PIL.ImageOps.usm is deprecated. '
  495. 'Use PIL.ImageFilter.UnsharpMask instead. '
  496. 'This function will be removed in a future version.',
  497. DeprecationWarning
  498. )
  499. return unsharp_mask(im, radius, percent, threshold)
  500. def box_blur(image, radius):
  501. """
  502. Blur the image by setting each pixel to the average value of the pixels
  503. in a square box extending radius pixels in each direction.
  504. Supports float radius of arbitrary size. Uses an optimized implementation
  505. which runs in linear time relative to the size of the image
  506. for any radius value.
  507. :param image: The image to blur.
  508. :param radius: Size of the box in one direction. Radius 0 does not blur,
  509. returns an identical image. Radius 1 takes 1 pixel
  510. in each direction, i.e. 9 pixels in total.
  511. :return: An image.
  512. """
  513. warnings.warn(
  514. 'PIL.ImageOps.box_blur is deprecated. '
  515. 'Use PIL.ImageFilter.BoxBlur instead. '
  516. 'This function will be removed in a future version.',
  517. DeprecationWarning
  518. )
  519. image.load()
  520. return image._new(image.im.box_blur(radius))