pystacia.image

pystacia.image.read(filename, factory=None)

Read Image from filename.

Parameters:
  • filename (str) – file name to read
  • factory – Image subclass to use when instantiating objects
Return type:

Image

Reads file, determines its format and returns an Image representing it. You can optionally pass factory parameter to use alternative Image subclass.

>>> read('example.jpg')
<Image(w=512,h=512,8bit,rgb,truecolor) object at 0x10302ee00L>
pystacia.image.read_blob(blob, format=None, length=None, factory=None)

Read Image from a blob string or stream with a header.

Parameters:
  • blob (str (Python 2.x) / bytes (Python 3.x) or file-like object) – blob data string or stream
  • format (str) – container format such as JPEG or BMP
  • length (int) – read maximum this bytes from stream
  • factory – Image subclass to use when instantiating objects
Return type:

Image

Reads image from string or data stream that contains a valid file header i.e. it carries information on image dimensions, bit depth and compression. Data format is equivalent to e.g. JPEG file read into string(Python 2.x)/bytes(Python 3.x) or file-like object. It is useful in cases when you have open file-like object but not the file itself in the file system. That often happens in web applications which map POST data with file-like objects. Format and length are typically not used but can be a hint when the information cannot be guessed from the data itself. You can optionally pass factory parameter to use alternative Image subclass.

>>> with file('example.jpg') as f:
...     img = read_blob(f)
>>> img
<Image(w=512,h=512,8bit,rgb,truecolor) object at 0x10302ee00L>
pystacia.image.read_raw(raw, format, width, height, depth, factory=None)

Read Image from raw string or stream.

Parameters:
  • raw (str (Python 2.x) / bytes (Python 3.x) or file-like object) – raw data string or stream
  • format (str) – raw pixel format eg. 'RGB'
  • width (int) – width of image in raw data
  • height (int) – height of image in raw data
  • depth (int) – depth of a single channel in bits
  • factory – Image subclass to use when instantiating objects
Return type:

Image

Reads image data from a raw string or stream containing data in format such as RGB or YCbCr. The contained image has dimensions of width and height pixels. Each channel is of depth bits. You can optionally pass factory parameter to use alternative Image subclass.

>>> img = read_raw(b'raw triplets', 'rgb', 1, 1, 8)
pystacia.image.blank(width, height, background=None, factory=None)

Create Image with monolithic background

Parameters:
  • width (int) – Width in pixels
  • height (int) – Height in pixels
  • background (pystacia.Color) – background color, defaults to fully transparent

Creates blank image of given dimensions filled with background color.

>>> from pystacia.image import color
>>> blank(32, 32, color.from_string('red'))
<Image(w=32,h=32,16bit,rgb,palette) object at 0x108006000L>

The Image class

class pystacia.image.Image(resource=None)
adaptive_blur(radius, strength=None, bias=None)

Adaptively blur an image

Parameters:radius (float) – radius in pixels

Applies adaptive blur of given radius to an image.

This method can be chained.

adaptive_sharpen(radius, strength=None, bias=None)

Adaptive sharpen an image

Parameters:radius (float) – radius in pixels

Applies adaptive sharpening to an image.

This method can be chained.

add_noise(attenuate=0, noise_type=None)

Add noise to an image.

Parameters:
  • attenuate (float) – Attenuation factor
  • noise_type – values representing

pystacia.image.enum.noises

Adds noise of given type to an image. Noise type defaults to "gaussian".

This method can be chained.

auto_gamma()

Auto-gamma image.

Extracts the ‘mean’ from the image and adjust the image to try make set its gamma appropriately.

This method can be chained.

auto_level()

Auto-level image.

Adjusts the levels of an image by scaling the minimum and maximum values to the full quantum range.

This method can be chained.

blur(radius, strength=None)

Blur image.

Parameters:
  • radius (float) – Gaussian operator radius
  • strength (float) – Standard deviation (sigma)

Convolves the image with a Gaussian operator of the given radius and standard deviation (strength).

This method can be chained.

brightness(factor)

Brightens an image.

Parameters:factor (float) – Brightness factor between -1 and 1

Brightens an image with specified factor. Factor of 0 is no-change operation. Values towards -1 make image darker. -1 makes image completely black. Values towards 1 make image brigther. 1 makes image completely white.

This method can be chained.

charcoal(radius, strength=None, bias=None)

Simulate a charcoal.

Parameters:radius (float) – Charcoal radius

This method can be chained.

checkerboard()

Fills transparent pixels with checkerboard.

Useful for presentation when you want to explicitly mark transparent pixels when otherwise it might be unclear where they are.

colorize(color)

