Merge pull request #375 from irskep/doc-improvements

Document ImageEnhance, ImageFile, ImageFilter, ImageFont, ImageGrab, ImageMath, and ImageOps
This commit is contained in:
Alex Clark ☺ 2013-10-13 10:04:12 -07:00
commit 4ea303af6f
20 changed files with 684 additions and 411 deletions

View File

@ -20,71 +20,68 @@
from PIL import Image, ImageFilter, ImageStat
class _Enhance:
##
# Returns an enhanced image. The enhancement factor is a floating
# point value controlling the enhancement. Factor 1.0 always
# returns a copy of the original image, lower factors mean less
# colour (brightness, contrast, etc), and higher values more.
# There are no restrictions on this value.
#
# @param factor Enhancement factor.
# @return An enhanced image.
def enhance(self, factor):
"""
Returns an enhanced image.
:param factor: A floating point value controlling the enhancement.
Factor 1.0 always returns a copy of the original image,
lower factors mean less color (brightness, contrast,
etc), and higher values more. There are no restrictions
on this value.
:rtype: :py:class:`~PIL.Image.Image`
"""
return Image.blend(self.degenerate, self.image, factor)
##
# Color enhancement object.
# <p>
# This class can be used to adjust the colour balance of an image, in
# a manner similar to the controls on a colour TV set. An enhancement
# factor of 0.0 gives a black and white image, a factor of 1.0 gives
# the original image.
class Color(_Enhance):
"Adjust image colour balance"
"""Adjust image color balance.
This class can be used to adjust the colour balance of an image, in
a manner similar to the controls on a colour TV set. An enhancement
factor of 0.0 gives a black and white image. A factor of 1.0 gives
the original image.
"""
def __init__(self, image):
self.image = image
self.degenerate = image.convert("L").convert(image.mode)
##
# Contrast enhancement object.
# <p>
# This class can be used to control the contrast of an image, similar
# to the contrast control on a TV set. An enhancement factor of 0.0
# gives a solid grey image, factor 1.0 gives the original image.
class Contrast(_Enhance):
"Adjust image contrast"
"""Adjust image contrast.
This class can be used to control the contrast of an image, similar
to the contrast control on a TV set. An enhancement factor of 0.0
gives a solid grey image. A factor of 1.0 gives the original image.
"""
def __init__(self, image):
self.image = image
mean = int(ImageStat.Stat(image.convert("L")).mean[0] + 0.5)
self.degenerate = Image.new("L", image.size, mean).convert(image.mode)
##
# Brightness enhancement object.
# <p>
# This class can be used to control the brighntess of an image. An
# enhancement factor of 0.0 gives a black image, factor 1.0 gives the
# original image.
class Brightness(_Enhance):
"Adjust image brightness"
"""Adjust image brightness.
This class can be used to control the brighntess of an image. An
enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
original image.
"""
def __init__(self, image):
self.image = image
self.degenerate = Image.new(image.mode, image.size, 0)
##
# Sharpness enhancement object.
# <p>
# This class can be used to adjust the sharpness of an image. The
# enhancement factor 0.0 gives a blurred image, 1.0 gives the original
# image, and a factor of 2.0 gives a sharpened image.
class Sharpness(_Enhance):
"Adjust image sharpness"
"""Adjust image sharpness.
This class can be used to adjust the sharpness of an image. An
enhancement factor of 0.0 gives a blurred image, a factor of 1.0 gives the
original image, and a factor of 2.0 gives a sharpened image.
"""
def __init__(self, image):
self.image = image
self.degenerate = image.filter(ImageFilter.SMOOTH)

View File

