gift

package
v0.0.0-...-2bc18d8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 14, 2017 License: BSD-2-Clause, MIT Imports: 7 Imported by: 0

README

GO IMAGE FILTERING TOOLKIT (GIFT)

GoDoc Build Status Coverage Status

Package gift provides a set of useful image processing filters.

Pure Go. No external dependencies outside of the Go standard library.

INSTALLATION / UPDATING
go get -u github.com/disintegration/gift
DOCUMENTATION

http://godoc.org/github.com/disintegration/gift

QUICK START
// 1. Create a new GIFT filter list and add some filters:
g := gift.New(
    gift.Resize(800, 0, gift.LanczosResampling),
    gift.UnsharpMask(1.0, 1.0, 0.0),
)

// 2. Create a new image of the corresponding size.
// dst is a new target image, src is the original image
dst := image.NewRGBA(g.Bounds(src.Bounds()))

// 3. Use Draw func to apply the filters to src and store the result in dst:
g.Draw(dst, src)
USAGE

To create a sequence of filters, the New function is used:

g := gift.New(
   gift.Grayscale(),
   gift.Contrast(10),
)

Filters also can be added using the Add method:

g.Add(GaussianBlur(2)) 

The Bounds method takes the bounds of the source image and returns appropriate bounds for the destination image to fit the result (for example, after using Resize or Rotate filters).

dst := image.NewRGBA(g.Bounds(src.Bounds()))

There are two methods available to apply these filters to an image:

  • Draw applies all the added filters to the src image and outputs the result to the dst image starting from the top-left corner (Min point).
g.Draw(dst, src)
  • DrawAt provides more control. It outputs the filtered src image to the dst image at the specified position using the specified image composition operator. This example is equivalent to the previous:
g.DrawAt(dst, src, dst.Bounds().Min, gift.CopyOperator)

Two image composition operators are supported by now:

  • CopyOperator - Replaces pixels of the dst image with pixels of the filtered src image. This mode is used by the Draw method.
  • OverOperator - Places the filtered src image on top of the dst image. This mode makes sence if the filtered src image has transparent areas.

Empty filter list can be used to create a copy of an image or to paste one image to another. For example:

// Create a new image with dimensions of bgImage
dstImage := image.NewNRGBA(bgImage.Bounds())
// Copy the bgImage to the dstImage.
gift.New().Draw(dstImage, bgImage)
// Draw the fgImage over the dstImage at the (100, 100) position.
gift.New().DrawAt(dstImage, fgImage, image.Pt(100, 100), gift.OverOperator)
SUPPORTED FILTERS
  • Transformations

    • Crop(rect image.Rectangle)
    • CropToSize(width, height int, anchor Anchor)
    • FlipHorizontal()
    • FlipVertical()
    • Resize(width, height int, resampling Resampling)
    • ResizeToFill(width, height int, resampling Resampling, anchor Anchor)
    • ResizeToFit(width, height int, resampling Resampling)
    • Rotate(angle float32, backgroundColor color.Color, interpolation Interpolation)
    • Rotate180()
    • Rotate270()
    • Rotate90()
    • Transpose()
    • Transverse()
  • Adjustments & effects

    • Brightness(percentage float32)
    • ColorBalance(percentageRed, percentageGreen, percentageBlue float32)
    • ColorFunc(fn func(r0, g0, b0, a0 float32) (r, g, b, a float32))
    • Colorize(hue, saturation, percentage float32)
    • ColorspaceLinearToSRGB()
    • ColorspaceSRGBToLinear()
    • Contrast(percentage float32)
    • Convolution(kernel []float32, normalize, alpha, abs bool, delta float32)
    • Gamma(gamma float32)
    • GaussianBlur(sigma float32)
    • Grayscale()
    • Hue(shift float32)
    • Invert()
    • Maximum(ksize int, disk bool)
    • Mean(ksize int, disk bool)
    • Median(ksize int, disk bool)
    • Minimum(ksize int, disk bool)
    • Pixelate(size int)
    • Saturation(percentage float32)
    • Sepia(percentage float32)
    • Sigmoid(midpoint, factor float32)
    • Sobel()
    • UnsharpMask(sigma, amount, thresold float32)