Colorize image.

Parameters:color (pystacia.color.Color) – color from which hue value is used

Colorizes image resulting in image containing only one hue value.

This method can be chained.

colorspace

Return or set colorspace associated with image.

Sets or gets colorspace. When you set this property there’s no colorspace conversion performed and the original channel values are just left as is. If you actually want to perform a conversion use convert_colorspace instead. Popular colorspace include RGB, YCbCr, grayscale and so on.

Return type:pystacia.lazyenum.EnumValue
compare(image, metric=None, factory=None)

Compare image to another image

Parameters:
  • image (pystacia.image.Image) – reference image
  • metric (pystacia.lazyenum.EnumValue) – distortion metric
  • factory – factory to be used to create difference image
Return type:

tuple of Image and float distortion in given metric

Compares two images of the same sizes. Returns a tuple of an image marking different parts with red color and a distortion metric. By default it uses pystacia.image.metrics.absolute_error metric. If images are of different sizes returns False instead.

contrast(factor)

Change image contrast.

Parameters:factor (float) – Contrast factor between -1 and 1

Change image contrast with specified factor. Factor of 0 is no-change operation. Values towards -1 make image less contrasting. -1 makes image completely gray. Values towards 1 increase image contrast. 1 pulls channel values towards 0 and 1 resulting in a highly contrasting posterized image.

This method can be chained.

contrast_stretch(black=0, white=1)

Stretch image contrast

convert_colorspace(colorspace)

Convert to given colorspace.

Parameters:colorspace (pystacia.color.Color) – destination colorspace

Converts an image to a given colorspace.

>>> img = read('example.jpg')
>>> img.convert_colorspace(colorspaces.ycbcr)
>>> img.colorspace == colorspaces.ycbcr
True

This method can be chained.

denoise()

Attempt to remove noise preserving edges.

Applies a digital filter that improves the quality of a noisy image.

This method can be chained.

depth

Set or get image depth per channel.

Return type:int

Set or get depth per channel in bits. Either 8 or 16.

desaturate()

Desatures an image.

Reduces saturation level of all pixels to minimum yielding grayscale image.

This method can be chained.

despeckle()

Attempt to remove speckle preserving edges.

Resulting image almost solid color areas are smoothed preserving edges.

This method can be chained.

detect_edges(radius, strength=None)

Detect edges in image.

Parameters:radius (float) – radius of detected edges

Analyzes image and marks contrasting edges. It operates on all channels by default so it might be a good idea to grayscale an image before performing it.

This method can be chained.

emboss(radius=0, strength=None)

Apply edge detecting algorithm.

Parameters:
  • radius (int) – filter radius
  • strength (int) – filter strength (sigma)

On a typical photo creates effect of raised edges.

This method can be chained.

equalize()

Equalize image histogram.

This method usually increases the global contrast of many images, especially when the usable data of the image is represented by close contrast values. Through this adjustment, the intensities can be better distributed on the histogram. This allows for areas of lower local contrast to gain a higher contrast. See also: http://en.wikipedia.org/wiki/Histogram_equalization.

This method can be chained.

evaluate(operation, value)

Apply operation to image color information

Parameters:
  • operation (Enum operations representation) – Operation like “multiply” or “subtract”
  • value (float) – A constant value used as operand

Evaluate each pixel in image with operation and provided value. E.g. using 'divide' operation and 2 as value would result in all pixels divided by two.

fill(fill, blend=1)

Overlay color over whole image.

Parameters:

Overlay a color over whole image. Blend is blending factor of a color with 0 being completely transparent and 1 fully opaque.

This method can be chained.

fit(width=None, height=None, mode=None, upscale=False, filter=None, blur=1)

Fits an image into a rectangle preserving aspect ratio

Parameters:
  • width (int) – width in pixels
  • height (int) – height in pixels

Fits an image into a region of width, and height pixels preserving aspect ratio.

This method can be chained.

flip(axis)

Flip an image along given axis.

Parameters:axis (pystacia.lazyenum.EnumValue) – X or Y axis

Flips (mirrors) an image along axes.x or axes.y.

This method can be chained.

format

Get original image format.

Return type:str

Return format image was originally stored in.

fx(expression)

Perform expression using ImageMagick mini-language.

Parameters:expression – expression to evaluate

For more information on the available expressions visit: http://www.imagemagick.org/script/fx.php.

This method can be chained.

gamma(gamma)

Apply gamma correction to an image.

Parameters:gamma (float) – Gamma value

Apply gamma correction to an image. Value 1 is an identity operation. Higher values yield brighter image and lower values darken image. More information on gamma correction can be found here: http://en.wikipedia.org/wiki/Gamma_correction.

