gift

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2017 License: MIT Imports: 7 Imported by: 2

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, 1, 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 the bgImage.
dstImage := image.NewRGBA(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()
    • Threshold(percentage float32)
    • UnsharpMask(sigma, amount, threshold float32)
FILTER EXAMPLES

The original image:

Resulting images after applying some of the filters:

name / result name / result name / result name / result
resize crop_to_size rotate_180 rotate_30
brightness_increase brightness_decrease contrast_increase contrast_decrease
saturation_increase saturation_decrease gamma_1.5 gamma_0.5
gaussian_blur unsharp_mask sigmoid pixelate
colorize grayscale sepia invert
mean median minimum maximum
hue_rotate color_balance color_func convolution_emboss

Here's the code that produces the above images:

package main

import (
	"image"
	"image/color"
	"image/png"
	"log"
	"os"

	"github.com/disintegration/gift"
)

func main() {
	src := loadImage("testdata/src.png")

	filters := map[string]gift.Filter{
		"resize":               gift.Resize(100, 0, gift.LanczosResampling),
		"crop_to_size":         gift.CropToSize(100, 100, gift.LeftAnchor),
		"rotate_180":           gift.Rotate180(),
		"rotate_30":            gift.Rotate(30, color.Transparent, gift.CubicInterpolation),
		"brightness_increase":  gift.Brightness(30),
		"brightness_decrease":  gift.Brightness(-30),
		"contrast_increase":    gift.Contrast(30),
		"contrast_decrease":    gift.Contrast(-30),
		"saturation_increase":  gift.Saturation(50),
		"saturation_decrease":  gift.Saturation(-50),
		"gamma_1.5":            gift.Gamma(1.5),
		"gamma_0.5":            gift.Gamma(0.5),
		"gaussian_blur":        gift.GaussianBlur(1),
		"unsharp_mask":         gift.UnsharpMask(1, 1, 0),
		"sigmoid":              gift.Sigmoid(0.5, 7),
		"pixelate":             gift.Pixelate(5),
		"colorize":             gift.Colorize(240, 50, 100),
		"grayscale":            gift.Grayscale(),
		"sepia":                gift.Sepia(100),
		"invert":               gift.Invert(),
		"mean":                 gift.Mean(5, true),
		"median":               gift.Median(5, true),
		"minimum":              gift.Minimum(5, true),
		"maximum":              gift.Maximum(5, true),
		"hue_rotate":           gift.Hue(45),
		"color_balance":        gift.ColorBalance(10, -10, -10),
		"color_func": 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
			},
		),
		"convolution_emboss": gift.Convolution(
			[]float32{
				-1, -1, 0,
				-1, 1, 1,
				0, 1, 1,
			},
			false, false, false, 0.0,
		),
	}

	for name, filter := range filters {
		g := gift.New(filter)
		dst := image.NewNRGBA(g.Bounds(src.Bounds()))
		g.Draw(dst, src)
		saveImage("testdata/dst_"+name+".png", dst)
	}
}

func loadImage(filename string) image.Image {
	f, err := os.Open(filename)
	if err != nil {
		log.Fatalf("os.Open failed: %v", err)
	}
	img, _, err := image.Decode(f)
	if err != nil {
		log.Fatalf("image.Decode failed: %v", err)
	}
	return img
}

func saveImage(filename string, img image.Image) {
	f, err := os.Create(filename)
	if err != nil {
		log.Fatalf("os.Create failed: %v", err)
	}
	err = png.Encode(f, img)
	if err != nil {
		log.Fatalf("png.Encode failed: %v", err)
	}
}

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, 1, 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
)

Anchor point positions.

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 gives the original image. Gamma less than 1 darkens the image and gamma greater than 1 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, 5),
)
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 Threshold added in v1.1.0

func Threshold(percentage float32) Filter

Threshold creates a filter that applies black/white thresholding to the image. The percentage parameter must be in range (0, 100).

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, threshold 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 threshold parameter controls the minimum brightness change that will be sharpened. Typically between 0 and 0.05.

Example:

g := gift.New(
	gift.UnsharpMask(1, 1, 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.

type Interpolation

type Interpolation int

Interpolation is an interpolation algorithm used for image transformation.

const (
	// NearestNeighborInterpolation is a nearest-neighbor interpolation algorithm.
	NearestNeighborInterpolation Interpolation = iota
	// LinearInterpolation is a bilinear interpolation algorithm.
	LinearInterpolation
	// CubicInterpolation is a bicubic interpolation algorithm.
	CubicInterpolation
)

type Operator

type Operator int

Operator is an image composition operator.

const (
	CopyOperator Operator = iota
	OverOperator
)

Composition operators.

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

BoxResampling is a box resampling filter (average of surrounding pixels).

var CubicResampling Resampling

CubicResampling is a bicubic resampling filter (Catmull-Rom).

var LanczosResampling Resampling

LanczosResampling is a Lanczos resampling filter (3 lobes).

var LinearResampling Resampling

LinearResampling is a bilinear resampling filter.

var NearestNeighborResampling Resampling

NearestNeighborResampling is a nearest neighbor resampling filter.

Jump to

Keyboard shortcuts

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