FILTER EXAMPLES
Resize using lanczos resampling
gift.Resize(200, 0, gift.LanczosResampling)
Original image Filtered image
original filtered
Resize using linear resampling
gift.Resize(200, 0, gift.LinearResampling)
Original image Filtered image
original filtered
Resize to fit 160x160px bounding box
gift.ResizeToFit(160, 160, gift.LanczosResampling)
Original image Filtered image
original filtered
Resize to fill 160x160px rectangle, anchor: center
gift.ResizeToFill(160, 160, gift.LanczosResampling, gift.CenterAnchor)
Original image Filtered image
original filtered
Crop 90, 90 - 250, 250
gift.Crop(image.Rect(90, 90, 250, 250))
Original image Filtered image
original filtered
Crop to size 160x160px, anchor: center
gift.CropToSize(160, 160, gift.CenterAnchor)
Original image Filtered image
original filtered
Rotate 90 degrees
gift.Rotate90()
Original image Filtered image
original filtered
Rotate 180 degrees
gift.Rotate180()
Original image Filtered image
original filtered
Rotate 270 degrees
gift.Rotate270()
Original image Filtered image
original filtered
Rotate 30 degrees, white background, cubic interpolation
gift.Rotate(30, color.White, gift.CubicInterpolation)
Original image Filtered image
original filtered
Flip horizontal
gift.FlipHorizontal()
Original image Filtered image
original filtered
Flip vertical
gift.FlipVertical()
Original image Filtered image
original filtered
Transpose
gift.Transpose()
Original image Filtered image
original filtered
Transverse
gift.Transverse()
Original image Filtered image
original filtered
Contrast +30%
gift.Contrast(30)
Original image Filtered image
original filtered
Contrast -30%
gift.Contrast(-30)
Original image Filtered image
original filtered
Brightness +30%
gift.Brightness(30)
Original image Filtered image
original filtered
Brightness -30%
gift.Brightness(-30)
Original image Filtered image
original filtered
Saturation +50%
gift.Saturation(50)
Original image Filtered image
original filtered
Saturation -50%
gift.Saturation(-50)
Original image Filtered image
original filtered
Hue +45
gift.Hue(45)
Original image Filtered image
original filtered
Hue -45
gift.Hue(-45)
Original image Filtered image
original filtered
Sigmoid 0.5, 5.0
gift.Sigmoid(0.5, 5.0)
Original image Filtered image
original filtered
Gamma correction = 0.5
gift.Gamma(0.5)
Original image Filtered image
original filtered
Gamma correction = 1.5
gift.Gamma(1.5)
Original image Filtered image
original filtered
Gaussian blur, sigma=1.0
gift.GaussianBlur(1.0)
Original image Filtered image
original filtered
Unsharp mask, sigma=1.0, amount=1.5, thresold=0.0
gift.UnsharpMask(1.0, 1.5, 0.0)
Original image Filtered image
original filtered
Grayscale
gift.Grayscale()
Original image Filtered image
original filtered
Sepia, 100%
gift.Sepia(100)
Original image Filtered image
original filtered
Invert
gift.Invert()
Original image Filtered image
original filtered
Colorize, blue, saturation=50%
gift.Colorize(240, 50, 100)
Original image Filtered image
original filtered
Color balance, +20% red, -20% green
gift.ColorBalance(20, -20, 0)
Original image Filtered image
original filtered
Color function
gift.ColorFunc(
    func(r0, g0, b0, a0 float32) (r, g, b, a float32) {
        r = 1 - r0   // invert the red channel
        g = g0 + 0.1 // shift the green channel by 0.1
        b = 0        // set the blue channel to 0
        a = a0       // preserve the alpha channel
        return
    },
)
Original image Filtered image
original filtered
Local mean, disc shape, size=5
gift.Mean(5, true)
Original image Filtered image
original filtered
Local median, disc shape, size=5
gift.Median(5, true)
Original image Filtered image
original filtered
Local minimum, disc shape, size=5
gift.Minimum(5, true)
Original image Filtered image
original filtered
Local maximum, disc shape, size=5
gift.Maximum(5, true)
Original image Filtered image
original filtered
Pixelate, size=5
gift.Pixelate(5)
Original image Filtered image
original filtered
Convolution matrix - Emboss
gift.Convolution(
    []float32{
        -1, -1, 0,
        -1, 1, 1,
        0, 1, 1,
    },
    false, false, false, 0.0,
)
Original image Filtered image
original filtered
Convolution matrix - Edge detection
gift.Convolution(
    []float32{
        -1, -1, -1,
        -1, 8, -1,
        -1, -1, -1,
    },
    false, false, false, 0.0,
)
Original image Filtered image
original filtered
Sobel operator
gift.Sobel()
Original image Filtered image
original filtered

