Goulib.image module

image processing with PIL’s ease and skimage’s power

requires:
optional:
class Goulib.image.Mode(name, nchannels, type, min, max)[source]

Bases: object

__init__(name, nchannels, type, min, max)[source]

Initialize self. See help(type(self)) for accurate signature.

__repr__()[source]

Return repr(self).

__class__

alias of builtins.type

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init_subclass__()

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__le__

Return self<=value.

__lt__

Return self<value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

Goulib.image.nchannels(arr)[source]
Goulib.image.guessmode(arr)[source]
Goulib.image.adapt_rgb(func)[source]

Decorator that adapts to RGB(A) images to a gray-scale filter. :param apply_to_rgb: function

Function that returns a filtered image from an image-filter and RGB image. This will only be called if the image is RGB-like.
class Goulib.image.Image(data=None, mode=None, **kwargs)[source]

Bases: Goulib.plot.Plot

Parameters:data – can be either:
  • PIL.Image : makes a copy
  • string : path of image to load OR PNG encoded image
  • memoryview (extracted from a db blob)
  • None : creates an empty image with kwargs parameters:

** size : (y,x) pixel size tuple ** mode : ‘F’ (gray) by default ** color: to fill None=black by default ** colormap: Palette or matplotlib colormap

__init__(data=None, mode=None, **kwargs)[source]
Parameters:data – can be either:
  • PIL.Image : makes a copy
  • string : path of image to load OR PNG encoded image
  • memoryview (extracted from a db blob)
  • None : creates an empty image with kwargs parameters:

** size : (y,x) pixel size tuple ** mode : ‘F’ (gray) by default ** color: to fill None=black by default ** colormap: Palette or matplotlib colormap

shape
size
width
height
nchannels
npixels
__nonzero__()[source]
__lt__(other)[source]

is smaller

load(path)[source]
save(path, autoconvert=True, **kwargs)[source]

saves an image :param path: string with path/filename.ext :param autoconvert: bool, if True converts color planes formats to RGB :param kwargs: optional params passed to skimage.io.imsave: :return: self for chaining

render(fmt='png', **kwargs)[source]
static open(path)[source]

PIL(low) compatibility

static new(mode, size, color='black')[source]

PIL(low) compatibility

pil

convert to PIL(low) Image :see: http://effbot.org/imagingbook/concepts.htm

getdata(dtype=<class 'numpy.uint8'>, copy=True)[source]
split(mode=None)[source]
getpixel(yx)[source]
putpixel(yx, value)[source]
getpalette(maxcolors=256)[source]
setpalette(p)[source]
getcolors(maxcolors=256)[source]
Returns:an unsorted list of (count, color) tuples,

where count is the number of times the corresponding color occurs in the image. If the maxcolors value is exceeded, the method stops counting and returns None. The default maxcolors value is 256. To make sure you get all colors in an image, you can pass in size[0]*size[1] (but make sure you have lots of memory before you do that on huge images).

replace(pairs)[source]

replace a color by another currently works only for indexed color images :param pairs: iterable of (from,to) ints

optimize(maxcolors=256)[source]

remove unused colors from the palette

crop(lurb)[source]
Parameters:lurl – 4-tuple with left,up,right,bottom int coordinates
Returns:Image
__getitem__(slice)[source]
ratio
resize(size, filter=2, **kwargs)[source]

Resize image

Returns:

a resized copy of image.

Parameters:
  • size – int tuple (width, height) requested size in pixels
  • filter
    • NEAREST (use nearest neighbour),
    • BILINEAR (linear interpolation in a 2x2 environment),
    • BICUBIC (cubic spline interpolation in a 4x4 environment)
    • ANTIALIAS (a high-quality downsampling filter)
  • kwargs – extra parameters passed to skimage.transform.resize
rotate(angle, **kwargs)[source]

Rotate image

Returns:

a rotated copy of image.

Parameters:
  • angle – float rotation angle in degrees in counter-clockwork direction
  • kwargs – extra parameters passed to skimage.transform.rotate
flip(flipx=True, flipy=False)[source]

Flip image

Returns:

a flipped copy of image.

Parameters:
  • flipx – bool flip X direction
  • flipy – bool flip Y direction
  • kwargs – extra parameters passed to skimage.transform.rotate
paste(image, box=None, mask=None)[source]

Pastes another image into this image.

Parameters:
  • image – image to paste, or color given as a single numerical value for single-band images, and a tuple for multi-band images.
  • box – 2-tuple giving the upper left corner or 4-tuple defining the left, upper, right, and lower pixel coordinate, or None (same as (0, 0)). If a 4-tuple is given, the size of the pasted image must match the size of the region.
