From VipsWiki
Jump to: navigation, search


VIPS has two Python interfaces. There's an older vips7 interface which is now deprecated, and a fancy new one based on pygobject. It works with python2.7 and python3.4 (and probably others) on Linux, OS X and Windows. There's a section in the libvips manual about it, with notes on installing and running it.

The usual Python imaging library is PIL. See the Speed and Memory Use page for details, but on that benchmark at least, VIPS is 5 times faster and needs only 10% of the memory to run.


This example loads an image, crops 100 pixels off every edge, shrinks by 10%, sharpens, and saves again.


import sys

from gi.repository import Vips

im = Vips.Image.new_from_file(sys.argv[1])

im = im.extract_area(100, 100, im.width - 200, im.height - 200)
im = im.similarity(scale = 0.9)
mask = Vips.Image.new_from_array([[-1, -1,  -1], 
                                  [-1, 16,  -1], 
                                  [-1, -1,  -1]], scale = 8)
im = im.conv(mask)


Reading this example, the first line loads the input file. You can append load options to the argument list as keyword arguments, for example:

im = Vips.Image.new_from_file(sys.argv[1], access = Vips.Access.SEQUENTIAL)

See the various loaders for a list of the available options for each file format. The C equivalent to this function, vips_image_new_from_file(), has more extensive documentation. Try help(Vips.Image) to see a list of all the image constructors --- you can load from memory, or create from an array, for example.

The next line crops 100 pixels off every edge. Try help(im.extract_area) and the C API docs for vips_extract_area() for details. You can use .crop() as a synonym, if you like. im.width gets the image width in pixels, see help(Vips.Image) and vips_image_get_width() and friends for a list of the other getters.

The similarity line shrinks by 10%. By default it uses bilinear interpolation, use interpolate to pick another interpolator, for example:

im = im.similarity(scale = 0.9, interpolate ="bicubic"))

.new_from_array() makes an image from a 2D array. The scale keyword argument lets you set a divisor for convolution, handy for integer convolutions. You can set offset as well. See vips_conv() for details on the vips convolution operator.

Finally, .write_to_file() sends the image back to the filesystem. There's also .write_to_buffer() to make a string containing the formatted image, and .write() to write to another image.