This method can be chained

gaussian_blur(radius, strength=None, bias=None)

Gaussian blur an image

Parameters:radius (float) – radius in pixels

Applies Gaussian blur to an image of given radius.

This method can be chained.

get_blob(format, compression=None, quality=None, factory=None)

Return a blob representing an image

Parameters:
  • format (str) – format of the output such as JPEG
  • compression (pystacia.lazyenum.EnumValue) – compression supported by format
  • quality – output quality
Return type:

str (Python 2.x) / bytes (Python 3.x)

Returns blob carrying data representing an image along its header in the given format. Compression is one of compression algorithms. Some formats like TIFF supports more then one compression algorithms but typically this parameter is not used. The interpretation of quality parameter depends on the chosen format. E.g. for JPEG it’s integer number between 1 (worst) and 100 (best). The default value is to choose best available compression that preserves good quality image. The details are in the ImageMagick documentation <http://www.imagemagick.org/script/ command-line-options.php#quality>.

get_pixel(x, y, factory=None)

Get pixel color at given coordinates.

Parameters:
  • x (int) – x coordinate of pixel
  • y (int) – y coordinate of pixel
Return type:

:color:`pystacia.color.Color`

Reads pixel color at point (x,y).

get_range()

Return range minimum and maximum range of channels

Return type:tuple

Return a range of color information as a tuple of floats between 0 and 1. E.g. black and white image would have a range of 0 for minimum and 1 for maximum 1-color images will have maximum equal to minimum.

get_raw(format, factory=None)

Return dict representing raw image data.

Parameters:format (str) – format of the output such as RGB
Return type:dict

Returns raw data dict consisting of raw, format, width, height and depth keys along their values.

height

Get image height.

Return type:int

Return image height in pixels.

invert(only_gray=False)

Invert image colors.

Inverts all image colors resulting in a negative image.

This method can be chained.

is_same(image)

Check if images are the same.

Parameters:image – reference image
Return type:bool

Returns True if images are exactly the same i.e. are of same dimensions and underlying pixel data is exactly the same.

map(lookup, interpolation=None)

Map image using intensities as keys and lookup image.

Parameters:

Maps an image using lightness as key and copying color values from lookup image.

modulate(hue=0, saturation=0, lightness=0)

Modulate hue, saturation and lightness of the image

Parameters:
  • hue (float) – Hue value from -1 to 1
  • saturation (float) – Saturation value from -1 to infinity
  • lightness (float) – Lightness value from -1 to infinity

Setting any of the parameters to 0 is no-change operation. Hue parameter represents hue rotation relatively to current position. -1 means rotation by 180 degrees counter-clockwise and 1 is rotation by 180 degrees clockwise. Setting saturation to -1 completely desaturates image (makes it grayscale) while values from 0 towards infinity make it more saturated. Setting lightness to -1 makes image completely black and values from 0 towards infinity make it lighter eventually reaching pure white.

This method can be chained.

motion_blur(radius, angle=0, strength=None, bias=None)

Motion blur image

Parameters:
  • radius (float) – Blur radius in pixels
  • angle – Angle measured clockwise to X-axis

:type angle:float

Applies motion blur of given radius along in given direction measured in degrees of X-axis clockwise.

This method can be chained.

normalize()

Normalize image histogram.

oil_paint(radius)

Simulates oil painting.

Parameters:radius (float) – brush radius

Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

This method can be chained.

overlay(image, x=0, y=0, composite=None)

Overlay another image on this image.

Parameters:
  • image (pystacia.image.Image) – imaged to be overlayed
  • x (int) – x coordinate of overlay
  • y (int) – y coordinate of overlay
  • composite (pystacia.lazyenum.EnumValue) – Composition operator

Overlays given image on this image at (x, y) using composite operator. There are many popular composite operators available like lighten, darken, colorize, saturate, overlay, burn or default - over.

>>> img = read('example.jpg')
>>> img2 = read('example2.jpg')
>>> img.overlay(img2, 10, 10)

This method can be chained.

posterize(levels, dither=False)

Reduces number of colors in the image.

Parameters:
  • levels (int) – Output number of levels per channel
  • dither – Weather dithering should be performed

‘type dither: :bool:

Reduces the image to a limited number of color levels. Levels specify color levels allowed in each channel. The channel spectrum is divided equally by level. Very low values (2, 3 or 4) have the most visible effect. 1 produces 1**3 output colors, 2 produces 2**3 colors i.e. 8 and so on. Setting dither to True enables dithering.

This method can be chained.

radial_blur(angle)

Performs radial blur.