:param mask:optional image to update only the regions indicated by the mask.
You can use either “1”, “L” or “RGBA” images (in the latter case, the alpha band is used as mask). Where the mask is 255, the given image is copied as is. Where the mask is 0, the current value is preserved. Intermediate values can be used for transparency effects. Note that if you paste an “RGBA” image, the alpha band is ignored. You can work around this by using the same image as both source image and mask.
threshold(level=None)[source]
quantize(colors=256, method=None, kmeans=0, palette=None)[source]

(PIL.Image compatible) Convert the image to ‘P’ mode with the specified number of colors. :param colors: The desired number of colors, <= 256 :param method: 0 = median cut

1 = maximum coverage 2 = fast octree 3 = libimagequant
Parameters:
  • kmeans – Integer
  • palette – Quantize to the PIL.ImagingPalette palette.
Returns:

A new image

convert(mode, **kwargs)[source]

convert image mode :param mode: string destination mode :param kwargs: optional params passed to converter(s). can contain: * palette : to force using a palette instead of the image’s one for indexed images :return: image in desired mode

__repr__()[source]

Return repr(self).

average_hash(hash_size=8)[source]

Average Hash

See:http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
Parameters:hash_size – int sqrt of the hash size. 8 (64 bits) is perfect for usual photos
Returns:int of hash_size**2 bits
perceptual_hash(hash_size=8, highfreq_factor=4)[source]

Perceptual Hash

See:http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
Parameters:hash_size – int sqrt of the hash size. 8 (64 bits) is perfect for usual photos
Returns:int of hash_size**2 bits
dist(other, method=0, hash_size=8, symmetries=False)[source]

distance between images

Parameters:hash_size – int sqrt of the hash size. 8 (64 bits) is perfect for usual photos
Returns:float =0 if images are equal or very similar (same average_hash) =1 if images are completely decorrelated (half of the hash bits are the same by luck) =2 if images are inverted
__hash__()[source]

Return hash(self).

__abs__()[source]
Returns:float Frobenius norm of image
invert()[source]
__neg__()
__inv__()
grayscale(mode=None)[source]

convert (color) to grayscale :param mode: string target mode (should be in ‘FUIL’) or automatic if none

colorize(color0, color1=None)[source]

colorize a grayscale image

Parameters:color0,color1 – 2 colors. - If only one is specified, image is colorized from white (for 0) to the specified color (for 1) - if 2 colors are specified, image is colorized from color0 (for 0) to color1 (for 1)
Returns:RGB(A) color
dither(method=None, n=2)[source]
normalize(newmax=None, newmin=None)[source]
filter(f)[source]
correlation(other)[source]

Compute the correlation between two, single-channel, grayscale input images. The second image must be smaller than the first. :param other: the Image we’re looking for

scale(s)[source]

resize image by factor s

Parameters:s – (sx, sy) tuple of float scaling factor, or scalar s=sx=sy
Returns:Image scaled
shift(dx, dy, **kwargs)[source]
expand(size, ox=None, oy=None)[source]
Returns:image in larger canvas size, pasted at ox,oy
compose(other, a=0.5, b=0.5, mode=None)[source]

compose new image from a*self + b*other

add(other, pos=(0, 0), alpha=1, mode=None)[source]

simply adds other image at px,py (subbixel) coordinates

__add__(other)[source]
__radd__(other)[source]

only to allow sum(images) easily

sub(other, pos=(0, 0), alpha=1, mode=None)[source]
__sub__(other)[source]
deltaE(other)[source]
__mul__(other)[source]
__div__(f)[source]
__truediv__(f)
__class__

alias of builtins.type

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__init_subclass__()

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__le__

Return self<=value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

html(**kwargs)
plot(**kwargs)

renders on IPython Notebook (alias to make usage more straightforward)

png(**kwargs)
svg(**kwargs)
Goulib.image.alpha_composite(front, back)[source]

Alpha composite two RGBA images.

Source: http://stackoverflow.com/a/9166671/284318

Keyword Arguments: front – PIL RGBA Image object back – PIL RGBA Image object

The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing

Goulib.image.alpha_composite_with_color(image, color=(255, 255, 255))[source]

Alpha composite an RGBA image with a single color image of the specified color and the same size as the original image.

Keyword Arguments: image – PIL RGBA Image object color – Tuple r, g, b (default 255, 255, 255)

Goulib.image.pure_pil_alpha_to_color_v1(image, color=(255, 255, 255))[source]

Alpha composite an RGBA Image with a specified color.

NOTE: This version is much slower than the alpha_composite_with_color solution. Use it only if numpy is not available.

Source: http://stackoverflow.com/a/9168169/284318

Keyword Arguments: image – PIL RGBA Image object color – Tuple r, g, b (default 255, 255, 255)

Goulib.image.pure_pil_alpha_to_color_v2(image, color=(255, 255, 255))[source]

Alpha composite an RGBA Image with a specified color.