Documentation

Overview

Package gift provides a set of useful image processing filters.

Basic usage:

// 1. Create a new GIFT and add some filters:

g := gift.New(
    gift.Resize(800, 0, gift.LanczosResampling),
    gift.UnsharpMask(1.0, 1.0, 0.0),
)

// 2. Create a new image of the corresponding size.
// dst is a new target image, src is the original image

dst := image.NewRGBA(g.Bounds(src.Bounds()))

// 3. Use Draw func to apply the filters to src and store the result in dst:

g.Draw(dst, src)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Anchor

type Anchor int

Anchor is the anchor point for image cropping.

const (
	CenterAnchor Anchor = iota
	TopLeftAnchor
	TopAnchor
	TopRightAnchor
	LeftAnchor
	RightAnchor
	BottomLeftAnchor
	BottomAnchor
	BottomRightAnchor
)

type Filter

type Filter interface {
	// Draw applies the filter to the src image and outputs the result to the dst image.
	Draw(dst draw.Image, src image.Image, options *Options)
	// Bounds calculates the appropriate bounds of an image after applying the filter.
	Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle)
}

Filter is an image processing filter.

func Brightness

func Brightness(percentage float32) Filter

Brightness creates a filter that changes the brightness of an image. The percentage parameter must be in range (-100, 100). The percentage = 0 gives the original image. The percentage = -100 gives solid black image. The percentage = 100 gives solid white image.

func ColorBalance

func ColorBalance(percentageRed, percentageGreen, percentageBlue float32) Filter

ColorBalance creates a filter that changes the color balance of an image. The percentage parameters for each color channel (red, green, blue) must be in range (-100, 500).

Example:

