Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

ImageOps.py 20KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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, 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 and crop.
  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 pad(image, size, method=Image.Resampling.BICUBIC, color=None, centering=(0.5, 0.5)):
  232. """
  233. Returns a resized and padded version of the image, expanded to fill the
  234. requested aspect ratio and size.
  235. :param image: The image to resize and crop.
  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. :param color: The background color of the padded image.
  242. :param centering: Control the position of the original image within the
  243. padded version.
  244. (0.5, 0.5) will keep the image centered
  245. (0, 0) will keep the image aligned to the top left
  246. (1, 1) will keep the image aligned to the bottom
  247. right
  248. :return: An image.
  249. """
  250. resized = contain(image, size, method)
  251. if resized.size == size:
  252. out = resized
  253. else:
  254. out = Image.new(image.mode, size, color)
  255. if resized.palette:
  256. out.putpalette(resized.getpalette())
  257. if resized.width != size[0]:
  258. x = round((size[0] - resized.width) * max(0, min(centering[0], 1)))
  259. out.paste(resized, (x, 0))
  260. else:
  261. y = round((size[1] - resized.height) * max(0, min(centering[1], 1)))
  262. out.paste(resized, (0, y))
  263. return out
  264. def crop(image, border=0):
  265. """
  266. Remove border from image. The same amount of pixels are removed
  267. from all four sides. This function works on all image modes.
  268. .. seealso:: :py:meth:`~PIL.Image.Image.crop`
  269. :param image: The image to crop.
  270. :param border: The number of pixels to remove.
  271. :return: An image.
  272. """
  273. left, top, right, bottom = _border(border)
  274. return image.crop((left, top, image.size[0] - right, image.size[1] - bottom))
  275. def scale(image, factor, resample=Image.Resampling.BICUBIC):
  276. """
  277. Returns a rescaled image by a specific factor given in parameter.
  278. A factor greater than 1 expands the image, between 0 and 1 contracts the
  279. image.
  280. :param image: The image to rescale.
  281. :param factor: The expansion factor, as a float.
  282. :param resample: Resampling method to use. Default is
  283. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  284. See :ref:`concept-filters`.
  285. :returns: An :py:class:`~PIL.Image.Image` object.
  286. """
  287. if factor == 1:
  288. return image.copy()
  289. elif factor <= 0:
  290. msg = "the factor must be greater than 0"
  291. raise ValueError(msg)
  292. else:
  293. size = (round(factor * image.width), round(factor * image.height))
  294. return image.resize(size, resample)
  295. def deform(image, deformer, resample=Image.Resampling.BILINEAR):
  296. """
  297. Deform the image.
  298. :param image: The image to deform.
  299. :param deformer: A deformer object. Any object that implements a
  300. ``getmesh`` method can be used.
  301. :param resample: An optional resampling filter. Same values possible as
  302. in the PIL.Image.transform function.
  303. :return: An image.
  304. """
  305. return image.transform(
  306. image.size, Image.Transform.MESH, deformer.getmesh(image), resample
  307. )
  308. def equalize(image, mask=None):
  309. """
  310. Equalize the image histogram. This function applies a non-linear
  311. mapping to the input image, in order to create a uniform
  312. distribution of grayscale values in the output image.
  313. :param image: The image to equalize.
  314. :param mask: An optional mask. If given, only the pixels selected by
  315. the mask are included in the analysis.
  316. :return: An image.
  317. """
  318. if image.mode == "P":
  319. image = image.convert("RGB")
  320. h = image.histogram(mask)
  321. lut = []
  322. for b in range(0, len(h), 256):
  323. histo = [_f for _f in h[b : b + 256] if _f]
  324. if len(histo) <= 1:
  325. lut.extend(list(range(256)))
  326. else:
  327. step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
  328. if not step:
  329. lut.extend(list(range(256)))
  330. else:
  331. n = step // 2
  332. for i in range(256):
  333. lut.append(n // step)
  334. n = n + h[i + b]
  335. return _lut(image, lut)
  336. def expand(image, border=0, fill=0):
  337. """
  338. Add border to the image
  339. :param image: The image to expand.
  340. :param border: Border width, in pixels.
  341. :param fill: Pixel fill value (a color value). Default is 0 (black).
  342. :return: An image.
  343. """
  344. left, top, right, bottom = _border(border)
  345. width = left + image.size[0] + right
  346. height = top + image.size[1] + bottom
  347. color = _color(fill, image.mode)
  348. if image.palette:
  349. palette = ImagePalette.ImagePalette(palette=image.getpalette())
  350. if isinstance(color, tuple):
  351. color = palette.getcolor(color)
  352. else:
  353. palette = None
  354. out = Image.new(image.mode, (width, height), color)
  355. if palette:
  356. out.putpalette(palette.palette)
  357. out.paste(image, (left, top))
  358. return out
  359. def fit(image, size, method=Image.Resampling.BICUBIC, bleed=0.0, centering=(0.5, 0.5)):
  360. """
  361. Returns a resized and cropped version of the image, cropped to the
  362. requested aspect ratio and size.
  363. This function was contributed by Kevin Cazabon.
  364. :param image: The image to resize and crop.
  365. :param size: The requested output size in pixels, given as a
  366. (width, height) tuple.
  367. :param method: Resampling method to use. Default is
  368. :py:attr:`~PIL.Image.Resampling.BICUBIC`.
  369. See :ref:`concept-filters`.
  370. :param bleed: Remove a border around the outside of the image from all
  371. four edges. The value is a decimal percentage (use 0.01 for
  372. one percent). The default value is 0 (no border).
  373. Cannot be greater than or equal to 0.5.
  374. :param centering: Control the cropping position. Use (0.5, 0.5) for
  375. center cropping (e.g. if cropping the width, take 50% off
  376. of the left side, and therefore 50% off the right side).
  377. (0.0, 0.0) will crop from the top left corner (i.e. if
  378. cropping the width, take all of the crop off of the right
  379. side, and if cropping the height, take all of it off the
  380. bottom). (1.0, 0.0) will crop from the bottom left
  381. corner, etc. (i.e. if cropping the width, take all of the
  382. crop off the left side, and if cropping the height take
  383. none from the top, and therefore all off the bottom).
  384. :return: An image.
  385. """
  386. # by Kevin Cazabon, Feb 17/2000
  387. # kevin@cazabon.com
  388. # https://www.cazabon.com
  389. # ensure centering is mutable
  390. centering = list(centering)
  391. if not 0.0 <= centering[0] <= 1.0:
  392. centering[0] = 0.5
  393. if not 0.0 <= centering[1] <= 1.0:
  394. centering[1] = 0.5
  395. if not 0.0 <= bleed < 0.5:
  396. bleed = 0.0
  397. # calculate the area to use for resizing and cropping, subtracting
  398. # the 'bleed' around the edges
  399. # number of pixels to trim off on Top and Bottom, Left and Right
  400. bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
  401. live_size = (
  402. image.size[0] - bleed_pixels[0] * 2,
  403. image.size[1] - bleed_pixels[1] * 2,
  404. )
  405. # calculate the aspect ratio of the live_size
  406. live_size_ratio = live_size[0] / live_size[1]
  407. # calculate the aspect ratio of the output image
  408. output_ratio = size[0] / size[1]
  409. # figure out if the sides or top/bottom will be cropped off
  410. if live_size_ratio == output_ratio:
  411. # live_size is already the needed ratio
  412. crop_width = live_size[0]
  413. crop_height = live_size[1]
  414. elif live_size_ratio >= output_ratio:
  415. # live_size is wider than what's needed, crop the sides
  416. crop_width = output_ratio * live_size[1]
  417. crop_height = live_size[1]
  418. else:
  419. # live_size is taller than what's needed, crop the top and bottom
  420. crop_width = live_size[0]
  421. crop_height = live_size[0] / output_ratio
  422. # make the crop
  423. crop_left = bleed_pixels[0] + (live_size[0] - crop_width) * centering[0]
  424. crop_top = bleed_pixels[1] + (live_size[1] - crop_height) * centering[1]
  425. crop = (crop_left, crop_top, crop_left + crop_width, crop_top + crop_height)
  426. # resize the image and return it
  427. return image.resize(size, method, box=crop)
  428. def flip(image):
  429. """
  430. Flip the image vertically (top to bottom).
  431. :param image: The image to flip.
  432. :return: An image.
  433. """
  434. return image.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
  435. def grayscale(image):
  436. """
  437. Convert the image to grayscale.
  438. :param image: The image to convert.
  439. :return: An image.
  440. """
  441. return image.convert("L")
  442. def invert(image):
  443. """
  444. Invert (negate) the image.
  445. :param image: The image to invert.
  446. :return: An image.
  447. """
  448. lut = []
  449. for i in range(256):
  450. lut.append(255 - i)
  451. return image.point(lut) if image.mode == "1" else _lut(image, lut)
  452. def mirror(image):
  453. """
  454. Flip image horizontally (left to right).
  455. :param image: The image to mirror.
  456. :return: An image.
  457. """
  458. return image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
  459. def posterize(image, bits):
  460. """
  461. Reduce the number of bits for each color channel.
  462. :param image: The image to posterize.
  463. :param bits: The number of bits to keep for each channel (1-8).
  464. :return: An image.
  465. """
  466. lut = []
  467. mask = ~(2 ** (8 - bits) - 1)
  468. for i in range(256):
  469. lut.append(i & mask)
  470. return _lut(image, lut)
  471. def solarize(image, threshold=128):
  472. """
  473. Invert all pixel values above a threshold.
  474. :param image: The image to solarize.
  475. :param threshold: All pixels above this greyscale level are inverted.
  476. :return: An image.
  477. """
  478. lut = []
  479. for i in range(256):
  480. if i < threshold:
  481. lut.append(i)
  482. else:
  483. lut.append(255 - i)
  484. return _lut(image, lut)
  485. def exif_transpose(image):
  486. """
  487. If an image has an EXIF Orientation tag, other than 1, return a new image
  488. that is transposed accordingly. The new image will have the orientation
  489. data removed.
  490. Otherwise, return a copy of the image.
  491. :param image: The image to transpose.
  492. :return: An image.
  493. """
  494. exif = image.getexif()
  495. orientation = exif.get(0x0112)
  496. method = {
  497. 2: Image.Transpose.FLIP_LEFT_RIGHT,
  498. 3: Image.Transpose.ROTATE_180,
  499. 4: Image.Transpose.FLIP_TOP_BOTTOM,
  500. 5: Image.Transpose.TRANSPOSE,
  501. 6: Image.Transpose.ROTATE_270,
  502. 7: Image.Transpose.TRANSVERSE,
  503. 8: Image.Transpose.ROTATE_90,
  504. }.get(orientation)
  505. if method is not None:
  506. transposed_image = image.transpose(method)
  507. transposed_exif = transposed_image.getexif()
  508. if 0x0112 in transposed_exif:
  509. del transposed_exif[0x0112]
  510. if "exif" in transposed_image.info:
  511. transposed_image.info["exif"] = transposed_exif.tobytes()
  512. elif "Raw profile type exif" in transposed_image.info:
  513. transposed_image.info[
  514. "Raw profile type exif"
  515. ] = transposed_exif.tobytes().hex()
  516. elif "XML:com.adobe.xmp" in transposed_image.info:
  517. for pattern in (
  518. r'tiff:Orientation="([0-9])"',
  519. r"<tiff:Orientation>([0-9])</tiff:Orientation>",
  520. ):
  521. transposed_image.info["XML:com.adobe.xmp"] = re.sub(
  522. pattern, "", transposed_image.info["XML:com.adobe.xmp"]
  523. )
  524. return transposed_image
  525. return image.copy()