ImageFilter.py 17 KB

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