Parameters:angle (float) – Blur angle in degrees

Radial blurs image within given angle.

This method can be chained.

rescale(width=None, height=None, factor=None, filter=None, blur=1)

Rescales an image to given dimensions.

Parameters:
  • width (int) – Width of resulting image
  • height (int) – Height of resulting image
  • factor (float or tuple of float) – Zoom factor
  • filter (pystacia.lazuenym.Enums) – Scaling filter

Rescales an image to a given width and height pixels. If one of the dimensions is set to None it gets automatically computed using the other one so that the image aspect ratio is preserved. Instead of supplying width and height you can use factor parameter which is a tuple of two floats specifying scaling factor along x and y axes. You can also pass single float as factor which implies the same factor for both axes. Filter is one of possible scaling algorithms. You can choose from popular Bilinear, Cubic, Sinc, Lanczos and many more. By default it uses filter which is most adequate for the scaling you perform i.e. the one which preserves as much as possible detail and sharpness.

>>> img = read('example.jpg')
>>> img.size
(32L, 32L)
>>> img.rescale(640, 480)
>>> img.size
(640L, 480L)
>>> img.rescale(factor=.5)
>>> img.size
(320L, 240L)

This method can be chained.

resize(width, height, x=0, y=0)

Resize (crop) image to given dimensions.

Parameters:
  • width (int) – Width of resulting image
  • height (int) – Height of resulting image
  • x (int) – x origin of resized area
  • y (int) – y origin of resized area

Crops out the given x, y, width, height area of image.

>>> img = read('example.jpg')
>>> img.size
(512L, 512L)
>>> img.resize(320, 240, 10, 20)
>>> img.size()
(320L, 240L)

This method can be chained.

roll(x, y)

Roll pixels in the image.

Parameters:
  • x (int) – offset in the x-axis direction
  • y (int) – offset in the y-axis direction

Rolls pixels in the image in the left-to-right direction along x-axis and top-to-bottom direction along y-axis. Offsets can be negative to roll in the opposite direction.

This method can be chained.

rotate(angle)

Rotate an image.

Parameters:angle – angle of rotation in degrees clockwise

Rotates an image clockwise. Resulting image can be larger in size than the original. The resulting empty spaces are filled with transparent pixels.

This method can be chained

sepia(threshold=0.8, saturation=-0.4)

Sepia-tonne an image.

Parameters:
  • threshold (float) – Controls hue. Set to sepia tone by default.
  • saturation – Saturation level

:type saturation:float

Perform sepia-toning of an image. You can control hue by adjusting threshold parameter.

This method can be chained.

set_alpha(alpha)

Set alpha channel of pixels in the image.

Parameters:alpha (float) – target alpha value

Resets alpha channel of all pixels in the image to given value between 0 (transparent) and 1 (opaque).

This method can be chained.

set_color(fill)

Fill whole image with one color.

Parameters:fill (pystacia.color.Color) – desired fill color

Fills whole image with a monolithic color.

>>> img = read('example.jpg')
>>> img.fill(color.from_string('yellow'))
>>> img.get_pixel(20, 20) == color.from_string('yellow')
True

This method can be chained.

shade(azimuth=45, elevation=45, grayscale=True)

Simulate 3D shading effect.

Parameters:
  • azimuth (float) – azimuth in degrees - light direction
  • elevation (float) – elevation above image surface in degrees
  • grayscale (bool) – Whether grayscale image

Simulates 3D effect by finding edges and rendering them as raised with light coming from azimuth direction in elevation degrees above image surface. Azimuth is rotation along Z axis. By default it grayscales an image before applying an effect.

This method can be chained

sharpen(radius, strength=None, bias=None)

Sharpen an image.

Parameters:radius (float) – Radius of sharpening kernel

Performs sharpening of an image.

This method can be chained.

show(checkerboard=True, zoom=1, no_gui=False)

Display an image in GUI.

Parameters:no_gui (bool) – Skip opening interactive viewer program
Return type:str

Saves image to temporary lossless file format on a disk and sends it to default image handling program to display. Returns a path to the temporary file. You get no guarantees about life span of a file after process ended since it will be typically deleted when process ends.

size

Return a tuple of image width and height.

Return type:tuple of two int

Returns a tuple storing image width on first position and image height on second position.

>>> img = read('example.jpg')
>> img.size
(640, 480)
sketch(radius, angle=45, strength=None)

Simulate sketched image.

Parameters:
  • radius (float) – stroke length.
  • angle – angle of strokes clockwise relative to horizontal axis
  • strength (float) – effect strength (sigma)

Simulates a sketch by adding strokes into an image.

