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.

ImageFilter.py 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. #
  2. # The Python Imaging Library.
  3. # $Id$
  4. #
  5. # standard filters
  6. #
  7. # History:
  8. # 1995-11-27 fl Created
  9. # 2002-06-08 fl Added rank and mode filters
  10. # 2003-09-15 fl Fixed rank calculation in rank filter; added expand call
  11. #
  12. # Copyright (c) 1997-2003 by Secret Labs AB.
  13. # Copyright (c) 1995-2002 by Fredrik Lundh.
  14. #
  15. # See the README file for information on usage and redistribution.
  16. #
  17. from __future__ import division
  18. import functools
  19. try:
  20. import numpy
  21. except ImportError: # pragma: no cover
  22. numpy = None
  23. class Filter(object):
  24. pass
  25. class MultibandFilter(Filter):
  26. pass
  27. class BuiltinFilter(MultibandFilter):
  28. def filter(self, image):
  29. if image.mode == "P":
  30. raise ValueError("cannot filter palette images")
  31. return image.filter(*self.filterargs)
  32. class Kernel(BuiltinFilter):
  33. """
  34. Create a convolution kernel. The current version only
  35. supports 3x3 and 5x5 integer and floating point kernels.
  36. In the current version, kernels can only be applied to
  37. "L" and "RGB" images.
  38. :param size: Kernel size, given as (width, height). In the current
  39. version, this must be (3,3) or (5,5).
  40. :param kernel: A sequence containing kernel weights.
  41. :param scale: Scale factor. If given, the result for each pixel is
  42. divided by this value. the default is the sum of the
  43. kernel weights.
  44. :param offset: Offset. If given, this value is added to the result,
  45. after it has been divided by the scale factor.
  46. """
  47. name = "Kernel"
  48. def __init__(self, size, kernel, scale=None, offset=0):
  49. if scale is None:
  50. # default scale is sum of kernel
  51. scale = functools.reduce(lambda a, b: a + b, kernel)
  52. if size[0] * size[1] != len(kernel):
  53. raise ValueError("not enough coefficients in kernel")
  54. self.filterargs = size, scale, offset, kernel
  55. class RankFilter(Filter):
  56. """
  57. Create a rank filter. The rank filter sorts all pixels in
  58. a window of the given size, and returns the **rank**'th value.
  59. :param size: The kernel size, in pixels.
  60. :param rank: What pixel value to pick. Use 0 for a min filter,
  61. ``size * size / 2`` for a median filter, ``size * size - 1``
  62. for a max filter, etc.
  63. """
  64. name = "Rank"
  65. def __init__(self, size, rank):
  66. self.size = size
  67. self.rank = rank
  68. def filter(self, image):
  69. if image.mode == "P":
  70. raise ValueError("cannot filter palette images")
  71. image = image.expand(self.size // 2, self.size // 2)
  72. return image.rankfilter(self.size, self.rank)
  73. class MedianFilter(RankFilter):
  74. """
  75. Create a median filter. Picks the median pixel value in a window with the
  76. given size.
  77. :param size: The kernel size, in pixels.
  78. """
  79. name = "Median"
  80. def __init__(self, size=3):
  81. self.size = size
  82. self.rank = size * size // 2
  83. class MinFilter(RankFilter):
  84. """
  85. Create a min filter. Picks the lowest pixel value in a window with the
  86. given size.
  87. :param size: The kernel size, in pixels.
  88. """
  89. name = "Min"
  90. def __init__(self, size=3):
  91. self.size = size
  92. self.rank = 0
  93. class MaxFilter(RankFilter):
  94. """
  95. Create a max filter. Picks the largest pixel value in a window with the
  96. given size.
  97. :param size: The kernel size, in pixels.
  98. """
  99. name = "Max"
  100. def __init__(self, size=3):
  101. self.size = size
  102. self.rank = size * size - 1
  103. class ModeFilter(Filter):
  104. """
  105. Create a mode filter. Picks the most frequent pixel value in a box with the
  106. given size. Pixel values that occur only once or twice are ignored; if no
  107. pixel value occurs more than twice, the original pixel value is preserved.
  108. :param size: The kernel size, in pixels.
  109. """
  110. name = "Mode"
  111. def __init__(self, size=3):
  112. self.size = size
  113. def filter(self, image):
  114. return image.modefilter(self.size)
  115. class GaussianBlur(MultibandFilter):
  116. """Gaussian blur filter.
  117. :param radius: Blur radius.
  118. """
  119. name = "GaussianBlur"
  120. def __init__(self, radius=2):
  121. self.radius = radius
  122. def filter(self, image):
  123. return image.gaussian_blur(self.radius)
  124. class BoxBlur(MultibandFilter):
  125. """Blurs the image by setting each pixel to the average value of the pixels
  126. in a square box extending radius pixels in each direction.
  127. Supports float radius of arbitrary size. Uses an optimized implementation
  128. which runs in linear time relative to the size of the image
  129. for any radius value.
  130. :param radius: Size of the box in one direction. Radius 0 does not blur,
  131. returns an identical image. Radius 1 takes 1 pixel
  132. in each direction, i.e. 9 pixels in total.
  133. """
  134. name = "BoxBlur"
  135. def __init__(self, radius):
  136. self.radius = radius
  137. def filter(self, image):
  138. return image.box_blur(self.radius)
  139. class UnsharpMask(MultibandFilter):
  140. """Unsharp mask filter.
  141. See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
  142. the parameters.
  143. :param radius: Blur Radius
  144. :param percent: Unsharp strength, in percent
  145. :param threshold: Threshold controls the minimum brightness change that
  146. will be sharpened
  147. .. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
  148. """ # noqa: E501
  149. name = "UnsharpMask"
  150. def __init__(self, radius=2, percent=150, threshold=3):
  151. self.radius = radius
  152. self.percent = percent
  153. self.threshold = threshold
  154. def filter(self, image):
  155. return image.unsharp_mask(self.radius, self.percent, self.threshold)
  156. class BLUR(BuiltinFilter):
  157. name = "Blur"
  158. # fmt: off
  159. filterargs = (5, 5), 16, 0, (
  160. 1, 1, 1, 1, 1,
  161. 1, 0, 0, 0, 1,
  162. 1, 0, 0, 0, 1,
  163. 1, 0, 0, 0, 1,
  164. 1, 1, 1, 1, 1,
  165. )
  166. # fmt: on
  167. class CONTOUR(BuiltinFilter):
  168. name = "Contour"
  169. # fmt: off
  170. filterargs = (3, 3), 1, 255, (
  171. -1, -1, -1,
  172. -1, 8, -1,
  173. -1, -1, -1,
  174. )
  175. # fmt: on
  176. class DETAIL(BuiltinFilter):
  177. name = "Detail"
  178. # fmt: off
  179. filterargs = (3, 3), 6, 0, (
  180. 0, -1, 0,
  181. -1, 10, -1,
  182. 0, -1, 0,
  183. )
  184. # fmt: on
  185. class EDGE_ENHANCE(BuiltinFilter):
  186. name = "Edge-enhance"
  187. # fmt: off
  188. filterargs = (3, 3), 2, 0, (
  189. -1, -1, -1,
  190. -1, 10, -1,
  191. -1, -1, -1,
  192. )
  193. # fmt: on
  194. class EDGE_ENHANCE_MORE(BuiltinFilter):
  195. name = "Edge-enhance More"
  196. # fmt: off
  197. filterargs = (3, 3), 1, 0, (
  198. -1, -1, -1,
  199. -1, 9, -1,
  200. -1, -1, -1,
  201. )
  202. # fmt: on
  203. class EMBOSS(BuiltinFilter):
  204. name = "Emboss"
  205. # fmt: off
  206. filterargs = (3, 3), 1, 128, (
  207. -1, 0, 0,
  208. 0, 1, 0,
  209. 0, 0, 0,
  210. )
  211. # fmt: on
  212. class FIND_EDGES(BuiltinFilter):
  213. name = "Find Edges"
  214. # fmt: off
  215. filterargs = (3, 3), 1, 0, (
  216. -1, -1, -1,
  217. -1, 8, -1,
  218. -1, -1, -1,
  219. )
  220. # fmt: on
  221. class SHARPEN(BuiltinFilter):
  222. name = "Sharpen"
  223. # fmt: off
  224. filterargs = (3, 3), 16, 0, (
  225. -2, -2, -2,
  226. -2, 32, -2,
  227. -2, -2, -2,
  228. )
  229. # fmt: on
  230. class SMOOTH(BuiltinFilter):
  231. name = "Smooth"
  232. # fmt: off
  233. filterargs = (3, 3), 13, 0, (
  234. 1, 1, 1,
  235. 1, 5, 1,
  236. 1, 1, 1,
  237. )
  238. # fmt: on
  239. class SMOOTH_MORE(BuiltinFilter):
  240. name = "Smooth More"
  241. # fmt: off
  242. filterargs = (5, 5), 100, 0, (
  243. 1, 1, 1, 1, 1,
  244. 1, 5, 5, 5, 1,
  245. 1, 5, 44, 5, 1,
  246. 1, 5, 5, 5, 1,
  247. 1, 1, 1, 1, 1,
  248. )
  249. # fmt: on
  250. class Color3DLUT(MultibandFilter):
  251. """Three-dimensional color lookup table.
  252. Transforms 3-channel pixels using the values of the channels as coordinates
  253. in the 3D lookup table and interpolating the nearest elements.
  254. This method allows you to apply almost any color transformation
  255. in constant time by using pre-calculated decimated tables.
  256. .. versionadded:: 5.2.0
  257. :param size: Size of the table. One int or tuple of (int, int, int).
  258. Minimal size in any dimension is 2, maximum is 65.
  259. :param table: Flat lookup table. A list of ``channels * size**3``
  260. float elements or a list of ``size**3`` channels-sized
  261. tuples with floats. Channels are changed first,
  262. then first dimension, then second, then third.
  263. Value 0.0 corresponds lowest value of output, 1.0 highest.
  264. :param channels: Number of channels in the table. Could be 3 or 4.
  265. Default is 3.
  266. :param target_mode: A mode for the result image. Should have not less
  267. than ``channels`` channels. Default is ``None``,
  268. which means that mode wouldn't be changed.
  269. """
  270. name = "Color 3D LUT"
  271. def __init__(self, size, table, channels=3, target_mode=None, **kwargs):
  272. if channels not in (3, 4):
  273. raise ValueError("Only 3 or 4 output channels are supported")
  274. self.size = size = self._check_size(size)
  275. self.channels = channels
  276. self.mode = target_mode
  277. # Hidden flag `_copy_table=False` could be used to avoid extra copying
  278. # of the table if the table is specially made for the constructor.
  279. copy_table = kwargs.get("_copy_table", True)
  280. items = size[0] * size[1] * size[2]
  281. wrong_size = False
  282. if numpy and isinstance(table, numpy.ndarray):
  283. if copy_table:
  284. table = table.copy()
  285. if table.shape in [
  286. (items * channels,),
  287. (items, channels),
  288. (size[2], size[1], size[0], channels),
  289. ]:
  290. table = table.reshape(items * channels)
  291. else:
  292. wrong_size = True
  293. else:
  294. if copy_table:
  295. table = list(table)
  296. # Convert to a flat list
  297. if table and isinstance(table[0], (list, tuple)):
  298. table, raw_table = [], table
  299. for pixel in raw_table:
  300. if len(pixel) != channels:
  301. raise ValueError(
  302. "The elements of the table should "
  303. "have a length of {}.".format(channels)
  304. )
  305. table.extend(pixel)
  306. if wrong_size or len(table) != items * channels:
  307. raise ValueError(
  308. "The table should have either channels * size**3 float items "
  309. "or size**3 items of channels-sized tuples with floats. "
  310. "Table should be: {}x{}x{}x{}. Actual length: {}".format(
  311. channels, size[0], size[1], size[2], len(table)
  312. )
  313. )
  314. self.table = table
  315. @staticmethod
  316. def _check_size(size):
  317. try:
  318. _, _, _ = size
  319. except ValueError:
  320. raise ValueError(
  321. "Size should be either an integer or a tuple of three integers."
  322. )
  323. except TypeError:
  324. size = (size, size, size)
  325. size = [int(x) for x in size]
  326. for size1D in size:
  327. if not 2 <= size1D <= 65:
  328. raise ValueError("Size should be in [2, 65] range.")
  329. return size
  330. @classmethod
  331. def generate(cls, size, callback, channels=3, target_mode=None):
  332. """Generates new LUT using provided callback.
  333. :param size: Size of the table. Passed to the constructor.
  334. :param callback: Function with three parameters which correspond
  335. three color channels. Will be called ``size**3``
  336. times with values from 0.0 to 1.0 and should return
  337. a tuple with ``channels`` elements.
  338. :param channels: The number of channels which should return callback.
  339. :param target_mode: Passed to the constructor of the resulting
  340. lookup table.
  341. """
  342. size1D, size2D, size3D = cls._check_size(size)
  343. if channels not in (3, 4):
  344. raise ValueError("Only 3 or 4 output channels are supported")
  345. table = [0] * (size1D * size2D * size3D * channels)
  346. idx_out = 0
  347. for b in range(size3D):
  348. for g in range(size2D):
  349. for r in range(size1D):
  350. table[idx_out : idx_out + channels] = callback(
  351. r / (size1D - 1), g / (size2D - 1), b / (size3D - 1)
  352. )
  353. idx_out += channels
  354. return cls(
  355. (size1D, size2D, size3D),
  356. table,
  357. channels=channels,
  358. target_mode=target_mode,
  359. _copy_table=False,
  360. )
  361. def transform(self, callback, with_normals=False, channels=None, target_mode=None):
  362. """Transforms the table values using provided callback and returns
  363. a new LUT with altered values.
  364. :param callback: A function which takes old lookup table values
  365. and returns a new set of values. The number
  366. of arguments which function should take is
  367. ``self.channels`` or ``3 + self.channels``
  368. if ``with_normals`` flag is set.
  369. Should return a tuple of ``self.channels`` or
  370. ``channels`` elements if it is set.
  371. :param with_normals: If true, ``callback`` will be called with
  372. coordinates in the color cube as the first
  373. three arguments. Otherwise, ``callback``
  374. will be called only with actual color values.
  375. :param channels: The number of channels in the resulting lookup table.
  376. :param target_mode: Passed to the constructor of the resulting
  377. lookup table.
  378. """
  379. if channels not in (None, 3, 4):
  380. raise ValueError("Only 3 or 4 output channels are supported")
  381. ch_in = self.channels
  382. ch_out = channels or ch_in
  383. size1D, size2D, size3D = self.size
  384. table = [0] * (size1D * size2D * size3D * ch_out)
  385. idx_in = 0
  386. idx_out = 0
  387. for b in range(size3D):
  388. for g in range(size2D):
  389. for r in range(size1D):
  390. values = self.table[idx_in : idx_in + ch_in]
  391. if with_normals:
  392. values = callback(
  393. r / (size1D - 1),
  394. g / (size2D - 1),
  395. b / (size3D - 1),
  396. *values
  397. )
  398. else:
  399. values = callback(*values)
  400. table[idx_out : idx_out + ch_out] = values
  401. idx_in += ch_in
  402. idx_out += ch_out
  403. return type(self)(
  404. self.size,
  405. table,
  406. channels=ch_out,
  407. target_mode=target_mode or self.mode,
  408. _copy_table=False,
  409. )
  410. def __repr__(self):
  411. r = [
  412. "{} from {}".format(self.__class__.__name__, self.table.__class__.__name__),
  413. "size={:d}x{:d}x{:d}".format(*self.size),
  414. "channels={:d}".format(self.channels),
  415. ]
  416. if self.mode:
  417. r.append("target_mode={}".format(self.mode))
  418. return "<{}>".format(" ".join(r))
  419. def filter(self, image):
  420. from . import Image
  421. return image.color_lut_3d(
  422. self.mode or image.mode,
  423. Image.LINEAR,
  424. self.channels,
  425. self.size[0],
  426. self.size[1],
  427. self.size[2],
  428. self.table,
  429. )