Simpler, faster version than the solutions above.

Source: http://stackoverflow.com/a/9459208/284318

Keyword Arguments: image – PIL RGBA Image object color – Tuple r, g, b (default 255, 255, 255)

Goulib.image.disk(radius, antialias=1)[source]
Goulib.image.fspecial(name, **kwargs)[source]

mimics the Matlab image toolbox fspecial function http://www.mathworks.com/help/images/ref/fspecial.html?refresh=true

Goulib.image.normalize(a, newmax=255, newmin=0)[source]
Goulib.image.read_pdf(path, **kwargs)[source]

reads a bitmap graphics on a .pdf file

Parameters:
  • path – string path
  • kwargs – params passed to Drawing.draw in case the .pdf contains only vector graphics
Returns:

Image

Goulib.image.fig2img(fig)[source]

Convert a Matplotlib figure to a PIL Image in RGBA format and return it

Parameters:fig – matplotlib figure
Returns:PIL image
Goulib.image.quantize(image, N=2, L=None)[source]

Quantize a gray image. :param image: ndarray input image. :param N: int number of quantization levels. :param L: float max value.

Goulib.image.randomize(image, N=2, L=None)[source]
class Goulib.image.Ditherer(name, method)[source]

Bases: object

__init__(name, method)[source]

Initialize self. See help(type(self)) for accurate signature.

__call__(image, N=2)[source]

Call self as a function.

__repr__()[source]

Return repr(self).

__class__

alias of builtins.type

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init_subclass__()

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__le__

Return self<=value.

__lt__

Return self<value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

class Goulib.image.ErrorDiffusion(name, positions, weights, wsum=None)[source]

Bases: Goulib.image.Ditherer

__init__(name, positions, weights, wsum=None)[source]

Initialize self. See help(type(self)) for accurate signature.

__call__(image, N=2)[source]

Call self as a function.

__class__

alias of builtins.type

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init_subclass__()

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__le__

Return self<=value.

__lt__

Return self<value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

class Goulib.image.FloydSteinberg[source]

Bases: Goulib.image.ErrorDiffusion

__init__()[source]

Initialize self. See help(type(self)) for accurate signature.

__call__(image, N=2)[source]

Call self as a function.

__class__

alias of builtins.type

__delattr__

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__

Return self==value.

__format__()

Default object formatter.

__ge__

Return self>=value.

__getattribute__

Return getattr(self, name).

__gt__

Return self>value.

__hash__

Return hash(self).

__init_subclass__()

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__le__

Return self<=value.

__lt__

Return self<value.

__ne__

Return self!=value.

__new__()

Create and return a new object. See help(type) for accurate signature.

__reduce__()

Helper for pickle.

__reduce_ex__()

Helper for pickle.

__repr__()

Return repr(self).

__setattr__

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__

Return str(self).

Goulib.image.dither(image, method=3, N=2)[source]

Quantize a gray image, using dithering. :param image: ndarray input image. :param method: key in dithering dict :param N: int number of quantization levels. References ———- http://www.efg2.com/Lab/Library/ImageProcessing/DHALF.TXT

Goulib.image.gray2bool(image, method=3, N=2)

Quantize a gray image, using dithering. :param image: ndarray input image. :param method: key in dithering dict :param N: int number of quantization levels. References ———- http://www.efg2.com/Lab/Library/ImageProcessing/DHALF.TXT

Goulib.image.rgb2cmyk(rgb)[source]
Goulib.image.cmyk2rgb(cmyk)[source]
Goulib.image.gray2rgb(im, color0=(0, 0, 0), color1=(1, 1, 1))[source]
Goulib.image.bool2rgb(im, color0=(0, 0, 0), color1=(1, 1, 1))
Goulib.image.bool2gray(im)[source]
Goulib.image.rgb2rgba(array)[source]
Goulib.image.palette(im, ncolors, tol=0.01)[source]

extract the color palette of image array (in its own colorspace. use Lab for best results) :param im: nparray (x,y,n) containing image :param ncolors: int number of colors :param tol: tolerance for precision/speed compromise. 1/100 means about 100 points per color are taken for kmeans segmentation :return: array of ncolors most used in image (center of kmeans centroids)

Goulib.image.lab2ind(im, colors=256)[source]

convert a Lab image to indexed colors :param a: nparray (x,y,n) containing image :param colors: int number of colors or predefined Palette :ref: http://scikit-learn.org/stable/auto_examples/cluster/plot_color_quantization.html

Goulib.image.ind2any(im, palette, dest)[source]
Goulib.image.ind2rgb(im, palette)[source]
Goulib.image.convert(a, source, target, **kwargs)[source]

convert an image between modes, eventually using intermediary steps :param a: nparray (x,y,n) containing image :param source: string : key of source image mode in modes :param target: string : key of target image mode in modes