This method can be chained.

skew(offset, axis=None)

Skews an image by given offsets.

Parameters:
  • offset (int) – offset in pixels along given axis
  • axis (pystacia.lazyenum.EnumValue) – axis along which to perform skew

Skews an image along given axis. If no axis is given it defaults to X axis.

This method can be chained.

solarize(factor)

Solarizes an image.

Parameters:factor (float) – solarize factor

Applies solarization which is a color value operation similar to what can be a result of partially exposing a photograph in a darkroom. The usable range of factor is from 0 to 1 inclusive. Value of 0 is no-change operation whilst 1 produces a negative. Typically factor 0.5 produces interesting effect.

This method can be chained.

splice(x, y, width, height)

Insert bands of transparent areas into an image.

Parameters:
  • x (int) – x coordinate of splice
  • y (int) – y coordinate of splice
  • width (int) – width of splice
  • height (int) – height of splice

This method can be chained.

spread(radius)

Spread pixels in random direction.

Parameters:radius (int) – Maximal distance from original position

Applies special effect method that randomly displaces each pixel in a block defined by the radius parameter.

This method can be chained.

straighten(threshold)

Attempt to straighten image.

Parameters:threshold (float) – Separate background from foreground.

Removes skew from the image. Skew is an artifact that occurs in scanned images because of the camera being misaligned, imperfections in the scanning or surface, or simply because the paper was not placed completely flat when scanned.

This method can be chained.

swirl(angle)

Distort image with swirl effect.

Parameters:angle (float) – Angle in degrees clockwise

Swirls an image by angle clockwise. Angle can be negative resulting in distortion in opposite direction.

This method can be chained.

threshold(factor=0.5, mode=None)

Threshold image forcing pixels into black & white.

Parameters:factor (float or tuple) – Threshold factor
Patam mode:One of ‘default’, ‘white’, ‘black’

Threshold image resulting in black & white image. Factor specify lightness threshold. It’s a float ranging from 0 to 1 and defaults to 0.5. Pixels below intensity factor are renderer black and pixels above it end up white. In white mode channel pixels above factor intensity are pushed into their maximum whilst one below are left untouched. In black mode channel pixels below factor are set to 0 whilst one above are left untouched. In random mode factor should be two-element tuple that specify minimum and maximum thresholds. Thresholds are then randomly chosen for each pixel individually from given range.

total_colors

Return total number of unique colors in image

transpose()

Transpose an image.

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them 90-degrees. In other words each row of source image from top to bottom becomes a column of new image from left to right.

This method can be chained.

transverse()

Transverse an image.

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them 270-degrees.

This method can be chained.

trim(similarity=0.1, background=None)

Attempt to trim off extra background around image.

Parameters:
  • similarity (float) – Similarity factor
  • background (pystacia.color.Color) – background color, transparent by default

Removes edges that are the background color from the image. The greater similarity the more distant hues are considered the same color. Similarity of 0 means only this exact color.

This method can be chained.

type

Set or get image type.

Return type:pystacia.lazyenum.EnumValue

Popular image types include truecolor, pallete, bilevel and their matter counterparts.

>>> img = read('example.jpg')
>>> img.type == types.truecolor
wave(amplitude, length, offset=0, axis=None)

Apply wave like distortion to an image.

Parameters:
  • amplitude (int) – amplitude (A) of wave in pixels
  • length (int) – length (lambda) of wave in pixels.
  • offset – offset (phi) from initial position in pixels
  • axis (pystacia.enum.EnumValue) – axis along which to apply deformation. Defaults to x.

Applies wave like distortion to an image along chosen axis. Axis defaults to :attr:axes.x. Offset parameter is not effective as for now. Will be implemented in the feature. Resulting empty areas are filled with transparent pixels.

This method can be chained.

width

Get image width.

Return type:int

Return image width in pixels.

write(filename, format=None, compression=None, quality=None, flatten=None, background=None)

Write an image to file system.

Parameters:
  • filename (str) – file name to write to.
  • format (str) – file format
  • compression (pystacia.lazyenum.EnumValue) – compression algorithm
  • quality (int) – output quality

Saves an image to disk under given filename, format is determined from filename unless specified explicitly. The interpretation of quality parameter depends on the chosen format. E.g. for JPEG it’s a integer number between 1 (worst) and 100 (best). The default value is to choose best available compression that preserves good quality image. The details are in the ImageMagick documentation <http://www.imagemagick.org/script/ command-line-options.php#quality>.

>>> img = blank(10, 10)
>>> img.write('example.jpg')
>>> img.close()

This method can be chained.

Table Of Contents

Related Topics

This Page