@ -137,7 +137,7 @@ class ImageFile(Image.Image):
readonly = 0
if self.filename and len(self.tile) == 1 and not hasattr(sys, 'pypy_version_info'):
# As of pypy 2.1.0, memory mapping was failing here.
# As of pypy 2.1.0, memory mapping was failing here.
# try memory mapping
d, e, o, a = self.tile[0]
if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES:
@ -299,6 +299,8 @@ class Parser:
"""
Incremental image parser. This class implements the standard
feed/close consumer interface.
In Python 2.x, this is an old-style class.
"""
incremental = None
image = None
@ -318,7 +320,7 @@ class Parser:
"""
(Consumer) Feed data to the parser.
:param data" A string buffer.
:param data: A string buffer.
:exception IOError: If the parser failed to parse the image file.
"""
# collect data
@ -404,7 +406,9 @@ class Parser:
(Consumer) Close the stream.
:returns: An image object.
:exception IOError: If the parser failed to parse the image file.
:exception IOError: If the parser failed to parse the image file either
because it cannot be identified or cannot be
decoded.
"""
# finish decoding
if self.decoder:

View File

@ -17,31 +17,28 @@
from functools import reduce
class Filter(object):
pass
##
# Convolution filter kernel.
class Kernel(Filter):
"""
Create a convolution kernel. The current version only
supports 3x3 and 5x5 integer and floating point kernels.
##
# Create a convolution kernel. The current version only
# supports 3x3 and 5x5 integer and floating point kernels.
# <p>
# In the current version, kernels can only be applied to
# "L" and "RGB" images.
#
# @def __init__(size, kernel, **options)
# @param size Kernel size, given as (width, height). In
# the current version, this must be (3,3) or (5,5).
# @param kernel A sequence containing kernel weights.
# @param **options Optional keyword arguments.
# @keyparam scale Scale factor. If given, the result for each
# pixel is divided by this value. The default is the sum
# of the kernel weights.
# @keyparam offset Offset. If given, this value is added to the
# result, after it has been divided by the scale factor.
In the current version, kernels can only be applied to
"L" and "RGB" images.
:param size: Kernel size, given as (width, height). In the current
version, this must be (3,3) or (5,5).
:param kernel: A sequence containing kernel weights.
:param scale: Scale factor. If given, the result for each pixel is
divided by this value. the default is the sum of the
kernel weights.
:param offset: Offset. If given, this value is added to the result,
after it has been divided by the scale factor.
"""
def __init__(self, size, kernel, scale=None, offset=0):
if scale is None:
@ -56,24 +53,23 @@ class Kernel(Filter):
raise ValueError("cannot filter palette images")
return image.filter(*self.filterargs)
class BuiltinFilter(Kernel):
def __init__(self):
pass
##
# Rank filter.
class RankFilter(Filter):
name = "Rank"
"""
Create a rank filter. The rank filter sorts all pixels in
a window of the given size, and returns the **rank**'th value.
##
# Create a rank filter. The rank filter sorts all pixels in
# a window of the given size, and returns the rank'th value.
#
# @param size The kernel size, in pixels.
# @param rank What pixel value to pick. Use 0 for a min filter,
# size*size/2 for a median filter, size*size-1 for a max filter,
# etc.
:param size: The kernel size, in pixels.
:param rank: What pixel value to pick. Use 0 for a min filter,
``size * size / 2`` for a median filter, ``size * size - 1``
for a max filter, etc.
"""
name = "Rank"
def __init__(self, size, rank):
self.size = size
@ -85,99 +81,99 @@ class RankFilter(Filter):
image = image.expand(self.size//2, self.size//2)
return image.rankfilter(self.size, self.rank)
##
# Median filter. Picks the median pixel value in a window with the
# given size.
class MedianFilter(RankFilter):
name = "Median"
"""
Create a median filter. Picks the median pixel value in a window with the
given size.
##
# Create a median filter.
#
# @param size The kernel size, in pixels.
:param size: The kernel size, in pixels.
"""
name = "Median"
def __init__(self, size=3):
self.size = size
self.rank = size*size//2
##
# Min filter. Picks the lowest pixel value in a window with the given
# size.
class MinFilter(RankFilter):
name = "Min"
"""
Create a min filter. Picks the lowest pixel value in a window with the
given size.
##
# Create a min filter.
#
# @param size The kernel size, in pixels.
:param size: The kernel size, in pixels.
"""
name = "Min"
def __init__(self, size=3):
self.size = size
self.rank = 0
##
# Max filter. Picks the largest pixel value in a window with the
# given size.
class MaxFilter(RankFilter):
name = "Max"
"""
Create a max filter. Picks the largest pixel value in a window with the
given size.
##
# Create a max filter.
#
# @param size The kernel size, in pixels.
:param size: The kernel size, in pixels.
"""
name = "Max"
def __init__(self, size=3):
self.size = size
self.rank = size*size-1
##
# Mode filter. Picks the most frequent pixel value in a box with the
# given size. Pixel values that occur only once or twice are ignored;
# if no pixel value occurs more than twice, the original pixel value
# is preserved.
class ModeFilter(Filter):
name = "Mode"
"""
##
# Create a mode filter.
#
# @param size The kernel size, in pixels.
Create a mode filter. Picks the most frequent pixel value in a box with the
given size. Pixel values that occur only once or twice are ignored; if no
pixel value occurs more than twice, the original pixel value is preserved.
:param size: The kernel size, in pixels.
"""
name = "Mode"
def __init__(self, size=3):
self.size = size
def filter(self, image):
return image.modefilter(self.size)
##
# Gaussian blur filter.
class GaussianBlur(Filter):
"""Gaussian blur filter.
:param radius: Blur radius.
"""
name = "GaussianBlur"
def __init__(self, radius=2):
self.radius = radius
def filter(self, image):
return image.gaussian_blur(self.radius)
##
# Unsharp mask filter.
class UnsharpMask(Filter):
"""Unsharp mask filter.
See Wikipedia's entry on `digital unsharp masking`_ for an explanation of
the parameters.
.. _digital unsharp masking: https://en.wikipedia.org/wiki/Unsharp_masking#Digital_unsharp_masking
"""
name = "UnsharpMask"
def __init__(self, radius=2, percent=150, threshold=3):
self.radius = radius
self.percent = percent
self.threshold = threshold
def filter(self, image):
return image.unsharp_mask(self.radius, self.percent, self.threshold)
##
# Simple blur filter.
class BLUR(BuiltinFilter):
name = "Blur"
@ -189,8 +185,6 @@ class BLUR(BuiltinFilter):
1, 1, 1, 1, 1
)
##
# Simple contour filter.
class CONTOUR(BuiltinFilter):
name = "Contour"
@ -200,8 +194,6 @@ class CONTOUR(BuiltinFilter):
-1, -1, -1
)
##
# Simple detail filter.
class DETAIL(BuiltinFilter):
name = "Detail"
@ -211,8 +203,6 @@ class DETAIL(BuiltinFilter):
0, -1, 0
)
##
# Simple edge enhancement filter.
class EDGE_ENHANCE(BuiltinFilter):
name = "Edge-enhance"
@ -222,8 +212,6 @@ class EDGE_ENHANCE(BuiltinFilter):
-1, -1, -1
)
##
# Simple stronger edge enhancement filter.
class EDGE_ENHANCE_MORE(BuiltinFilter):
name = "Edge-enhance More"
@ -233,8 +221,6 @@ class EDGE_ENHANCE_MORE(BuiltinFilter):
-1, -1, -1
)
##
# Simple embossing filter.
class EMBOSS(BuiltinFilter):
name = "Emboss"
@ -244,8 +230,6 @@ class EMBOSS(BuiltinFilter):
0, 0, 0
)
##
# Simple edge-finding filter.
class FIND_EDGES(BuiltinFilter):
name = "Find Edges"
@ -255,8 +239,6 @@ class FIND_EDGES(BuiltinFilter):
-1, -1, -1
)
##
# Simple smoothing filter.
class SMOOTH(BuiltinFilter):
name = "Smooth"
@ -266,8 +248,6 @@ class SMOOTH(BuiltinFilter):
1, 1, 1
)
##
# Simple stronger smoothing filter.
class SMOOTH_MORE(BuiltinFilter):
name = "Smooth More"
@ -279,8 +259,6 @@ class SMOOTH_MORE(BuiltinFilter):
1, 1, 1, 1, 1
)
##
# Simple sharpening filter.
class SHARPEN(BuiltinFilter):
name = "Sharpen"

View File

@ -61,21 +61,6 @@ except ImportError:
# position according to dx, dy.
# --------------------------------------------------------------------
##
# The <b>ImageFont</b> module defines a class with the same name.
# Instances of this class store bitmap fonts, and are used with the
# <b>text</b> method of the <b>ImageDraw</b> class.
# <p>
# PIL uses it's own font file format to store bitmap fonts. You can
# use the <b>pilfont</b> utility to convert BDF and PCF font
# descriptors (X window font formats) to this format.
# <p>
# Starting with version 1.1.4, PIL can be configured to support
# TrueType and OpenType fonts. For earlier version, TrueType
# support is only available as part of the imToolkit package
#
# @see ImageDraw#ImageDraw.text
# @see pilfont
class ImageFont:
"PIL font wrapper"
@ -197,41 +182,42 @@ class TransposedFont:
return im.transpose(self.orientation)
return im
##
# Load font file. This function loads a font object from the given
# bitmap font file, and returns the corresponding font object.
#
# @param filename Name of font file.
# @return A font object.
# @exception IOError If the file could not be read.
def load(filename):
"Load a font file."
"""
Load a font file. This function loads a font object from the given
bitmap font file, and returns the corresponding font object.
:param filename: Name of font file.
:return: A font object.
:exception IOError: If the file could not be read.
"""
f = ImageFont()
f._load_pilfont(filename)
return f
##
# Load a TrueType or OpenType font file, and create a font object.
# This function loads a font object from the given file, and creates
# a font object for a font of the given size.
# <p>
# This function requires the _imagingft service.
#
# @param filename A truetype font file. Under Windows, if the file
# is not found in this filename, the loader also looks in Windows
# <b>fonts</b> directory
# @param size The requested size, in points.
# @param index Which font face to load (default is first available face).
# @param encoding Which font encoding to use (default is Unicode). Common
# encodings are "unic" (Unicode), "symb" (Microsoft Symbol), "ADOB"
# (Adobe Standard), "ADBE" (Adobe Expert), and "armn" (Apple Roman).
# See the FreeType documentation for more information.
# @return A font object.
# @exception IOError If the file could not be read.
def truetype(font=None, size=10, index=0, encoding="", filename=None):
"Load a truetype font file."
"""
Load a TrueType or OpenType font file, and create a font object.
This function loads a font object from the given file, and creates
a font object for a font of the given size.
This function requires the _imagingft service.
:param filename: A truetype font file. Under Windows, if the file
is not found in this filename, the loader also looks in
Windows :file:`fonts/` directory.
:param size: The requested size, in points.
:param index: Which font face to load (default is first available face).
:param encoding: Which font encoding to use (default is Unicode). Common
encodings are "unic" (Unicode), "symb" (Microsoft
Symbol), "ADOB" (Adobe Standard), "ADBE" (Adobe Expert),
and "armn" (Apple Roman). See the FreeType documentation
for more information.
:return: A font object.
:exception IOError: If the file could not be read.
"""
if filename:
if warnings:
@ -251,17 +237,16 @@ def truetype(font=None, size=10, index=0, encoding="", filename=None):
return FreeTypeFont(filename, size, index, encoding)
raise
##
# Load font file. Same as load, but searches for a bitmap font along
# the Python path.
#
# @param filename Name of font file.
# @return A font object.
# @exception IOError If the file could not be read.
# @see #load
def load_path(filename):
"Load a font file, searching along the Python path."
"""
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a
bitmap font along the Python path.
:param filename: Name of font file.
:return: A font object.
:exception IOError: If the file could not be read.
"""
for dir in sys.path:
if isDirectory(dir):
if not isinstance(filename, str):
@ -275,13 +260,14 @@ def load_path(filename):
pass
raise IOError("cannot find font file")
##
# Load a (probably rather ugly) default font.
#
# @return A font object.
def load_default():
"Load a default font."
"""Load a "better than nothing" default font.
.. versionadded:: 1.1.4
:return: A font object.
"""
from io import BytesIO
import base64
f = ImageFont()
@ -406,6 +392,7 @@ w7IkEbzhVQAAAABJRU5ErkJggg==
'''))))
return f
if __name__ == "__main__":
# create font data chunk for embedding
import base64, os, sys

View File

@ -17,14 +17,6 @@
from PIL import Image
##
# (New in 1.1.3) The <b>ImageGrab</b> module can be used to copy
# the contents of the screen to a PIL image memory.
# <p>
# The current version works on Windows only.</p>
#
# @since 1.1.3
##
try:
# built-in driver (1.1.3 and later)
@ -34,14 +26,6 @@ except AttributeError:
import _grabscreen
grabber = _grabscreen.grab
##
# (New in 1.1.3) Take a snapshot of the screen. The pixels inside the
# bounding box are returned as an "RGB" image. If the bounding box is
# omitted, the entire screen is copied.
#
# @param bbox What region to copy. Default is the entire screen.
# @return An image
# @since 1.1.3
def grab(bbox=None):
size, data = grabber()
@ -54,13 +38,6 @@ def grab(bbox=None):
im = im.crop(bbox)
return im
##
# (New in 1.1.4) Take a snapshot of the clipboard image, if any.
#
# @return An image, a list of filenames, or None if the clipboard does
# not contain image data or filenames. Note that if a list is
# returned, the filenames may not represent image files.
# @since 1.1.4
def grabclipboard():
debug = 0 # temporary interface

View File

@ -199,17 +199,19 @@ for k, v in list(globals().items()):
if k[:10] == "imagemath_":
ops[k[10:]] = v
##
# Evaluates an image expression.
#
# @param expression A string containing a Python-style expression.
# @keyparam options Values to add to the evaluation context. You
# can either use a dictionary, or one or more keyword arguments.
# @return The evaluated expression. This is usually an image object,
# but can also be an integer, a floating point value, or a pixel
# tuple, depending on the expression.
def eval(expression, _dict={}, **kw):
"""
Evaluates an image expression.
:param expression: A string containing a Python-style expression.
:param options: Values to add to the evaluation context. You
can either use a dictionary, or one or more keyword
arguments.
:return: The evaluated expression. This is usually an image object, but can
also be an integer, a floating point value, or a pixel tuple,
depending on the expression.
"""
# build execution namespace
args = ops.copy()

View File

@ -22,14 +22,6 @@ from PIL._util import isStringType
import operator
from functools import reduce
##
# (New in 1.1.3) The <b>ImageOps</b> module contains a number of
# 'ready-made' image processing operations. This module is somewhat
# experimental, and most operators only work on L and RGB images.
#
# @since 1.1.3
##
#
# helpers
@ -63,20 +55,20 @@ def _lut(image, lut):
#
# actions
##
# Maximize (normalize) image contrast. This function calculates a
# histogram of the input image, removes <i>cutoff</i> percent of the
# lightest and darkest pixels from the histogram, and remaps the image
# so that the darkest pixel becomes black (0), and the lightest
# becomes white (255).
#
# @param image The image to process.
# @param cutoff How many percent to cut off from the histogram.
# @param ignore The background pixel value (use None for no background).
# @return An image.
def autocontrast(image, cutoff=0, ignore=None):
"Maximize image contrast, based on histogram"
"""
Maximize (normalize) image contrast. This function calculates a
histogram of the input image, removes **cutoff** percent of the
lightest and darkest pixels from the histogram, and remaps the image
so that the darkest pixel becomes black (0), and the lightest
becomes white (255).
:param image: The image to process.
:param cutoff: How many percent to cut off from the histogram.
:param ignore: The background pixel value (use None for no background).
:return: An image.
"""
histogram = image.histogram()
lut = []
for layer in range(0, len(histogram), 256):
@ -139,19 +131,19 @@ def autocontrast(image, cutoff=0, ignore=None):
lut.append(ix)
return _lut(image, lut)
##
# Colorize grayscale image. The <i>black</i> and <i>white</i>
# arguments should be RGB tuples; this function calculates a colour
# wedge mapping all black pixels in the source image to the first
# colour, and all white pixels to the second colour.
#
# @param image The image to colourize.
# @param black The colour to use for black input pixels.
# @param white The colour to use for white input pixels.
# @return An image.
def colorize(image, black, white):
"Colorize a grayscale image"
"""
Colorize grayscale image. The **black** and **white**
arguments should be RGB tuples; this function calculates a color
wedge mapping all black pixels in the source image to the first
color, and all white pixels to the second color.
:param image: The image to colorize.
:param black: The color to use for black input pixels.
:param white: The color to use for white input pixels.
:return: An image.
"""
assert image.mode == "L"
black = _color(black, "RGB")
white = _color(white, "RGB")
@ -163,49 +155,50 @@ def colorize(image, black, white):
image = image.convert("RGB")
return _lut(image, red + green + blue)
##
# Remove border from image. The same amount of pixels are removed
# from all four sides. This function works on all image modes.
#
# @param image The image to crop.
# @param border The number of pixels to remove.
# @return An image.
# @see Image#Image.crop
def crop(image, border=0):
"Crop border off image"
"""
Remove border from image. The same amount of pixels are removed
from all four sides. This function works on all image modes.
.. seealso:: :py:meth:`~PIL.Image.Image.crop`
:param image: The image to crop.
:param border: The number of pixels to remove.
:return: An image.
"""
left, top, right, bottom = _border(border)
return image.crop(
(left, top, image.size[0]-right, image.size[1]-bottom)
)
##
# Deform the image.
#
# @param image The image to deform.
# @param deformer A deformer object. Any object that implements a
# <b>getmesh</b> method can be used.
# @param resample What resampling filter to use.
# @return An image.
def deform(image, deformer, resample=Image.BILINEAR):
"Deform image using the given deformer"
"""
Deform the image.
:param image: The image to deform.
:param deformer: A deformer object. Any object that implements a
**getmesh** method can be used.
:param resample: What resampling filter to use.
:return: An image.
"""
return image.transform(
image.size, Image.MESH, deformer.getmesh(image), resample
)
##
# Equalize the image histogram. This function applies a non-linear
# mapping to the input image, in order to create a uniform
# distribution of grayscale values in the output image.
#
# @param image The image to equalize.
# @param mask An optional mask. If given, only the pixels selected by
# the mask are included in the analysis.
# @return An image.
def equalize(image, mask=None):
"Equalize image histogram"
"""
Equalize the image histogram. This function applies a non-linear
mapping to the input image, in order to create a uniform
distribution of grayscale values in the output image.
:param image: The image to equalize.
:param mask: An optional mask. If given, only the pixels selected by
the mask are included in the analysis.
:return: An image.
"""
if image.mode == "P":
image = image.convert("RGB")
h = image.histogram(mask)
@ -225,15 +218,16 @@ def equalize(image, mask=None):
n = n + h[i+b]
return _lut(image, lut)
##
# Add border to the image
#
# @param image The image to expand.
# @param border Border width, in pixels.
# @param fill Pixel fill value (a colour value). Default is 0 (black).
# @return An image.
def expand(image, border=0, fill=0):
"""
Add border to the image
:param image: The image to expand.
:param border: Border width, in pixels.
:param fill: Pixel fill value (a color value). Default is 0 (black).
:return: An image.
"""
"Add border to image"
left, top, right, bottom = _border(border)
width = left + image.size[0] + right
@ -242,33 +236,32 @@ def expand(image, border=0, fill=0):
out.paste(image, (left, top))
return out
##
# Returns a sized and cropped version of the image, cropped to the
# requested aspect ratio and size.
# <p>
# The <b>fit</b> function was contributed by Kevin Cazabon.
#
# @param size The requested output size in pixels, given as a
# (width, height) tuple.
# @param method What resampling method to use. Default is Image.NEAREST.
# @param bleed Remove a border around the outside of the image (from all
# four edges. The value is a decimal percentage (use 0.01 for one
# percent). The default value is 0 (no border).
# @param centering Control the cropping position. Use (0.5, 0.5) for
# center cropping (e.g. if cropping the width, take 50% off of the
# left side, and therefore 50% off the right side). (0.0, 0.0)
# will crop from the top left corner (i.e. if cropping the width,
# take all of the crop off of the right side, and if cropping the
# height, take all of it off the bottom). (1.0, 0.0) will crop
# from the bottom left corner, etc. (i.e. if cropping the width,
# take all of the crop off the left side, and if cropping the height
# take none from the top, and therefore all off the bottom).
# @return An image.
def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
"""
This method returns a sized and cropped version of the image,
cropped to the aspect ratio and size that you request.
Returns a sized and cropped version of the image, cropped to the
requested aspect ratio and size.
This function was contributed by Kevin Cazabon.
:param size: The requested output size in pixels, given as a
(width, height) tuple.
:param method: What resampling method to use. Default is
:py:attr:`PIL.Image.NEAREST`.
:param bleed: Remove a border around the outside of the image (from all
four edges. The value is a decimal percentage (use 0.01 for
one percent). The default value is 0 (no border).
:param centering: Control the cropping position. Use (0.5, 0.5) for
center cropping (e.g. if cropping the width, take 50% off
of the left side, and therefore 50% off the right side).
(0.0, 0.0) will crop from the top left corner (i.e. if
cropping the width, take all of the crop off of the right
side, and if cropping the height, take all of it off the
bottom). (1.0, 0.0) will crop from the bottom left
corner, etc. (i.e. if cropping the width, take all of the
crop off the left side, and if cropping the height take
none from the top, and therefore all off the bottom).
:return: An image.
"""
# by Kevin Cazabon, Feb 17/2000
@ -336,73 +329,73 @@ def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
# resize the image and return it
return out.resize(size, method)
##
# Flip the image vertically (top to bottom).
#
# @param image The image to flip.
# @return An image.
def flip(image):
"Flip image vertically"
"""
Flip the image vertically (top to bottom).
:param image: The image to flip.
:return: An image.
"""
return image.transpose(Image.FLIP_TOP_BOTTOM)
##
# Convert the image to grayscale.
#
# @param image The image to convert.
# @return An image.
def grayscale(image):
"Convert to grayscale"
"""
Convert the image to grayscale.
:param image: The image to convert.
:return: An image.
"""
return image.convert("L")
##
# Invert (negate) the image.
#
# @param image The image to invert.
# @return An image.
def invert(image):
"Invert image (negate)"
"""
Invert (negate) the image.
:param image: The image to invert.
:return: An image.
"""
lut = []
for i in range(256):
lut.append(255-i)
return _lut(image, lut)
##
# Flip image horizontally (left to right).
#
# @param image The image to mirror.
# @return An image.
def mirror(image):
"Flip image horizontally"
"""
Flip image horizontally (left to right).
:param image: The image to mirror.
:return: An image.
"""
return image.transpose(Image.FLIP_LEFT_RIGHT)
##
# Reduce the number of bits for each colour channel.
#
# @param image The image to posterize.
# @param bits The number of bits to keep for each channel (1-8).
# @return An image.
def posterize(image, bits):
"Reduce the number of bits per color channel"
"""
Reduce the number of bits for each color channel.
:param image: The image to posterize.
:param bits: The number of bits to keep for each channel (1-8).
:return: An image.
"""
lut = []
mask = ~(2**(8-bits)-1)
for i in range(256):
lut.append(i & mask)
return _lut(image, lut)
##
# Invert all pixel values above a threshold.
#
# @param image The image to posterize.
# @param threshold All pixels above this greyscale level are inverted.
# @return An image.
def solarize(image, threshold=128):
"Invert all values above threshold"
"""
Invert all pixel values above a threshold.
:param image: The image to posterize.
:param threshold: All pixels above this greyscale level are inverted.
:return: An image.
"""
lut = []
for i in range(256):
if i < threshold:

View File

@ -68,6 +68,7 @@ can be found here.
:undoc-members:
:show-inheritance:
.. intentionally skipped documenting this because it's not documented anywhere
:mod:`ImageDraw2` Module
------------------------
@ -76,22 +77,7 @@ can be found here.
:undoc-members:
:show-inheritance:
:mod:`ImageEnhance` Module
--------------------------
.. automodule:: PIL.ImageEnhance
:members:
:undoc-members:
:show-inheritance:
:mod:`ImageFile` Module
-----------------------
.. automodule:: PIL.ImageFile
:members:
:undoc-members:
:show-inheritance:
.. intentionally skipped documenting this because it's deprecated
:mod:`ImageFileIO` Module
-------------------------
@ -100,46 +86,6 @@ can be found here.
:undoc-members:
:show-inheritance:
:mod:`ImageFilter` Module
-------------------------
.. automodule:: PIL.ImageFilter
:members:
:undoc-members:
:show-inheritance:
:mod:`ImageFont` Module
-----------------------
.. automodule:: PIL.ImageFont
:members:
:undoc-members:
:show-inheritance:
:mod:`ImageMath` Module
-----------------------
.. automodule:: PIL.ImageMath
:members:
:undoc-members:
:show-inheritance:
:mod:`ImageMode` Module
-----------------------
.. automodule:: PIL.ImageMode
:members:
:undoc-members:
:show-inheritance:
:mod:`ImageOps` Module
----------------------
.. automodule:: PIL.ImageOps
:members:
:undoc-members:
:show-inheritance:
:mod:`ImagePalette` Module
--------------------------

View File

@ -1,8 +1,8 @@
.. py:module:: PIL.Image
.. py:currentmodule:: PIL.Image
:mod:`Image` Module
===================
:py:mod:`Image` Module
======================
The :py:mod:`~PIL.Image` module provides a class with the same name which is
used to represent a PIL image. The module also provides a number of factory

View File

@ -1,8 +1,8 @@
.. py:module:: PIL.ImageChops
.. py:currentmodule:: PIL.ImageChops
:mod:`ImageChops` Module
========================
:py:mod:`ImageChops` Module
===========================
The :py:mod:`ImageChops` module contains a number of arithmetical image
operations, called channel operations (“chops”). These can be used for various

View File

@ -1,8 +1,8 @@
.. py:module:: PIL.ImageColor
.. py:currentmodule:: PIL.ImageColor
:mod:`ImageColor` Module
========================
:py:mod:`ImageColor` Module
===========================
The :py:mod:`ImageColor` module contains color tables and converters from
CSS3-style color specifiers to RGB tuples. This module is used by

View File

@ -1,8 +1,8 @@
.. py:module:: PIL.ImageDraw
.. py:currentmodule:: PIL.ImageDraw
:mod:`ImageDraw` Module
=======================
:py:mod:`ImageDraw` Module
==========================
The :py:mod:`ImageDraw` module provide simple 2D graphics for
:py:class:`~PIL.Image.Image` objects. You can use this module to create new
@ -18,7 +18,7 @@ Example: Draw a gray cross over an image
.. code-block:: python
import Image, ImageDraw
from PIL import Image, ImageDraw
im = Image.open("lena.pgm")

View File

@ -0,0 +1,38 @@
.. py:module:: PIL.ImageEnhance
.. py:currentmodule:: PIL.ImageEnhance
:py:mod:`ImageEnhance` Module
=============================
The :py:mod:`ImageEnhance` module contains a number of classes that can be used
for image enhancement.
Example: Vary the sharpness of an image
---------------------------------------
.. code-block:: python
from PIL import ImageEnhance
enhancer = ImageEnhance.Sharpness(image)
for i in range(8):
factor = i / 4.0
enhancer.enhance(factor).show("Sharpness %f" % factor)
Also see the :file:`enhancer.py` demo program in the :file:`Scripts/`
directory.
Classes
-------
All enhancement classes implement a common interface, containing a single
method:
.. autoclass:: PIL.ImageEnhance._Enhance
:members:
.. autoclass:: PIL.ImageEnhance.Color
.. autoclass:: PIL.ImageEnhance.Contrast
.. autoclass:: PIL.ImageEnhance.Brightness
.. autoclass:: PIL.ImageEnhance.Sharpness

View File

@ -0,0 +1,41 @@
.. py:module:: PIL.ImageFile
.. py:currentmodule:: PIL.ImageFile
:py:mod:`ImageFile` Module
==========================
The :py:mod:`ImageFile` module provides support functions for the image open
and save functions.
In addition, it provides a :py:class:`Parser` class which can be used to decode
an image piece by piece (e.g. while receiving it over a network connection).
This class implements the same consumer interface as the standard **sgmllib**
and **xmllib** modules.
Example: Parse an image
-----------------------
.. code-block:: python
from PIL import ImageFile
fp = open("lena.pgm", "rb")
p = ImageFile.Parser()
while 1:
s = fp.read(1024)
if not s:
break
p.feed(s)
im = p.close()
im.save("copy.jpg")
:py:class:`~PIL.ImageFile.Parser`
---------------------------------
.. autoclass:: PIL.ImageFile.Parser()
:members:

View File

@ -0,0 +1,47 @@
.. py:module:: PIL.ImageFilter
.. py:currentmodule:: PIL.ImageFilter
:py:mod:`ImageFilter` Module
============================
The :py:mod:`ImageFilter` module contains definitions for a pre-defined set of
filters, which can be be used with the :py:meth:`Image.filter()
<PIL.Image.Image.filter>` method.
Example: Filter an image
------------------------
.. code-block:: python
from PIL import ImageFilter
im1 = im.filter(ImageFilter.BLUR)
im2 = im.filter(ImageFilter.MinFilter(3))
im3 = im.filter(ImageFilter.MinFilter) # same as MinFilter(3)
Filters
-------
The current version of the library provides the following set of predefined
image enhancement filters:
* **BLUR**
* **CONTOUR**
* **DETAIL**
* **EDGE_ENHANCE**
* **EDGE_ENHANCE_MORE**
* **EMBOSS**
* **FIND_EDGES**
* **SMOOTH**
* **SMOOTH_MORE**
* **SHARPEN**
.. autoclass:: PIL.ImageFilter.GaussianBlur
.. autoclass:: PIL.ImageFilter.UnsharpMask
.. autoclass:: PIL.ImageFilter.Kernel
.. autoclass:: PIL.ImageFilter.RankFilter
.. autoclass:: PIL.ImageFilter.MedianFilter
.. autoclass:: PIL.ImageFilter.MinFilter
.. autoclass:: PIL.ImageFilter.MaxFilter
.. autoclass:: PIL.ImageFilter.ModeFilter

View File

@ -0,0 +1,69 @@
.. py:module:: PIL.ImageFont
.. py:currentmodule:: PIL.ImageFont
:py:mod:`ImageFont` Module
==========================
The :py:mod:`ImageFont` module defines a class with the same name. Instances of
this class store bitmap fonts, and are used with the
:py:meth:`PIL.ImageDraw.Draw.text` method.
PIL uses its own font file format to store bitmap fonts. You can use the
:command`pilfont` utility to convert BDF and PCF font descriptors (X window
font formats) to this format.
Starting with version 1.1.4, PIL can be configured to support TrueType and
OpenType fonts (as well as other font formats supported by the FreeType
library). For earlier versions, TrueType support is only available as part of
the imToolkit package
Example
-------
.. code-block:: python
from PIL import ImageFont, ImageDraw
draw = ImageDraw.Draw(image)
# use a bitmap font
font = ImageFont.load("arial.pil")
draw.text((10, 10), "hello", font=font)
# use a truetype font
font = ImageFont.truetype("arial.ttf", 15)
draw.text((10, 25), "world", font=font)
Functions
---------
.. autofunction:: PIL.ImageFont.load
.. autofunction:: PIL.ImageFont.load_path
.. autofunction:: PIL.ImageFont.truetype
.. autofunction:: PIL.ImageFont.load_default
Methods
-------
.. py:method:: PIL.ImageFont.ImageFont.getsize(text)
:return: (width, height)
.. py:method:: PIL.ImageFont.ImageFont.getmask(text, mode='')
Create a bitmap for the text.
If the font uses antialiasing, the bitmap should have mode “L” and use a
maximum value of 255. Otherwise, it should have mode “1”.
:param text: Text to render.
:param mode: Used by some graphics drivers to indicate what mode the
driver prefers; if empty, the renderer may return either
mode. Note that the mode is always a string, to simplify
C-level implementations.
.. versionadded:: 1.1.5
:return: An internal PIL storage memory instance as defined by the
:py:mod:`PIL.Image.core` interface module.

View File

@ -0,0 +1,33 @@
.. py:module:: PIL.ImageGrab
.. py:currentmodule:: PIL.ImageGrab
:py:mod:`ImageGrab` Module (Windows-only)
=========================================
The :py:mod:`ImageGrab` module can be used to copy the contents of the screen
or the clipboard to a PIL image memory.
.. note:: The current version works on Windows only.
.. versionadded:: 1.1.3
.. py:function:: PIL.ImageGrab.grab(bbox=None)
Take a snapshot of the screen. The pixels inside the bounding box are
returned as an "RGB" image. If the bounding box is omitted, the entire
screen is copied.
.. versionadded:: 1.1.3
:param bbox: What region to copy. Default is the entire screen.
:return: An image
.. py:function:: PIL.ImageGrab.grabclipboard()
Take a snapshot of the clipboard image, if any.
.. versionadded:: 1.1.4
:return: An image, a list of filenames, or None if the clipboard does
not contain image data or filenames. Note that if a list is
returned, the filenames may not represent image files.

View File

@ -0,0 +1,127 @@
.. py:module:: PIL.ImageMath
.. py:currentmodule:: PIL.ImageMath
:py:mod:`ImageMath` Module
==========================
The :py:mod:`ImageMath` module can be used to evaluate “image expressions”. The
module provides a single eval function, which takes an expression string and
one or more images.
Example: Using the :py:mod:`~PIL.ImageMath` module
--------------------------------------------------
.. code-block:: python
import Image, ImageMath
im1 = Image.open("image1.jpg")
im2 = Image.open("image2.jpg")
out = ImageMath.eval("convert(min(a, b), 'L')", a=im1, b=im2)
out.save("result.png")
.. py:function:: eval(expression, environment)
Evaluate expression in the given environment.
In the current version, :py:mod:`~PIL.ImageMath` only supports
single-layer images. To process multi-band images, use the
:py:meth:`~PIL.Image.Image.split` method or :py:func:`~PIL.Image.merge`
function.
:param expression: A string which uses the standard Python expression
syntax. In addition to the standard operators, you can
also use the functions described below.
:param environment: A dictionary that maps image names to Image instances.
You can use one or more keyword arguments instead of a
dictionary, as shown in the above example. Note that
the names must be valid Python identifiers.
:return: An image, an integer value, a floating point value,
or a pixel tuple, depending on the expression.
Expression syntax
-----------------
Expressions are standard Python expressions, but theyre evaluated in a
non-standard environment. You can use PIL methods as usual, plus the following
set of operators and functions:
Standard Operators
^^^^^^^^^^^^^^^^^^
You can use standard arithmetical operators for addition (+), subtraction (-),
multiplication (*), and division (/).
The module also supports unary minus (-), modulo (%), and power (**) operators.
Note that all operations are done with 32-bit integers or 32-bit floating
point values, as necessary. For example, if you add two 8-bit images, the
result will be a 32-bit integer image. If you add a floating point constant to
an 8-bit image, the result will be a 32-bit floating point image.
You can force conversion using the :py:func:`~PIL.ImageMath.convert`,
:py:func:`~PIL.ImageMath.float`, and :py:func:`~PIL.ImageMath.int` functions
described below.
Bitwise Operators
^^^^^^^^^^^^^^^^^
The module also provides operations that operate on individual bits. This
includes and (&), or (|), and exclusive or (^). You can also invert (~) all
pixel bits.
Note that the operands are converted to 32-bit signed integers before the
bitwise operation is applied. This means that youll get negative values if
you invert an ordinary greyscale image. You can use the and (&) operator to
mask off unwanted bits.
Bitwise operators dont work on floating point images.
Logical Operators
^^^^^^^^^^^^^^^^^
Logical operators like :keyword:`and`, :keyword:`or`, and :keyword:`not` work
on entire images, rather than individual pixels.
An empty image (all pixels zero) is treated as false. All other images are
treated as true.
Note that :keyword:`and` and :keyword:`or` return the last evaluated operand,
while not always returns a boolean value.
Built-in Functions
^^^^^^^^^^^^^^^^^^
These functions are applied to each individual pixel.
.. py:currentmodule:: None
.. py:function:: abs(image)
Absolute value.
.. py:function:: convert(image, mode)
Convert image to the given mode. The mode must be given as a string
constant.
.. py:function:: float(image)
Convert image to 32-bit floating point. This is equivalent to
convert(image, “F”).
.. py:function:: int(image)
Convert image to 32-bit integer. This is equivalent to convert(image, “I”).
Note that 1-bit and 8-bit images are automatically converted to 32-bit
integers if necessary to get a correct result.
.. py:function:: max(image1, image2)
Maximum value.
.. py:function:: min(image1, image2)
Minimum value.

View File

@ -0,0 +1,27 @@
.. py:module:: PIL.ImageOps
.. py:currentmodule:: PIL.ImageOps
:py:mod:`ImageOps` Module
==========================
The :py:mod:`ImageOps` module contains a number of ready-made image
processing operations. This module is somewhat experimental, and most operators
only work on L and RGB images.
Only bug fixes have been added since the Pillow fork.
.. versionadded:: 1.1.3
.. autofunction:: autocontrast
.. autofunction:: colorize
.. autofunction:: crop
.. autofunction:: deform
.. autofunction:: equalize
.. autofunction:: expand
.. autofunction:: fit
.. autofunction:: flip
.. autofunction:: grayscale
.. autofunction:: invert
.. autofunction:: mirror
.. autofunction:: posterize
.. autofunction:: solarize

View File

@ -8,4 +8,11 @@ Reference
ImageChops
ImageColor
ImageDraw
ImageEnhance
ImageFile
ImageFilter
ImageFont
ImageGrab
ImageMath
ImageOps
../PIL