g := gift.New(
	gift.ColorBalance(20, -20, 0), // +20% red, -20% green
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func ColorFunc

func ColorFunc(fn func(r0, g0, b0, a0 float32) (r, g, b, a float32)) Filter

ColorFunc creates a filter that changes the colors of an image using custom function. The fn parameter specifies a function that takes red, green, blue and alpha channels of a pixel as float32 values in range (0, 1) and returns the modified channel values.

Example:

g := gift.New(
	gift.ColorFunc(
		func(r0, g0, b0, a0 float32) (r, g, b, a float32) {
			r = 1 - r0   // invert the red channel
			g = g0 + 0.1 // shift the green channel by 0.1
			b = 0        // set the blue channel to 0
			a = a0       // preserve the alpha channel
			return
		},
	),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func Colorize

func Colorize(hue, saturation, percentage float32) Filter

Colorize creates a filter that produces a colorized version of an image. The hue parameter is the angle on the color wheel, typically in range (0, 360). The saturation parameter must be in range (0, 100). The percentage parameter specifies the strength of the effect, it must be in range (0, 100).

Example:

g := gift.New(
	gift.Colorize(240, 50, 100), // blue colorization, 50% saturation
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func ColorspaceLinearToSRGB

func ColorspaceLinearToSRGB() Filter

ColorspaceLinearToSRGB creates a filter that converts the colors of an image from linear RGB to sRGB.

func ColorspaceSRGBToLinear

func ColorspaceSRGBToLinear() Filter

ColorspaceSRGBToLinear creates a filter that converts the colors of an image from sRGB to linear RGB.

func Contrast

func Contrast(percentage float32) Filter

Contrast creates a filter that changes the contrast of an image. The percentage parameter must be in range (-100, 100). The percentage = 0 gives the original image. The percentage = -100 gives solid grey image. The percentage = 100 gives an overcontrasted image.

func Convolution

func Convolution(kernel []float32, normalize, alpha, abs bool, delta float32) Filter

Convolution creates a filter that applies a square convolution kernel to an image. The length of the kernel slice must be the square of an odd kernel size (e.g. 9 for 3x3 kernel, 25 for 5x5 kernel). Excessive slice members will be ignored. If normalize parameter is true, the kernel will be normalized before applying the filter. If alpha parameter is true, the alpha component of color will be filtered too. If abs parameter is true, absolute values of color components will be taken after doing calculations. If delta parameter is not zero, this value will be added to the filtered pixels.

Example:

// Apply the emboss filter to an image.
g := gift.New(
	gift.Convolution(
		[]float32{
			-1, -1, 0,
			-1, 1, 1,
			0, 1, 1,
		},
		false, false, false, 0,
	),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func Crop

func Crop(rect image.Rectangle) Filter

Crop creates a filter that crops the specified rectangular region from an image.

Example:

g := gift.New(
	gift.Crop(image.Rect(100, 100, 200, 200)),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func CropToSize

func CropToSize(width, height int, anchor Anchor) Filter

CropToSize creates a filter that crops an image to the specified size using the specified anchor point.

func FlipHorizontal

func FlipHorizontal() Filter

FlipHorizontal creates a filter that flips an image horizontally.

func FlipVertical

func FlipVertical() Filter

FlipVertical creates a filter that flips an image vertically.

func Gamma

func Gamma(gamma float32) Filter

Gamma creates a filter that performs a gamma correction on an image. The gamma parameter must be positive. Gamma = 1.0 gives the original image. Gamma less than 1.0 darkens the image and gamma greater than 1.0 lightens it.

func GaussianBlur

func GaussianBlur(sigma float32) Filter

GaussianBlur creates a filter that applies a gaussian blur to an image. The sigma parameter must be positive and indicates how much the image will be blurred. Blur affected radius roughly equals 3 * sigma.

Example:

g := gift.New(
	gift.GaussianBlur(1.5),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func Grayscale

func Grayscale() Filter

Grayscale creates a filter that produces a grayscale version of an image.

func Hue

func Hue(shift float32) Filter

Hue creates a filter that rotates the hue of an image. The shift parameter is the hue angle shift, typically in range (-180, 180). The shift = 0 gives the original image.

func Invert

func Invert() Filter

Invert creates a filter that negates the colors of an image.

func Maximum

func Maximum(ksize int, disk bool) Filter

Maximum creates a local maximum image filter. Picks a maximum value per channel in neighborhood for each pixel. The ksize parameter is the kernel size. It must be an odd positive integer (for example: 3, 5, 7). If the disk parameter is true, a disk-shaped neighborhood will be used instead of a square neighborhood.

func Mean

func Mean(ksize int, disk bool) Filter

Mean creates a local mean image filter. Takes an average across a neighborhood for each pixel. The ksize parameter is the kernel size. It must be an odd positive integer (for example: 3, 5, 7). If the disk parameter is true, a disk-shaped neighborhood will be used instead of a square neighborhood.

func Median

func Median(ksize int, disk bool) Filter

Median creates a median image filter. Picks a median value per channel in neighborhood for each pixel. The ksize parameter is the kernel size. It must be an odd positive integer (for example: 3, 5, 7). If the disk parameter is true, a disk-shaped neighborhood will be used instead of a square neighborhood.

func Minimum

func Minimum(ksize int, disk bool) Filter

Minimum creates a local minimum image filter. Picks a minimum value per channel in neighborhood for each pixel. The ksize parameter is the kernel size. It must be an odd positive integer (for example: 3, 5, 7). If the disk parameter is true, a disk-shaped neighborhood will be used instead of a square neighborhood.

func Pixelate

func Pixelate(size int) Filter

Pixelate creates a filter that applies a pixelation effect to an image.

func Resize

func Resize(width, height int, resampling Resampling) Filter

Resize creates a filter that resizes an image to the specified width and height using the specified resampling. If one of width or height is 0, the image aspect ratio is preserved. Supported resampling parameters: NearestNeighborResampling, BoxResampling, LinearResampling, CubicResampling, LanczosResampling.

Example:

// Resize the src image to width=300 preserving the aspect ratio.
g := gift.New(
	gift.Resize(300, 0, gift.LanczosResampling),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func ResizeToFill

func ResizeToFill(width, height int, resampling Resampling, anchor Anchor) Filter

ResizeToFill creates a filter that resizes an image to the smallest possible size that will cover the specified dimensions, then crops the resized image to the specified dimensions using the specified anchor point. Supported resampling parameters: NearestNeighborResampling, BoxResampling, LinearResampling, CubicResampling, LanczosResampling.

func ResizeToFit

func ResizeToFit(width, height int, resampling Resampling) Filter

ResizeToFit creates a filter that resizes an image to fit within the specified dimensions while preserving the aspect ratio. Supported resampling parameters: NearestNeighborResampling, BoxResampling, LinearResampling, CubicResampling, LanczosResampling.

func Rotate

func Rotate(angle float32, backgroundColor color.Color, interpolation Interpolation) Filter

Rotate creates a filter that rotates an image by the given angle counter-clockwise. The angle parameter is the rotation angle in degrees. The backgroundColor parameter specifies the color of the uncovered zone after the rotation. The interpolation parameter specifies the interpolation method. Supported interpolation methods: NearestNeighborInterpolation, LinearInterpolation, CubicInterpolation.

Example:

g := gift.New(
	gift.Rotate(45, color.Black, gift.LinearInterpolation),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func Rotate180

func Rotate180() Filter

Rotate180 creates a filter that rotates an image 180 degrees counter-clockwise.

func Rotate270

func Rotate270() Filter

Rotate270 creates a filter that rotates an image 270 degrees counter-clockwise.

func Rotate90

func Rotate90() Filter

Rotate90 creates a filter that rotates an image 90 degrees counter-clockwise.

func Saturation

func Saturation(percentage float32) Filter

Saturation creates a filter that changes the saturation of an image. The percentage parameter must be in range (-100, 500). The percentage = 0 gives the original image.

func Sepia

func Sepia(percentage float32) Filter

Sepia creates a filter that produces a sepia-toned version of an image. The percentage parameter specifies how much the image should be adjusted. It must be in the range (0, 100)

Example:

g := gift.New(
	gift.Sepia(100),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func Sigmoid

func Sigmoid(midpoint, factor float32) Filter

Sigmoid creates a filter that changes the contrast of an image using a sigmoidal function and returns the adjusted image. It's a non-linear contrast change useful for photo adjustments as it preserves highlight and shadow detail. The midpoint parameter is the midpoint of contrast that must be between 0 and 1, typically 0.5. The factor parameter indicates how much to increase or decrease the contrast, typically in range (-10, 10). If the factor parameter is positive the image contrast is increased otherwise the contrast is decreased.

Example:

g := gift.New(
	gift.Sigmoid(0.5, 3.0),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

func Sobel

func Sobel() Filter

Sobel creates a filter that applies a sobel operator to an image.

func Transpose

func Transpose() Filter

Transpose creates a filter that flips an image horizontally and rotates 90 degrees counter-clockwise.

func Transverse

func Transverse() Filter

Transverse creates a filter that flips an image vertically and rotates 90 degrees counter-clockwise.

func UnsharpMask

func UnsharpMask(sigma, amount, thresold float32) Filter

UnsharpMask creates a filter that sharpens an image. The sigma parameter is used in a gaussian function and affects the radius of effect. Sigma must be positive. Sharpen radius roughly equals 3 * sigma. The amount parameter controls how much darker and how much lighter the edge borders become. Typically between 0.5 and 1.5. The thresold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.

Example:

g := gift.New(
	gift.UnsharpMask(1.0, 1.0, 0.0),
)
dst := image.NewRGBA(g.Bounds(src.Bounds()))
g.Draw(dst, src)

type GIFT

type GIFT struct {
	Filters []Filter
	Options Options
}

GIFT implements a list of filters that can be applied to an image at once.

func New

func New(filters ...Filter) *GIFT

New creates a new instance of the filter toolkit and initializes it with the given list of filters.

func (*GIFT) Add

func (g *GIFT) Add(filters ...Filter)

Add appends the given filters to the list of filters.

func (*GIFT) Bounds

func (g *GIFT) Bounds(srcBounds image.Rectangle) (dstBounds image.Rectangle)

Bounds calculates the appropriate bounds for the result image after applying all the added filters. Parameter srcBounds is the bounds of the source image.

Example:

src := image.NewRGBA(image.Rect(0, 0, 100, 200))
g := gift.New(gift.Rotate90())

// calculate image bounds after applying rotation and create a new image of that size.
dst := image.NewRGBA(g.Bounds(src.Bounds())) // dst bounds: (0, 0, 200, 100)

func (*GIFT) Draw

func (g *GIFT) Draw(dst draw.Image, src image.Image)

Draw applies all the added filters to the src image and outputs the result to the dst image.

func (*GIFT) DrawAt

func (g *GIFT) DrawAt(dst draw.Image, src image.Image, pt image.Point, op Operator)

DrawAt applies all the added filters to the src image and outputs the result to the dst image at the specified position pt using the specified composition operator op.

func (*GIFT) Empty

func (g *GIFT) Empty()

Empty removes all the filters from the list.

func (*GIFT) Parallelization

func (g *GIFT) Parallelization() bool

Parallelization returns the current state of parallelization option.

func (*GIFT) SetParallelization

func (g *GIFT) SetParallelization(isEnabled bool)

SetParallelization enables or disables faster image processing using parallel goroutines. Parallelization is enabled by default. To achieve maximum performance, make sure to allow Go to utilize all CPU cores:

runtime.GOMAXPROCS(runtime.NumCPU())

type Interpolation

type Interpolation int

Interpolation is an interpolation algorithm used for image transformation.

const (
	// Nearest Neighbor interpolation algorithm
	NearestNeighborInterpolation Interpolation = iota
	// Linear interpolation algorithm
	LinearInterpolation
	// Cubic interpolation algorithm
	CubicInterpolation
)

type Operator

type Operator int

Operator is an image composition operator.

const (
	CopyOperator Operator = iota
	OverOperator
)

type Options

type Options struct {
	Parallelization bool
}

Options is the parameters passed to image processing filters.

type Resampling

type Resampling interface {
	Support() float32
	Kernel(float32) float32
}

Resampling is an interpolation algorithm used for image resizing.

var BoxResampling Resampling

Box resampling filter.

var CubicResampling Resampling

Cubic resampling filter (Catmull-Rom).

var LanczosResampling Resampling

Lanczos resampling filter (3 lobes).

var LinearResampling Resampling

Linear resampling filter.

var NearestNeighborResampling Resampling

Nearest neighbor resampling filter.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL